Suppose that you have the following declaration:
int j = 0;
The output of the statement:
if ((8 > 4) || (j++ == 7))
System.out.println("j = " + j); is:
j = 0
while the output of the statement:
if ((8 > 4) | (j++ == 7))
System.out.println("j = " + j);
is:
j = 1
Explain why.
The double pipe for OR is also referred to "short-circuit". In the first declaration that uses || it will mean if condition 1 is true(8>4) it won't check condition 2 (j++ == 7) so the program will not bother checking it and thus it will proceed to execute the code that should be executed if it evaluated to true. 8 being greater than 4, the second condition is skipped and thus proceeds to display that j=0.
On the second condition that uses single |, the second condition must be checked too even if the first condition is true. Therefore the j++ == 7 statement will increment j to 1, however testing for equality of 1 and 7 will evaluate to false. The program will proceed to executing the block of code under the if. Since j had been incremented the value will display as 1.
Comments
Leave a comment