Java – why is the output different in the case of \ u0026 \ u0026, &, |?
•
Java
This is a code snippet
Can you explain why the output changes?
1)
public static ShortCkt { public static void main(String args[]) { int i = 0; boolean t = true; boolean f = false,b; b = (t && ((i++) == 0)); b = (f && ((i+=2) > 0)); System.out.println(i); } }
The output in this case is 1
2)
public static ShortCkt { public static void main(String args[]) { int i = 0; boolean t = true; boolean f = false,b; b = (t & ((i++) == 0)); b = (f & ((i+=2) > 0)); System.out.println(i); } }
The output in this case is 3
3)
public static ShortCkt { public static void main(String args[]) { int i = 0; boolean t = true; boolean f = false,b; b = (t || ((i++) == 0)); b = (f || ((i+=2) > 0)); System.out.println(i); } }
The output in this case is 2
4)
public static ShortCkt { public static void main(String args[]) { int i = 0; boolean t = true; boolean f = false,b; b = (t | ((i++) == 0)); b = (f | ((i+=2) > 0)); System.out.println(i); } }
The output in this case is 3
Solution
As in C / C + + & & is evaluated as "lazy" rather than & not
If a is false then & & B will return false without even evaluating B
The same applies to | B: if the first operand A is true, the entire expression is true, and the second operand B is never evaluated For | however, both a and B will be evaluated
If there are side effects when using & & and / or (or |), as shown in your example
Sidenote: few Java programmers know that ^ (XOR) also applies to Boolean values (a ^ ^ version does not exist just because it is redundant.)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码