++ operator
Hi everyone,
Well I have one small doubt in the following code:
public static void main(String[] args) {
// TODO Auto-generated method stub
int i=10;
i=i++;
i=i++;
System.out.println("i:"+i);
}
The o/p of the program is 10 rather than 12.
Can anyone explain me why? I have tried to find out the reason but some tell it is coz of precendence but ++ has higher precedence than = then wht is the reason.
Regards,
Kamal
because you're assigning the result of i++ back to i again. i++ doesn't mean "i + 1", it means "increase i by 1". i++ will evaluate back to i, and then increment by 1, but then you go and re-assign i to it's origiinal value
> Is this, the annual "ask your students to research a
> stupid topic" day?
I seem to recall seeing this somewhere before, though, maybe in the SCJP exam, or something. Or maybe in Java Puzzlers. Maybe it was here. Anyway, I know I've seen it before. Is that a question they ask on the SCJP exam?
> Can anyone explain me why? I have tried to find out
> the reason but some tell it is coz of precendence but
> ++ has higher precedence than = then wht is the
> reason.
yeah, thats basically it. technically, the ++ does increment the variable, but the return value of the postIncrement operation is the ORIGINAL value of the variable. AFTER that value is returned, then it is applied to the = operator, which sets the variable back to its original value.
to put this topic to rest, take a look at an explanation from a True Java Expert, Joshua Bloch. He covered this in his programming puzzlers talk at the 2005 Java One conference (TS-3738). If you view the media presentation, he will explain to you what the problem is. You can find it at http://developers.sun.com/learning/javaoneonline/2005/coreplatform/ Look at puzzle number 3 (Tricky Assignment).
The answer to your question lies in the following code: run it and let us know what the output is now and how is this code different from the one you posted.
public static void main(String[] args) {
//TODO Auto-generated method stub
int i=10;
i=++i;
i=++i;
System.out.println("i:"+i);
}