• 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

Decrement Operator

 
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class CountDown{
public static void main(String args[]){
int countdown=3;
while(countdown-- > 0 ){
System.out.println(countdown--);
}
}
}
In the above code the output of countdown is 2 & 0.But i think it should be 2 & 1 because the value of countdown is 3 and a decrement operator is working on it.Can anyone make me clear .
Thanks
sudha
 
Ranch Hand
Posts: 177
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Sudha :
In the variable countdown the decrement is happening twice once in the while statement and inside the while statement.
It is important to note that the in post increment the value is assigned first and decremented in this case, hence the output.
Later
 
Ranch Hand
Posts: 1246
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class CountDown{
public static void main(String args[]){
int countdown=3;
while(countdown-- > 0 ){
System.out.println(countdown--);
}
}
}
First round:
countdown = 2 after While()
countdown = 2 print at System.out.println()
countdown = 1 after pritnln()
Second round:
countdown = 0 after While()
countdown = 0 print at System.out.println()
countdown = -1
THE best luck on your EXAM day.
end of loop
 
reply
    Bookmark Topic Watch Topic
  • New Topic