+ 1
int x = 14; int y = x++; System.out.println(x++); why result is 15?
Postfix: if x = 14 value of x [System.out.println(x++)] will be 14 I got this part but int x = 14; int y = x++; System.out.println(x++); giving me 15. please, anyone, explain this
7 Answers
+ 3
Prefix means first increment then assign.
Postfix means first assign then increment.
So y = x++; // first assign so y=14 now x has to be incremented.
When you print it in the next line, it has become 15.
+ 2
Hi! Your x stay 15 in line:
int y = x++;
it is increased by the x++ Postfix increment by one
Then in line:
System.out.println(x++);
the value 15 is output, which was defined in the previous line and the x was increased by one more time (behind the frame) , so if we add one more line with the command output x. the program will give us the result 16
System.out.println(x);
the result is be 16
https://code.sololearn.com/clNsGINb019D/?ref=app
+ 1
Because you incremented x when you defined y.
Edit: Try to println x again by it self after the last one.
+ 1
Yaroslav Vernigora: Result of y would be 14 :)
Thanks, man you made it clear.
+ 1
//step 1 = x has the value "14".
//step 2 = the value of x remain 14 which is asigned to y.
//step 3 = print the x++ with post increment to value "15"
0
Question to you: what is result of y?
0
15