0

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);
    }
}
user207421
  • 305,947
  • 44
  • 307
  • 483
  • 3
    It doesn't matter what answer is, true XOR false == false XOR true == true. – tkausl Oct 17 '21 at 01:09
  • Does this answer your question? [Creating a "logical exclusive or" operator in Java](https://stackoverflow.com/questions/726652/creating-a-logical-exclusive-or-operator-in-java) – sukalogika Oct 17 '21 at 01:21

2 Answers2

2

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
Jeremy Hunt
  • 701
  • 3
  • 10
0

I don't know which part is confusing you but I will try to explain your code line by line:

  1. boolean answer = false; // answer is false or 0

  2. 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:

  1. true ^ true = false
  2. true ^ false = true
  3. false ^ true = true
  4. false ^ false = false
user207421
  • 305,947
  • 44
  • 307
  • 483
Chipo Hamayobe
  • 877
  • 11
  • 13