+ 1

Justify the output?

public class Program { public static void main(String[] args) { int x = 4; int y = x++; int w = x; int z = y++; System.out.println(y); System.out.println(w); System.out.println(z); } } output: 5 5 4 why? output should be: 4 5 4 Right?

20th Feb 2017, 10:57 PM
Deepak Avula
Deepak Avula - avatar
2 Respostas
+ 3
Actually the original output is correct. You can read the expressions in this order: int x = 4; int y = x; x=x+1; int w = x; int z = y; y=y+1; So, in the end you have y=5, w=5 and z=4.
21st Feb 2017, 1:15 AM
Daniel Kreppel
Daniel Kreppel - avatar
+ 1
You have to check again the meanings of prefix and postfix increment operators. For example, y = x++ will perform assignment first then do the increment.
21st Feb 2017, 3:10 AM
Jian-hua Yeh
Jian-hua Yeh - avatar