Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

The question about : j=j++

 
Jonh yang
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi.. i am really a newbie, just a java beginner.
I need some help.
After executing the statement:j = j ++;
i found that the value of "j" wouldn't increase...but why ?
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34375
346
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Either of the following will increment j:

When using j = j++, it is adding one to j and overwriting it with the original value.
 
Marilyn de Queiroz
Sheriff
Posts: 9063
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Almost. If you look at the output of javap, I think you will see that in the case of j = j++, j is incremented after the value of 'j' is stored. On the other hand, in the case of j = ++j, j is incremented first and then the resulting value is stored in 'j'.
 
Davy Kelly
Ranch Hand
Posts: 384
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
check out this thread:
post increment
davy
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what you're doing is effectivel this:

though the compiler may optimise the whole thing away
j = ++j; would lead to
 
Mr. C Lamont Gilbert
Ranch Hand
Posts: 1170
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want a specific anser you can always look in the JLS. I believe java behaves differently that c in this respect.
 
Jos� Alberto Mu�iz Navarro
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah. in Microsoft's C compiler you get an output of 1 when you do


However, you get an output of 0 when you do

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic