Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

++ increment operator

 
Rahul Juneja
Ranch Hand
Posts: 425
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anybody comment on this ..... Why ?

byte a=10;
a=a++;

R E S U L T
System.out.println(a); =10
..................................
byte a=10;
c=a++;

R E S U L T
System.out.println(a); =11
..................................

Cheers,
Rahul
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The post-increment operator does the following:

1) Reads the value of the variable and saves it;
2) Increments the variable
3) Returns the saved value.

You also must know that the whole expression "a++," including all side effects, is evaluated before the assignment is made.

So "a=a++" results in the value 10 being saved, then a is incremented to 11, and finally, the saved value is put back into a -- so a is 10.

In the second example "c=a++", we don't store the saved value back into a, so a remains 11.
 
Sagar
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Simply put it this way..."=" operator has the lowest precedence..
 
Swati Udas
Ranch Hand
Posts: 121
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try printing c for second case..shud be 10 again
 
Steve Morrow
Ranch Hand
Posts: 657
Clojure Spring VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So "a=a++" results in the value 10 being saved, then a is incremented to 11, and finally, the saved value is put back into a -- so a is 10.

And anyone who writes "a=a++" in production code should be flogged about the face and shoulders with a dead mackerel.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Steve Morrow:

And anyone who writes "a=a++" in production code should be flogged about the face and shoulders with a dead mackerel.



Absolutely. But every single SCJP study guide -- and I suspect many versions of the test -- want you to be able to explain this behavior. Along with those *&^*&^ "How many String objects are there?" and "When is the FooBlat eligible for GC?" questions!
 
Steve Morrow
Ranch Hand
Posts: 657
Clojure Spring VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
True; no one is arguing that the SCJP is intended to evaluate one's design skill!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic