+ 1

Why is the output not 1 2 3 4?

public static void main(String[] args) { int x = 1; while(x > 0) { System.out.println(x); if(x == 3) { break; } x++; } System.out.println(x++); } The output comes out to be 1 2 3 3 If i write (x=x+1) in the last statement, it comes out to be 1 2 3 4. But if (x++) and (x=x+1) are same, why are the outputs not same?

15th Mar 2018, 9:06 AM
ADP
ADP - avatar
5 Respostas
+ 8
@ADP , see this ... 👍 //btw the difference caused in above question by ++x& x++ is only in printing https://www.sololearn.com/Discuss/1140298/?ref=app
15th Mar 2018, 10:26 AM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 6
x++ uses the value of x and then increments which basicly means that the old value of x will be used first and then the new value will be used next ++x increments the value of x and then uses it. ++x looks like x+=1.
15th Mar 2018, 12:16 PM
D_Stark
D_Stark - avatar
+ 3
public static void main(String[] args) { int x = 1; while(x > 0) { System.out.println(x); if(x == 3) { break; } x++; } System.out.println(++x); } "x++" and "++x" are not the same. For the answer "1 2 3 4" you need to use "++x".
15th Mar 2018, 9:55 AM
Dzmitry Ausiannikau
Dzmitry Ausiannikau - avatar
+ 1
Could u explain further please? (x++) is (x=x+1) right? and (++x) is?
15th Mar 2018, 10:25 AM
ADP
ADP - avatar
+ 1
Could u check this code....if i have understood clearly.... https://code.sololearn.com/c2nG7xO2to5x/?ref=app
15th Mar 2018, 10:46 AM
ADP
ADP - avatar