Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

XOR operator issue  RSS feed

 
Sen George
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import static java.lang.System.out;

public class test_operand {

public static void main(String[] args) {

boolean b1 = false;
boolean b2 = true;

out.println(" " + (false ^ true));
out.println(" " + (b1 ^ b2));
}
}

The first output gives the intended result true. Why is it that the second output gives false?
 
John Dell'Oso
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reason:

Because that's the way an exclusive OR works. If both operands are true and false, then the result is true. If both operands are the same (either false or true), then the result is false.

There's no difference between your first and second output statements. In the first statement you are using the Java keywords of false and true and in the second statement, you are setting fields to each of these reserved key words (values).

Do a little research on boolean logic and truth tables.


Regards,
JD
[ August 03, 2007: Message edited by: John Dell'Oso ]
 
Remko Strating
Ranch Hand
Posts: 893
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The second output is also true. The reason is already described by John Dell'Oso.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Sen George:
... Why is it that the second output gives false?

Not in my Java.
 
John Dell'Oso
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good point Marc, Whoa .. it's the early hours of the morn' here in Oz. Not in my Java as well. Both output statements are true.

Cheers,
JD
 
Gavin Tranter
Ranch Hand
Posts: 333
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
however that is not what the original poster was asking, he asked:
Why is it that the second output gives false?


I wonder what would happen if you did something like:


then printed out resultXOR
[ August 06, 2007: Message edited by: Gavin Tranter ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!