• 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

overflow and underflow

 
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Would anybody like to explain the subject topic in short here for me or point me to a place where I can find the relevant topic. Thanks.
I got this question 'coz of the following practice:
1: void infiniteLoop()
2: {
3: byte b = 1;
4:
5: while ( ++b > 0 )
6: ;
7: System.out.println("Welcome to Java");
8: }
what will print out?
 
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Luk,
An overflow occurs when the value assigned to a variable is larger than the maximum value the type can contain. Java does not produce a runtime exception when this happens; rather, it drops the high-order bits.
In your example, a byte can hold the positive values 0 to 127; once you reach '128' you overflow <code>byte</code> type. '128' is represented by '1000 0000' where the '1' is in the sign position, setting the value to a negative or less than zero, so you're loop ends without an error.
Actually, in your example, 'Welcome to Java' is displayed once. If you modify the code you can get a better picture of what's happening.

The last line printed shows that b is equal to '-128' ... the negative sign is the result of the way Java handles the overflow; it fills all the high order bits for the int type with the sign value.
Hope that helps.
------------------
Jane Griscti
Sun Certified Programmer for the Java� 2 Platform
 
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
i would like to know why this code is printing "Welcome to java" only once"??
 
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Hema,
It is because after the while loop gets over, the program execution continues to System.out.println ("Welcome to Java") and hence the output.
 
reply
    Bookmark Topic Watch Topic
  • New Topic