Answer to Question #188198 in Java | JSP | JSF for Hamza

Question #188198

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.


1
Expert's answer
2021-05-02T17:48:08-0400

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.


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS