Operators

Hello to all.Could anybody help me to understand the following java code:int i=10;i=i++;System.out.println(i); Why 10?And:int i=10;i=i++ + i++;System.out.println(i); Why 21?Thank you.
[267 byte] By [bulbaa] at [2007-10-2 0:00:54]
# 1

int i=10;

i=i++;//assigning a value is done after the expression is evaluated... here the expression value is "10 " since u r using post increment. after the expression evaluation is complete "i" value is 11. But as u have used the post increment the value of expression will be 10 which is assigned and printed.

System.out.println(i); Why 10?

And:

int i=10;

i=i++ + i++;

System.out.println(i); Why 21?

the expression here ((i++) + (i++)). We know that expression evaluation takes place from left to right.so at first (i++) it results in 10 and the second (i++) results to 11. so by adding up u will result in 21.

Jogeswara_Raoa at 2007-7-15 15:55:06 > top of Java-index,Core,Core APIs...
# 2

j++ uses the current value of j as the value of the expression first, then adds 1 to j. It is equivalent to the following statements:

result = j;

j += 1;

return result;

so it returns 10 which is assigned to i again.

same with the case of (i++)+(i++)

I dont know if it is a bug , but this is the only plausible solution

Nurasa at 2007-7-15 15:55:06 > top of Java-index,Core,Core APIs...
# 3

Think of it this way: if a ++ in front of/behind a field makes a copy of the field. The copy is the current field value without adding 1 if ++ is behind / with adding 1 if ++ is in front of the field.

i=i++is the same asi=i = 10

same with this example:

int i=10;

int j = 10;

i=i++ + j++;

i =i++ + j++is the same asi=i + j = 10+10 = 20

for the special case

int i=10;

i=i++ + i++;

you need to keep in mind that the first i++ copies the current value of i which is 10. The second i++ is also copying the current value of i but which is already 11 because of the first i++. Example:

i = i++ + i++

i = a + i++; //a is a copy of i that is 10, i itself is now 11

i = a + b; //b is a copy of i that is 11, i itself is now 12

i = 10 + 11 = 21

int i=10;

int j =i++ + i++;

System.out.println(i);

System.out.println(j);

MartinHilperta at 2007-7-15 15:55:06 > top of Java-index,Core,Core APIs...
# 4
int i=10;i =i++ + i++ + i++ + i++; //10 + 11 + 12 +13 = 46System.out.println(i);
MartinHilperta at 2007-7-15 15:55:06 > top of Java-index,Core,Core APIs...
# 5
> I dont know if it is a bug ,It's not. It's the behavior defined by the JLS.In C, the order of evaluation is undefined, so you could end up with either 10 or 11 for the first example.
jverda at 2007-7-15 15:55:06 > top of Java-index,Core,Core APIs...