Prem wrote:No, it should be exactly what it is. If that were not the case, it would mean that there is a HUGE error in a very basic part of Java that a beginner such as yourself was able to find, but that somehow didn't get fixed, despite Java being used in thousands of existing applications.
Ok.. thanks for that knowledge..
if operands are evaluated left to right then output of this expression should be 6 but it is 5 ? How ?
When we hit the first term (i++), the value of i is 0. The value of that expression is the original value of i, before incrementing, so we determine that the value of that expression is 0. Then we increment i to 1. So our running total is 0 and the value of i is 1.
int i=0; System.out.println( i++ + ++i + ++i);
Edited by: jverd on May 15, 2012 2:32 AM
int i = 0; int j = i++; // j = 0; i = 1; int k = ++i; // i = 2; k = 2; int m = ++i; // i = 3; m = 3; System.out.println(j + k + m); // 0 + 2 + 3
Yup. Perfectly expected. And based on my explanation above, you should be able to figure out why.Just for curiosity , I did i=i++
Also, you, know that it's always wrong to write i = i++, right?
Prem wrote:The same location as itself? Yes, but that's not relevant.
But in this case I guess i is pointing to some memory location . right ?
so in expression i=i++ , = has heigher precedence over postincrement operatorNo, it doesn't. If it did, then i = i++ would be equivalent to (i = i)++ which is illegal. The ++ operator requires a variable, and (i = i) is not a variable.
you would expect j to get the value 0, right? Because you know that j gets whatever the value of the expression on the RHS is, and you know that the value of the expression i++ is whatever i is before it gets incremented, right?
int i = 0; int j = i++;