+ 1

Java ++ operator

Hey guys. I am a bit confused why x become 4 and not 5 in the code below? int x =1; x = ++x + x++; System.out.println(x);

27th Oct 2020, 8:07 PM
Mohammad Kakuei Nezhad
Mohammad Kakuei Nezhad - avatar
4 odpowiedzi
+ 3
It’s because the x++ returns x, then makes it higher. So, ++x will make it higher, and give 2, and x++ will give 2, THEN turn x into 3. 2 + 2 = 4 Hope this helps.
27th Oct 2020, 8:15 PM
Rowsej
Rowsej - avatar
+ 2
Thanks I got it
27th Oct 2020, 9:16 PM
Mohammad Kakuei Nezhad
Mohammad Kakuei Nezhad - avatar
+ 1
I understand that x++ will first evaluate the statement and then add one. In this way 'x' first becomes 2(++x) and then it will be added to x(2+2 =4). Now the assignment is executed so x is 4. BUT after the assignment x++ should add one to x which gives 5. So after the execution of line two, x should be 5 !!! :(
27th Oct 2020, 8:33 PM
Mohammad Kakuei Nezhad
Mohammad Kakuei Nezhad - avatar