Section 3.7. Overflow

   

3.7 Overflow

An overflow happens when a result is too large for the type of variable that is meant to hold it; that is, the value assigned is too large to be represented by the type. This can happen for a few different reasons, chief among them is that there has been an implicit conversion of type somewhere, or that an expression has evaluated to a result larger than expected.

Java handles overflow differently for integers than it does for floating point values. If an integer overflows, only the least significant bits are stored. Remember that each Integral data type in Java can represent a certain number of values ”half of which are negative and half of which (including 0) are positive. That means that exceeding the highest possible positive value of an integer type will cause an overflow that results in a negative number (and vice versa). The following program demonstrates :

3.7.1 Overflow.java

 /*  File: chp3.Overflow.java Purpose: demo int overflow Author: E Hewitt */ public class Overflow { public static void main(String[] args) { int x = java.lang.Integer.MAX_VALUE; // prints 2147483647 System.out.println(x); // add 1 to max int value. prints -2147483648 System.out.println("overflow: "+ (x += 1));     } } 

Overflow.java demonstrates the wrapping that occurs with an integer overflow. Floating point expression overflow, however, does something different. When a double or a float overflows, the result is positive infinity. When a double or a float underflows; that is, when it becomes a value too small to be represented, the result is 0. Illegal operations (such as dividing by zero) result in NaN (Not a Number). Floating point expressions will not raise exceptions, they will simply conform to one of these predefined modes. See Section 3.10, titled "Java Standard Classes," for more information about how MAX_VALUE is used in this program.

If you are really in need of performing unbounded arithmetic on integers or floating point numbers , the java.Math package makes available two classes for you to use: BigInteger and BigDecimal . As you might guess, these perform more slowly than their primitive counterparts, which is why they are defined separately. In general, int s, double s, and float s will be just fine.


   
Top


Java for ColdFusion Developers
Java for ColdFusion Developers
ISBN: 0130461806
EAN: 2147483647
Year: 2005
Pages: 206
Authors: Eben Hewitt

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