+ 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????
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
+ 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. đ
+ 5
1. a = 8
2. a += ++a;
- ++a = 9
- a = 8 + 9 = 17
3. ++a = 18
+ 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.
+ 3
Thank you David! Your answer is inspired!
+ 2
It is as if you coded:
int a = 8, a1 = 8;
a += ++a1;
System.out.println(++a);
+ 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
+ 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.
+ 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.