0

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");
       }

   } 
Jens Erat
  • 37,523
  • 16
  • 80
  • 96
miatech
  • 2,150
  • 8
  • 41
  • 78
  • possible duplicate of [Why java statement evaluation is happening like these ?](http://stackoverflow.com/questions/12036481/why-java-statement-evaluation-is-happening-like-these) – raina77ow Nov 03 '12 at 16:59
  • 1
    ahh, never mind.. in the first if a is increment twice so is 0 == 1; then, a is incremented again in next line so a is now 2. In the second if a increment first and compare later so a is 3 and 3 != 2; therefore, the answer: not equals, not equals 2 – miatech Nov 03 '12 at 17:00
  • 1
    And this is exact duplicate, which has been [**answered**](http://stackoverflow.com/a/12036576/1229023) in very nice details (with link to the documentation included). Why you didn't use search, I wonder? – raina77ow Nov 03 '12 at 17:00

3 Answers3

2

it's not that it waits until the next line. The == is a 'logical' operator so the expression on each side is evaluated first, each of which has the side-effect of incrementing the 'a' value. The result of the 1st increment is used on LHS, result of 2nd on RHS.

In these cases it matters not whether the operator is 'prefix' or 'postfix'

robert
  • 4,612
  • 2
  • 29
  • 39
0

EDIT: just realized you asked also for first not equals, this just answers the second one yet.

Because

  • a is already 2 (already incremented twice)
  • ++a is 3 so
  • 3 == 2 is false since prefix is applied before evaluation.
Jack
  • 131,802
  • 30
  • 241
  • 343
0

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
PermGenError
  • 45,977
  • 8
  • 87
  • 106