Numeric Overflow


When working with integral variables, you must be careful to avoid overflow, which can create incorrect results.

For each numeric type, Java provides constants representing its range. For example, the constants Integer.MAX_VALUE and Integer.MIN_VALUE represent the largest (231 1) and smallest (231) values an int can have, respectively.

Java will internally assign the results of an expression to an appropriately large primitive type. The example test shows how you can add one to a byte at its maximum value (127). Java stores the result of the expression as a larger primitive value.

 byte b = Byte.MAX_VALUE; assertEquals(Byte.MAX_VALUE + 1, b + 1); 

But if you attempt to assign the result of an expression that is too large back to the byte, the results are probably not what you expected. The following test passes, showing that adding 1 to a byte at maximum value results in the smallest possible byte:

 byte b = Byte.MAX_VALUE; assertEquals(Byte.MAX_VALUE + 1, b + 1); b += 1; assertEquals(Byte.MIN_VALUE, b); 

The result is due to the way Java stores the numbers in binary. Any additional significant bits are lost in an overflow condition.

Floating-point numbers overflow to infinity.

 assertTrue(Double.isInfinite(Double.MAX_VALUE * Double.MAX_VALUE)); 

Floating-point numbers can also underflowthat is, have a value too close to zero to represent. Java makes these numbers zero.



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net