programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Increment Operator and Assignment Operator

Kaur Manpreet
Ranch Hand
Posts: 30
Hi All,

I need some help in understanding the following code snippet:

At Line 1, x++ would happen in the next line, however at the current line x is assigned the existing value that is 3

But x is never incremented, I mean x++ never actually happen
If we have something like x = y++; the x is assigned the existing value of y and the variable y is incremented in the next line after the assignment.

In the above only the assignment happens but there is no increment to x.

Thanks

Jeff Verdegan
Bartender
Posts: 6109
6
• 2
Kaur Manpreet wrote:Hi All,

I need some help in understanding the following code snippet:

At Line 1, x++ would happen in the next line,

False. First, make sure you understand that you should never write x = x++;. It's always wrong. But, when somebody does write it for these silly tests, here's what happens:

1. Note the current value of x. This is the value of the x++ expression.

2. Increment x.

3. Take the original value of x, from step 1, and store it in x.

It's as if we did

People often mistakenly think that the post-increment operator does its increment after the statement is done. That's wrong. It does the increment immediately after "remembering" the original value.

But x is never incremented, I mean x++ never actually happen

False. X is incremented, but then the x = part puts the original value back into x.

If we have something like x = y++;

If we have that, the behavior is exactly the same. Just a different variable getting assigned at the end.

the x is assigned the existing value of y and the variable y is incremented in the next line after the assignment.

No. y is incremented, and then x is assigned y's original value.

Kaur Manpreet
Ranch Hand
Posts: 30
Thanks Jeff, it was quite helpful

Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Kaur Manpreet wrote:

Jeff already explained it, but we also have a FAQ page about this: Post Increment Operator And Assignment.