wood burning stoves
The moose likes Programmer Certification (SCJP/OCPJP) 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 Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Increment operator" Watch "Increment operator" New topic

Increment operator

Raj Neets
Ranch Hand

Joined: Nov 12, 2002
Posts: 46
Hello everyone
I have a doubt with following program's output.The output is 0 , i checked by executing the code but iam not able to understand the concept properly.Can someone please explain it to me.

I thought the statement i=i++ should work as follows
Frist assign i the value of i and then increment the value of i, so before the print statement executes, the i value should be increased to 1.but its not.

public class Inc{
public static void main(String argv[]){
Inc inc = new Inc();
int i =0;
// my doubt is here
i = i++;
void fermin(int i){

Thank you
Phil Rhodes
Ranch Hand

Joined: Dec 27, 2003
Posts: 65
Ok, I think I found something that explains it. Look at this thread on the Sun Java forums:
Basically, assuming these guys are right, what happens is.. i++ is evaluated first, because ++ has higher precedence than =, so you get i temporarily valued at 1 (the side effect of the ++ ), but since the value returned from the post-increment operator is the value of i BEFORE the increment, you turn around and assign 0 right back to i.
That feels right... anybody else got any insight?
Oh, and BTW... doing that in real code would be considered VERY bad form. I'd recommend never, ever, ever writing real code that uses an expression like that. In fact, I'd suggest not using ++ and -- in larger expressions at all.
[ January 28, 2004: Message edited by: Phil Rhodes ]
[ January 28, 2004: Message edited by: Phil Rhodes ]

A+, Network+, SCJP, SCWCD<br />preparing for SCBCD, SCEA, CompTIA I-Net+
Raj Neets
Ranch Hand

Joined: Nov 12, 2002
Posts: 46
Thank you
but its a very complex issue to understand
Davy Kelly
Ranch Hand

Joined: Jan 12, 2004
Posts: 384
hey Raj,
i have ammended the code to add some print statements, this may help: i have put comments in as well to better understand.

I hope this may help a bit.
try out the code and see if you can se what is going on

How simple does it have to be???
I agree. Here's the link: http://aspose.com/file-tools
subject: Increment operator
It's not a secret anymore!