• Post Reply Bookmark Topic Watch Topic
  • New Topic

How does thsi work  RSS feed

 
sachin jauhari
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public static void main(String[] args) {

int i=0 , j;
i = i++;
j = i++;
System.out.print( i + " " + j );

}

Output is : 1 0

I could not understand the reason for this output
 
Stuart Gray
Ranch Hand
Posts: 410
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The pre-increment (++i) and post-increment (i++) operators are unary - they do not need to be part of an assignment statement using equals. So, this code will increment i by one:

But AFAIK the following code will do nothing, because the value of i is first assigned to i (which of course is a redundant assignment), and then the value on the right hand side is incremented by one (but not assigned anywhere):


So this is what is happening in your code:

int i=0 , j;
int i is assigned zero (explicitly), j is assigned zero (implicitly)

i = i++;
This assignment has no effect on i (still zero);

j = i++;
j is assigned value of i (zero), and then i is incremented to become 1.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12542
48
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the value of i is first assigned to i (which of course is a redundant assignment), and then the value on the right hand side is incremented by one

i don't think that's quite correct. first, the right hand side is evaluated, ignoring all post increment operators. in this case, it is evaluated to 0. we remember this for the moment, becuase we now need to take care of the post increment operator.

so now we look at the value of i, which is 0. we increment it, to 1.

now we're completly done with evaluating the RHS, so i can do the assignment. the RHS evaluated to 0. so i assign that to i.

so, for the briefest of moments, i actually is 1, but the we immediatly re-assign it to 0.
 
Steve Morrow
Ranch Hand
Posts: 657
Clojure Spring VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

First, this is horrible code that should be refactored immediately and the original programmer slapped with a dead mackerel.

Second, what happens with that code is this (at least in theory - a smart compiler should optimize this out):

The value contained in the 'i' variable is incremented. However, the expression 'i++' evaluates to the pre-increment (original) value of 'i'. The '=' assignment operator has the least precedence, so it happens last: the pre-increment (original) value of 'i' is assigned back to 'i'.

The moral? Don't write silly code like this.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!