This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes assignment operators Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "assignment operators" Watch "assignment operators" New topic

assignment operators

Anna Chu
Ranch Hand

Joined: May 18, 2006
Posts: 30
I get a very wierd problem about assigment operator about the code below:

int i=0;

The result printed out is 0.

I don't know why it is not 1. Can someone explain how this happens?
Thanks a lot!
Michael Carlson
Ranch Hand

Joined: Sep 11, 2005
Posts: 78
It's post increment, the assignment happens and then i is incremented.
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
Ashok S Yadav

Joined: May 04, 2006
Posts: 5
I am confused with the reply.
int i =0;
i = i++;
Here is what I think the sequence of operations is
1. i=0 and this value is assinged to the RHS and hence i is zero.
2. i is then incremented due to the post fix increment.
Shouldn't i then become 1.

Naseem Khan
Ranch Hand

Joined: Apr 25, 2005
Posts: 809

Posted by Michael Carlson
It's post increment, the assignment happens and then i is incremented.

Its a misconception among ppl that assignment occurs before increment but its wrong.

If u see the precedence order, postfix operator has higher precedence than assignment. So i++ is executed first.

Here is the order of execution.

1. i++ gets evaluated, so i becomes 1 but still the value of the expression i++ is zero.

U can test it by...

System.out.println(i++); it prints 0. if i is zero initially

Even in method call,

meth(i++, i) means-->>> meth(0, 1) if i is initially zero.

jst remember this. first VM stores the value of i which is zero to some temporary location then increments its value by one. So i becomes one, but the value which is assigned to i is again temporary location value.

Hence i again becomes zero.

[ May 31, 2006: Message edited by: Naseem Khan ]

Asking Smart Questions FAQ - How To Put Your Code In Code Tags
I agree. Here's the link:
subject: assignment operators
It's not a secret anymore!