• Post Reply Bookmark Topic Watch Topic
  • New Topic

Increment Operator and Assignment Operator  RSS feed

 
Kaur Manpreet
Ranch Hand
Posts: 30
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Please advise

Thanks
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jeff, it was quite helpful
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kaur Manpreet wrote:

Jeff already explained it, but we also have a FAQ page about this: Post Increment Operator And Assignment.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!