x=0; x=x++; System.out.println(x); why is the output 0? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

x=0; x=x++; System.out.println(x); why is the output 0?

22nd Dec 2016, 6:51 PM
Kibrom
Kibrom - avatar
9 Answers
+ 19
x=x++ will first assign value of x to x and then increment it. So again 0 is assigned to x and then incremented value 1 is not stored anywhere.So you get the output as 0 when you print x. i guess x=++x; should work.
23rd Dec 2016, 3:09 AM
Frost
Frost - avatar
+ 7
you must do: x=0; x++; or x=0; x=++x; (change post-increment to pre-increment)
22nd Dec 2016, 7:03 PM
Valen.H. ~
Valen.H. ~ - avatar
+ 5
Of Course! (it's not a loop) he just wanted to change the "0"...
22nd Dec 2016, 8:58 PM
Valen.H. ~
Valen.H. ~ - avatar
+ 2
Do you know what this symbol (=) stands for? The left represents the stack memory, the right represents the heap memory. The right should represent the memory address. It is the address of a pointer. X + +, in the heap memory is not out of the stack, you have changed the x pointer, x + + is actually divided into three steps, your wording interrupted the steps of the pointer, if you remove x = these two, you will get you The desired result!
17th Jan 2017, 12:45 PM
xuyexu
xuyexu - avatar
+ 1
x=0; x=x++; in the 2nd line,the variable in the memory will be increment to 1,but as it is a post increment 0 will be fetch at first.,then 0 is assigned to x as assignment is the last operation.,. here the value which previously was 1 will be replaced by 0. hence x=0.
16th Jan 2017, 8:35 AM
Subhakant Priyadarsan
Subhakant Priyadarsan - avatar
+ 1
This is post increment, in which original value is first assigned and then it is incremented, unlike in pre increment, value is first incremented and then new value is assigned, same applies for decrement.
20th Jan 2017, 11:17 AM
Varshal Davda
Varshal Davda - avatar
0
I suppose the statement x=x++ assignes to x the value of x before increment (so 0) and also it overrides the ++ increment, since the operations are sequentially: 1) extract the value of x; 2) increment the value of x; 3) assign to x the previously extract value. Meaning so that x=0. What practically happens is: tmp = x; x++; x = tmp; I suppose that if the variables were different then the left one would be the previous value of x (0) and also the x variable would increment.
22nd Dec 2016, 9:47 PM
Alexander James Pane
Alexander James Pane - avatar
0
x=0; x=x++; here at frst x(right side ) is assign to x(left side) which is 0 and then increase the x(right side) to 1. because it is post increment operation
16th Jan 2017, 4:55 PM
Kousik Mitra
Kousik Mitra - avatar
- 1
I also don't get it, isn't x=0; x=x++; and the final value of x will become 1 because of x++ ?
22nd Dec 2016, 11:36 PM
Leon lit
Leon lit - avatar