Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Post increment operator faux pas?

 
Gustavo Quiroz
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello. Can anyone please explain to me why Code Fragment I yields Output I while Code Fragment II yields Output II?

//Code Fragment I
int i=0;
i = i++;
System.out.println("i="+i);

//Output I
i=0

//Code Fragment II
int i=0, a=0;
a = i++;
System.out.println("a="+a);
System.out.println("i="+i);

//Output II
a=0
i=1

It seems than the JVM doesn't execute the post increment on the variable "i", but only when the LVALUE (variable on the left side of the assignment operator) is the varible "i" itself. Why?

Thanks in advance.

Gustavo Quiroz
Lima - Peru
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You may find Corey's Blog Article useful.
 
Ray Stojonic
Ranch Hand
Posts: 326
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i = i++; has been discussed many times.

It breaks down to this:
1- evaluate i, its current value is 0 so, 0 will be assigned.
2- increment i
3- assign 0 to i
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic