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.
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;tmp2 = ++z; can be broken down into: z = z + 1; tmp2 = z;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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With