wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes ++ increment operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "++ increment operator" Watch "++ increment operator" New topic
Author

++ increment operator

Rahul Juneja
Ranch Hand

Joined: Aug 03, 2002
Posts: 425
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


Rahul Juneja
ThoughtClicks - http://techlabs.thoughtclicks.com
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

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.


[Jess in Action][AskingGoodQuestions]
Sagar
Greenhorn

Joined: Mar 25, 2005
Posts: 14
Hi,
Simply put it this way..."=" operator has the lowest precedence..


Sagar
Swati Udas
Ranch Hand

Joined: Aug 18, 2004
Posts: 121
Try printing c for second case..shud be 10 again


SCJP 1.4 (90%)<br />SCWCD 1.4 (88%)
Steve Morrow
Ranch Hand

Joined: May 22, 2003
Posts: 657

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

Joined: Jul 08, 2003
Posts: 24183
    
  34

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

Joined: May 22, 2003
Posts: 657

True; no one is arguing that the SCJP is intended to evaluate one's design skill!
 
 
subject: ++ increment operator
 
Similar Threads
reading and printing a file gives a space every other character
JSP behaving badly!
Passed SCJP 1.4 with 95%
June Newsletter Puzzle
Tomcat madness!