• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Increment operator

 
Raj Neets
Ranch Hand
Posts: 46
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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;
inc.fermin(i);
// my doubt is here
i = i++;
System.out.println(i);
}
void fermin(int i){
i++;
}
}

Thank you
Raj
 
Phil Rhodes
Ranch Hand
Posts: 65
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, I think I found something that explains it. Look at this thread on the Sun Java forums:
http://forum.java.sun.com/thread.jsp?thread=54700&forum=31&message=137274
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 ]
 
Raj Neets
Ranch Hand
Posts: 46
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you
but its a very complex issue to understand
 
Davy Kelly
Ranch Hand
Posts: 384
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic