+ 2

WHY 18??WTF?

public class Program { public static void main(String[] args) { int a = 8; a += ++a; System.out.println(++a); } } OUTPUT "18" !!!! WHY????

11th Jan 2018, 9:47 PM
Grey King
Grey  King - avatar
10 Answers
+ 7
Doing this is Undefined Behavior. What I believe happens is the following: int a = 8; //a is 8 a += ++a; // load first a of 8 // load second a of 8 // increment second a to 9 // add second a (9) to first (8) yielding 17 System.out.println(++a); // increment 17 to 18 and print it
11th Jan 2018, 10:48 PM
John Wells
John Wells - avatar
+ 9
Grey... The challenges are not a test of your ability to program. They are really more like brain teasers designed to be tricky. Don't worry about missing questions. Rather, when you find questions you don't understand, test the code for yourself and learn from them. As you work through a lot of these, you will begin to retain an understanding that will begin to make answering new challenge questions effortless. Before you know it, you'll be getting 5 out of 5 most of the time. 😉
12th Jan 2018, 7:54 AM
David Carroll
David Carroll - avatar
+ 5
1. a = 8 2. a += ++a; - ++a = 9 - a = 8 + 9 = 17 3. ++a = 18
11th Jan 2018, 10:09 PM
Boris Batinkov
Boris Batinkov - avatar
+ 4
Although undefined behaviors and sequence points exist in C/C++, I'm pretty certain this isn't the case for Java. Also, if this was undefined behavior in Java, the answer would likely be some other value.
12th Jan 2018, 5:35 AM
David Carroll
David Carroll - avatar
+ 3
Thank you David! Your answer is inspired!
12th Jan 2018, 8:01 AM
Grey King
Grey  King - avatar
+ 2
It is as if you coded: int a = 8, a1 = 8; a += ++a1; System.out.println(++a);
11th Jan 2018, 10:56 PM
John Wells
John Wells - avatar
+ 2
++a-> a=a+1 in your code, a=8; a+=++a-> a=a+(a+1)=8+9=17 println(++a)-> a=a+1=17+1=18
12th Jan 2018, 12:30 AM
Hasan Jafarov
Hasan Jafarov - avatar
+ 2
Thank you all for the explanation, this code it's not my, I find it when see it in battle task (competition). and I cannot answer correct for it! It's quite disappoint me. And it so many not understandable things in competition even at my lvl! When I learn about java all fine , but when start competition...it's tearful.
12th Jan 2018, 7:19 AM
Grey King
Grey  King - avatar
+ 1
That is very confusing, but I THINK I know what is happening here: a += ++a; might do this: int func() { a++; return a; } a = 8 + func(); //8 because it didn’t increment a yet. The fact that it is a = ... means that the increment in func() has no actual effect on a after this line. This would now make it 17. This is just a theory, best explanation I can come up with.
11th Jan 2018, 10:11 PM
Jacob Pembleton
Jacob Pembleton - avatar