• 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

Easy but Tricky - count++

 
Ranch Hand
Posts: 156
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class tryplus {
final public static void main (String args[]) {
int count =1;
count = count++;
System.out.println(count);
count = count++;
System.out.println(count);
System.out.println(count++);
System.out.println(count);
count = count++;
System.out.println(count);
count++;
System.out.println(count);
}
}
---------------
My friend gave me this. Guess the output. I got the answer wrong. Scroll down for answer :

answer :
1
1
1
2
2
3
 
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
count = count++;
is a good example of a statement whose semantics are deliberately undefined in C or C++, but well-defined in Java.
It's still almost always a coding mistake, and I'd like to see the compiler issue a warning when it sees such a statement.
 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I thought the answer should be
1
1
2
2
2
3
How does System.out.println(count++) result in 1 and not 2?
Thanks.
 
Author
Posts: 201
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
1. print the value count 1
then
2. increment count by 1
Sometime having a C and C++ is good
 
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
System.out.println(++count) will print orginal value of count and then increment it by 1.If you make a slight change in code and make System.out.println(count++), it 1st increment the count by one then print the value of count.
regds,
Arpana
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic