aspose file tools*
The moose likes Beginning Java and the fly likes Operator associativity Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Operator associativity" Watch "Operator associativity" New topic
Author

Operator associativity

Hitesh Jodhavat
Greenhorn

Joined: Jan 02, 2006
Posts: 1
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

Joined: Aug 16, 2005
Posts: 14268
    
  21

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:


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
The thread is named "Associativity" and the class "Precedence", but the problem is really about the order in which side effects are applied


There is no emoticon for what I am feeling!
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11402
    
  16

There is also a FAQ on this very topic here


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Adam Price
Ranch Hand

Joined: Nov 11, 2005
Posts: 95
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

Joined: Dec 06, 2001
Posts: 3061
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 ]

Java API Documentation
The Java Tutorial
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Operator associativity