Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Operator associativity

 
Hitesh Jodhavat
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Precedence {
final public static void main(String args[]) {
int i = 0;
i = i++;
i = i++;
i = i++;
System.out.println(i); // prints 0
}
}

Could you explain the execution of i = i++;
i++ should increment the value of i, isn't it?

Regards,
Hitesh
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15284
39
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, i++ increments the value of i. But the expression i++ returns the old value of i (in this case, 0), and that's what you're assigning to i after incrementing.

If you want the output of this program to be 3, it should look like this:
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The thread is named "Associativity" and the class "Precedence", but the problem is really about the order in which side effects are applied
 
fred rosenberger
lowercase baba
Bartender
Posts: 12127
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is also a FAQ on this very topic here
 
Adam Price
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Hitesh Jodhavat:
public class Precedence {
final public static void main(String args[]) {
int i = 0;
i = i++;
i = i++;
i = i++;
System.out.println(i); // prints 0
}
}

Could you explain the execution of i = i++;
i++ should increment the value of i, isn't it?

Regards,
Hitesh


Greenhorn alert (by which I mean me):

i++ means "Return the current value of i, then add 1 to it."
I think you could see the results you are expecting by changing the incrementor to
++i which means "add one to i and give it's value." Is that right?
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The moral of the story here is that you should NOT use = and ++ in the same line of code! Although the behavior is clearly defined by the JLS, it is very confusing to new comers.

Layne
[ January 09, 2006: Message edited by: Layne Lund ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic