wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes post increment operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "post increment operator" Watch "post increment operator" New topic

post increment operator

Alexander Danilou

Joined: May 08, 2009
Posts: 28
Sorry if this question is so easy it is stupid, but Im new to Java and cannot wrap my mind aroud why:
int x = 5;
x = x++;
System. out.print (x);
produces 5. What happens with post increment?
John de Michele

Joined: Mar 09, 2009
Posts: 600

Welcome to JavaRanch!

No, your question is not dumb . The reason why you're getting 5, is that the postfix increment happens after the assignment. So, in your example what happens is:

You create x and assign it a value of 5:

You then assign x the value of a temporary variable equal to x++. In detail, you are assigning x the value of the temporary variable, then incrementing the temporary variable (which gets dropped):

Naturally, when you print it out, you get 5

If you want to get six, you probably should just do this:

Marco Ehrentreich
best scout

Joined: Mar 07, 2007
Posts: 1280

Hi Alexander,

welcome to the JavaRanch ;-)

For your question: Just have a look at the JavaRanch FAQ. It explains exactly your problem!

Alexander Danilou

Joined: May 08, 2009
Posts: 28
Thanks, looks like I need to start by learning how to use serch in FAQ..
Marco Ehrentreich
best scout

Joined: Mar 07, 2007
Posts: 1280

Searching for existing knowledge on the web is always a good idea

But as a general advice: If you want to learn Java you don't have to focus on such subtle details of the language syntax. If you take an exam or something like this then you probably will have to learn these things but for practical usage of Java there are other much more important things besides difficult to understand code fragments like this. Of course such an language constructs may be useful in some situations as you can see they often lead to confusion. And believe me, this is not only true because you are new to Java If you use a modern object oriented language like Java wisely you hopefully won't see such things very often! Today higher level concepts and clean design and architecture of a software are much more important than using tricky operators.

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 38007
Welcome to the Ranch. It is worthwhile searching for "postincrement" in this forum; similar questions come up frequently, probably on average one a month at least.

And it is very easy to get confused about the postincrement operator.
I agree. Here's the link: http://aspose.com/file-tools
subject: post increment operator
Similar Threads
assigment order and post increment
Reference variables and wrappers
x++ , ++x