Search code examples
javaif-statementprefixpostfix-notation

prefix and postfix increments while comparing variables


could someone explain why this code output is

not equals
not equals 2

in the first if statement it seems that a = 0 b/c is a postfix increment; therefore a will not increase untile next line; however, the two a's are not equal why? and in the second if when I run the debugger the value of a is 2, but the test is false, why?

public static void main (String[] args)
   {
       int a = 0;
       if (a++ == a++) {
           System.out.println("equals");
       } else {
           System.out.println("not equals");
       }

       if (++a == 2) {
           System.out.println("equals 2");
       } else {
           System.out.println("not equals 2");
       }

   } 

Solution

  • a++(post increment) would increment a first and then assign it to the variable. in your first case

    (a++==a++) in the first post increment a value would be incremented by 1 first but not assigned yet, but when it reaches the second a++, now the a value is assigned and you are incrementing it again.

    for example

    if say a=0;
    
    (a++==a++) would be (0==1)
    

    so now the a value would be 2 after evaluating the if.

    for your second case

    (++a==2) here a would be incremented to 3 , (3==2) which is false thus the else if executed