Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

increment operator

 
eskay kumar
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't remember which exam i saw this one at...but i just can't seem to understand why this should happen....
It seems obvious that the foll two code should give an output: a=3,
code 1:{
int a=2;
int y= a++;
System.out.println("a="+a);
}
code 2: {
int a=2;
a=a+1;
System.out.println("a="+a);
}
However this code below outputs a=2.
{
int a=2;
a= a++;
System.out.println("a="+a);
}
Why is the post incremented value of 'a' not printed in the last code???
Help !!!

[This message has been edited by eskay kumar (edited July 23, 2000).]
 
Joseph Zhou
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As you see, the expression a++ is 2, and will assign to a (using =). The = have the lowest precedence than others, so, it will be the last step to be carry out.
 
sunilkumar ssuparasmul
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
{
int a=2;
a= a++;
System.out.println("a="+a);
}

SEE it happens like this
1. a= 2 is stored in some memory location
2. a is incremented and stored in some other location
3. while assigning back it takes the original memory location i.e of step 1
4 . ie y u get output=2 if u try giving some other variable like b=a++ u would get the desired answer
thanks
sunil


------------------
"Winners don't do different things
They do things differently"
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic