+ 5

Why the output of this code is 1?

int a = 1; a = a++; System.out.println(a);

5th Jul 2017, 9:42 AM
Dahna
Dahna - avatar
10 Respostas
+ 10
Not 100% but i think it is because of the way it is being interpretted by the compiler.Which is make a new copy of a then plus 1 to the original a. so if you say int a = 1; a++; print(a) it will work as expected
5th Jul 2017, 10:14 AM
jay
jay - avatar
+ 7
so much efforts Jojo 😼
5th Jul 2017, 12:04 PM
jay
jay - avatar
+ 6
Yep! Had to think about it though. Prefix 1, i= 1+1
5th Jul 2017, 10:28 AM
jay
jay - avatar
+ 4
@Jojo explain it well, if you want a more accurate explanation, I'll be glad to give it to you but know where it will go. Beware beware, I'll try to make you understand some basics of assembly😂
5th Jul 2017, 12:20 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 3
It is because of the order of operator First we put 1 in a (int a =1) Secondly we save the value of a to put it in a as ++ is after the variable it increments and not before Then we increment a Then we put 1 that was save in a
5th Jul 2017, 11:13 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 2
Yes you're right, that's why i=i++ + ++i; // if i=0, i's value will be 2 and not 3 Dunno if you understand..
5th Jul 2017, 10:24 AM
Jojo
+ 2
Rupendra a=a++; is a valid expression. But this is what happen : (It is the SAME variable, the NUMBERS are here to ILLUSTRATE) a2=a1++; is like : a2=a1; // useless but valid a1++; // increments a1 but a1 doesn't exist anymore ! a1++ increments a value wich has been OVERWRITTEN. So the statement is ignored. Another exemple : int i=0; i=i++ + ++i; is like i+=1; // i=0+1=1 i=i+i; // i=1+1=2 i+=1; // i=i+1=3? nope... Let see with the number (used to ILLUSTRATE, i1, i2... are the SAME VARIABLE) i=i1++ + ++i1; i2=i1+1; // i1=0, i2=1. i3=i2+i2; // i3=2. i2=i1+1; // oops i2 doesn't exist anymore... i2 wich was equal to 1 was OVERWRITTEN by i3 wich equals 2. I know it's quite very very very difficult to explain and understand (maybe I chose a bad way to explain it) so I won't be angry if you don't understand... 😀 Anyway if you have questions on this answer ask me
5th Jul 2017, 12:01 PM
Jojo
+ 2
You can do it as Jay said: "int a = 1; a++;" or if you want to do it your old way you could try this: "int a = 1; a = ++a;" Please correct me if I'm wrong, but the a++ returns the value of "a" and then increments it, when the ++a, first increments the value and then returns it.
5th Jul 2017, 3:32 PM
Edi Stefanut
Edi Stefanut - avatar
+ 1
Yeah... I like incrementation, but I feel my head's gonna explose soon
5th Jul 2017, 12:05 PM
Jojo
+ 1
the correct answer is 1 2 3 4 .. to infinit
7th Nov 2017, 3:08 PM
John John
John John - avatar