Win a copy of TDD for a Shopping Website LiveProject this week in the Testing forum!
  • 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
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

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
 
Clowns were never meant to be THAT big! We must destroy it with this tiny ad:
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic