Skip to content
Advertisement

Are booleans implicitly true?

I’m a bit confused on this bit of code.

My professor explained that the output will always be true but I’m confused on why.

I changed the boolean to both true and false but the output is always true and I’m having a hard time explaining the logic behind it. I assumed that since a false && true will always represent true, then the true and false cancels out like algebra? Apologies if I’m confusing you guys, I’m quite confused myself!

public class TestProgram {

    public static void main(String args[]) {
        boolean answer = false;
        boolean output = (answer && true) ^ !answer;
        System.out.println("output = " + output);
    }
}

Advertisement

Answer

This code for calculating output means:

(answer AND true) XOR (NOT answer)

Therefore, when answer is true:

(answer AND true) XOR (NOT answer)
 = (true AND true) XOR (NOT true)
 = true XOR false
 = true

And when answer is false:

(answer AND true) XOR (NOT answer)
 = (false AND true) XOR (NOT false)
 = false XOR true
 = true
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement