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); } }
CodePudding user response:
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
CodePudding user response:
I don't know which part is confusing you but I will try to explain your code line by line:
boolean answer = false; // answer is false or 0
boolean output = (answer && true) ^ !answer;
a.
(answer && true) = false or 0
because answer is 0. And returns true or 1 ONLY if all conditions (2 in this case) are true.b.
!answer = true
because the negation of answer (false or ) is true or 1.c.
^
is a bitwise exclusive or operator: meaning a bit by bit comparison between two parameters is performed. The result for a bit position is 1 if one or the other (but not both) of the corresponding bits in the operands is 1.
For example:
00110 ^ 00011 = 00101
So in your case, you have: false ^ true = 0 ^ 1 = 1
(or true) because only one of the corresponding bits is 1.
NOTE that:
true ^ true
= falsetrue ^ false
= truefalse ^ true
= truefalse ^ false
= false