+ 2

Could someone explain why it is showed "1" in Java?

int x = 1; x = x++; System.out.println(x);//the issue

25th May 2017, 11:21 PM
Oleksandr Byelyenov
Oleksandr Byelyenov - avatar
4 Respostas
+ 10
x does get incremented, but not after x is assigned its old value
26th May 2017, 12:27 AM
Shane
Shane - avatar
+ 4
What the code thinks: 1) Oh so now we have a somebody called x 2) Okay there is an x with a value of x, or 1 3) okay increment the first x and forget it 4) print out the x that we have now x++ alone will ddo what you want don't need to declqre x=x++
20th Jul 2017, 3:46 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 2
When using increments You have to think about how You want to do the incrementation. There're two possibilities. First one is increment the number before execution by ++x which leads to x= 2, or increment after execution by x++ which leads to x = 1 and x = 2 after execution.
26th May 2017, 12:10 AM
zdena
+ 1
Try ++x
25th May 2017, 11:58 PM
Noor Mazlina