Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does this output 5?

My understanding is x++ == 0 runs first. But x is still -1 at the point of calculating (y = y++ / x) == 0? Otherwise it will be dividing by zero. I thought the output will be -5 but eclipse says 5. I’m going crazy.

public static void main(String[] args){
        
    int x = -1;
    int y = 5;
    boolean s = (x++ == 0) && ((y = y++ / x) == 0);
    System.out.println(x + y);
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

((y = y++ / x) == 0) is never evaluated since && is a short circuited logical AND operator, and (x++ == 0) is false, so s is evaluated to false without evaluating the second operand.

Hence, the output is

x + y

0 + 5 == 5

Note that if you change the && operator to &, which is not short circuited, the second operand will be evaluated, which will lead to division by 0 and ArithmeticException. x is incremented when the first operand is evaluated, so once the second operand is evaluated, x is already 0.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading