Can you explain to me the output of this Java code?
int a=5,i;
i=++a + ++a + a++;
i=a++ + ++a + ++a;
a=++a + ++a + a++;
System.out.println(a);
System.out.p
Pre-increment means that the variable is incremented BEFORE it's evaluated in the expression. Post-increment means that the variable is incremented AFTER it has been evaluated for use in the expression.
Therefore, look carefully and you'll see that all three assignments are arithmetically equivalent.
when a
is 5, then a++
gives a 5 to the expression and increments a
afterwards, while ++a
increments a
before passing the number to the expression (which gives a
6 to the expression in this case).
So you calculate
i = 6 + 7 + 7
i = 5 + 7 + 8
I believe however if you combine all of your statements and run it in Java 8.1 you will get a different answer, at least that's what my experience says.
The code will work like this:
int a=5,i;
i=++a + ++a + a++; /*a = 5;
i=++a + ++a + a++; =>
i=6 + 7 + 7; (a=8); i=20;*/
i=a++ + ++a + ++a; /*a = 5;
i=a++ + ++a + ++a; =>
i=8 + 10 + 11; (a=11); i=29;*/
a=++a + ++a + a++; /*a=5;
a=++a + ++a + a++; =>
a=12 + 13 + 13; a=38;*/
System.out.println(a); //output: 38
System.out.println(i); //output: 29
In both cases it first calculates value, but in post-increment it holds old value and after calculating returns it
++a
a++
a=5; i=++a + ++a + a++;
is
i = 7 + 6 + 7
Working: pre/post increment has "right to left" Associativity , and pre has precedence over post , so first of all pre increment will be solve as (++a + ++a) => 7 + 6
. then a=7
is provided to post increment => 7 + 6 + 7 =20
and a =8
.
a=5; i=a++ + ++a + ++a;
is
i=7 + 7 + 6
Working: pre/post increment has "right to left" Associativity , and pre has precedence over post , so first of all pre increment will be solve as (++a + ++a) => 7 + 6
.then a=7
is provided to post increment => 7 + 7 + 6 =20
and a =8
.
I believe you are executing all these statements differently
executing together will result => 38 ,29
int a=5,i;
i=++a + ++a + a++;
//this means i= 6+7+7=20 and when this result is stored in i,
//then last *a* will be incremented <br>
i=a++ + ++a + ++a;
//this means i= 5+7+8=20 (this could be complicated,
//but its working like this),<br>
a=++a + ++a + a++;
//as a is 6+7+7=20 (this is incremented like this)