• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Incrementing

 
Ranch Hand
Posts: 904
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi
I got a small question conserning the following code:
code 1:
<code>
int i = 5;
int y = i++;
System.out.println("i:"+i); //output i:6
System.out.println("y:"+y); //output y:5
</code>
We use post incrementation when we want to initialize y, which is why i is 6 and y 5. Observ the following code.
code2:
<code>
int i=5;
i = i++;
System.out.println("i:"+i); //output 5
int t = i++;
System.out.println("i:"+i); //output 6
</code>
Can anyone please discribe why i isn't incremented after i = i++.
Thanks in advantage.
/Svend Rost
 
Ranch Hand
Posts: 279
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
execution happens this way according to precedence:
1- right hand side of the = is evaluated ==> 5
2- i is incremented AFTER putting its current value in the RHS evaluation due to unary postfix ++ ==> 6
3- right hand side is assigned to the left hand side of the = operator
remember right hand side was evaluated before i was incremented, so right hand side still equals 5 although i is incremented.
after the assignment, i gets back the 5....
got it?
[ November 12, 2002: Message edited by: Alfred Kemety ]
 
Svend Rost
Ranch Hand
Posts: 904
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes - more or less atleast
Was just abit pusseled why i was incremented in code1 and not in code 2.
Thanks
/Svend
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic