+ 2

Why this code print 1, shouldn't it print 2 ?

class increment { public static void main(String[] args) { int x=1; x=x++; System.out.println(x); } }

24th Feb 2017, 5:40 PM
Preet Patel
Preet Patel - avatar
7 Réponses
+ 14
correction : class increment { public static void main(String[] args) { int x=1; ++x; System.out.println(x); } }
24th Feb 2017, 5:44 PM
Valen.H. ~
Valen.H. ~ - avatar
+ 3
x is incremented but you are assigning x to its old value if you write x = x++ If there is x++ the variable will increment but the ++ is behind the x so it wont have any effect on the statement in this lane. Then you reassign x to its old value so x will stay 1 I hope this answer will help you
24th Feb 2017, 6:14 PM
Hermann Set
Hermann Set - avatar
+ 2
{If you only write x++ or x = ++x, it will print one. But if you write x = x++, x will get the value of x and it will stay because the ++ is after the x. First the statement x =x will be executed and the x++ wont change anything because x =x} ;
24th Feb 2017, 5:45 PM
Hermann Set
Hermann Set - avatar
+ 1
My explanation not so good but, this happened Cause of memory heap ,The new value of X stored X old value is 1 ( on x=x++ or x = x = x+1 and in heap the value of X is 1 pushed ) , now the postfix icreament done and value of New X store in heap value 2 pushed but the reference of that heap memory popped the first value of X is 1 that's why you got the ans 1.
24th Feb 2017, 6:13 PM
Arshit patel
Arshit patel - avatar
0
Suppose if i change from x=x++; to some other statement say int y=x++; and then try to print the value of x then it will definitely print 2, correct ? But what's actually going on here why there is change in behaviour of the way code executes, please elaborate a bit more on it.
24th Feb 2017, 6:00 PM
Preet Patel
Preet Patel - avatar
0
I think too many answers are already given, but I think it may be correct too. When the increment sign(++) is before the integer, it is known as pre-increment operator. The value of x is changed to x+1 in both and displayed. But, when the increment sign(++) is after the integer, it is known as POST-increment operator. Its value is changed to x+1 in memory, but is displayed as x. Similarly, in your question, the value of x has been changed to 2... but is displayed as 1...because you used POST increment operator. Try this, the next when you cout x... it will show 2, because it happens only once. Hope this is unsuccessful in confusing you.
25th Feb 2017, 4:31 PM
Devansh Kaushik
Devansh Kaushik - avatar
0
@Devansh Kaushik no matter how many times i print x in the code below x=x++; statement, it always gives O/P as 1 only.
25th Feb 2017, 7:10 PM
Preet Patel
Preet Patel - avatar