Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why java statement evaluation is happening like these ?

int z = 1;
System.out.println(z++ == ++z);
System.out.println(++z == z++);

the output will be:

false
true

and I don't get why, please explain this to me.


2 Answers

Operands of == are evaluated left to right, and the ++ has higher priority, so your code is equivalent to:

int z = 1;
int tmp1 = z++; //tmp1 = 1 / z = 2
int tmp2 = ++z; //tmp2 = 3 / z = 3
System.out.println(tmp1 == tmp2);

tmp1 = ++z; //tmp1 = 4 / z = 4
tmp2 = z++; //tmp2 = 4 / z = 5
System.out.println(tmp1 == tmp2);

I assume you understand the difference between z++ and ++z:

  • tmp1 = z++; can be broken down into: tmp1 = z; z = z + 1;
  • whereas tmp2 = ++z; can be broken down into: z = z + 1; tmp2 = z;
like image 115
assylias Avatar answered Dec 02 '25 17:12

assylias


int z = 1;
    System.out.println(z++ == ++z);
    System.out.println(++z == z++);

z++ is post increment and ++z is pre-increment. Post increment increases the value after the expression is evaluated and pre increment increase the value before the expression is evaluated.

Hence,

int z = 1;
    System.out.println(z++ == ++z); // 1 == 3 false
    System.out.println(++z == z++);// 4 == 4 true
like image 25
Kazekage Gaara Avatar answered Dec 02 '25 19:12

Kazekage Gaara



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!