2013年12月10日星期二

SCJP exam one : Bitwise XOR operator with boolean values ??

Given:
3. public class Spock {
4. public static void main(String[] args) {
5. Long tail = 2000L;
6. Long distance = 1999L;
7. Long story = 1000L;
8. if((tail > distance) ^ ((story * 2) == tail))
9. System.out.print("1");
10. if((distance + 1 != tail) ^ ((story * 2) == distance))
11. System.out.print("2");
12. }
13. }

What is the result?
A. 1
B. 2
C. 12
D. Compilation fails.
E. No output is produced.
F. An exception is thrown at runtime.

If individual output : System.out.println ((tail> distance) ^ ((story * 2) == distance)); result is true.
Why not output in line 9 1 it?
please many experts advise. This is very confusing , is not very good . Thank you very much .
------ Solution ---------------------------------------- ----
tail> distance this get is Boolean, and C is different, this is a true or false value JAVA, C did not like that turn into 1,0 for computing , so the first how are false in an if . Why can not also get false operation without error, I do not know.
------ Solution ---------------------------------------- ----
simply ignore 1F

true ^ true is equivalent to 1 ^ 1 , the same on both sides , get 0, false
------ Solution ---------- ----------------------------------
^ is the XOR operator only when one of the two ends true one is false, the expression true ^ false or false ^ true will be true, the other is false.
------ For reference only -------------------------------------- -
I'm sorry I'm sorry , that I entered the wrong test .
result of wrong,
((tail> distance) ^ ((story * 2) == tail)) value is false;

lose the wrong post questions become :
If individual output : System.out.println ((tail> distance) ^ ((story * 2) == distance )); result is true.

title in accordance with the data to be absolutely no problem.


------ For reference only ---------------------------------- -----
(tail> distance): true
((story * 2) == tail): true
true ^ true: false
The first one does not output ;
(distance + 1 = tail!): false
((story * 2) == distance): false
false ^ false: false
The second is not output .
XOR , 1, false ^ false: false
2, true ^ true: false
3, false ^ true: true
4, true ^ false: true

没有评论:

发表评论