Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

i=i++;

 
weiliu lili
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Inc{
public static void main(String argv[]){
Inc inc = new Inc();
int i =0;
inc.fermin(i);
i = i++; /*if i change the code in here as%i=i;i++;%the output is 1 ,
i thought the two expressions are the same as %i=i++;%,but actually they are different,why? */
System.out.println(i);
}
void fermin(int i){
i++;
}
}
 
Jamal Hasanov
Ranch Hand
Posts: 411
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, Weiliu
Because ++ in "i++" is postfix operator.
Try compie/run this and analyse for yourself:
class test{
public static void main(String []arg) {
int i=0;
System.out.println(i++);
i=0;
System.out.println(++i);
}
}
Additionally read RHE.
Best Regards,
Jamal Hasanov
www.j-think.com
 
Jessica Sant
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As Jamal stated... i++ is the postfix increment operator. It doesn't return a result so that's why the expression i=i++; doesn't work --> i++ on its own increments the variable.
Also... check out the handy dandy UBB [CODE] tags that allows you to preserve whitespace in your code and improve readibility.
[ May 30, 2002: Message edited by: Jessica Sant ]
 
Younes Essouabni
Ranch Hand
Posts: 479
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by weiliu lili:
public class Inc{
public static void main(String argv[]){
Inc inc = new Inc();
int i =0;
inc.fermin(i);
i = i++; /*if i change the code in here as%i=i;i++;%the output is 1 ,
i thought the two expressions are the same as %i=i++;%,but actually they are different,why? */
System.out.println(i);
}
void fermin(int i){
i++;
}
}

As everybody noticed it's a post operator, it means that the value of i will be changed later.
But it's value is changed
So
i=i++;
System.out.println(i)// Will print 2
and
i=1;
System.out.println(i++)// Will print 1
System.println(i)// Will print 2
The incrementation is taking effect after the evaluation.
I hope it helps!
 
Swati Gupta
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I was in this thread I found the link to a very good thread where Maha Anna had explained about increment and decrement.
I am planning to appear for Exam in few days and wondering that do we have any list of these types of good threads then me going through each thread.
Thanks.
 
Vikrama Sanjeeva
Ranch Hand
Posts: 760
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try This Link.It discusses the same code in good detail.
Bye,
Viki.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic