Java Overflow And Underflow
October 13th, 2009Overflow and underflow is a condition where you cross the limit of prescribed size for a data type. When overflow or underflow condition is reached, either the program will crash or the underlying implementation of the programming language will have its own way of handing things.
In Java arithmetic operators don’t report overflow and underflow conditions. They simply swallow it! It is a very dangerous thing to do. If one doesn’t know how Java handles overflow and underflow then he will not be aware of things happening behind while doing arithmetic operations.
Overflow and Underflow in Java int operators
Arithmetic integer operations are performed in 32-bit precision. When the resultant value of an operation is larger than 32 bits (the maximum size an int variable can hold) then the low 32 bits only taken into consideration and the high order bits are discarded. When the MSB (most significant bit) is 1 then the value is treated as negative.
Overflow and Underflow in Java floating point operators
While using java floating point operators, overflow will result in Infinity and underflow will result 0.0 As a general rule here also Java doesn’t throw an error or exception for overflow and underflow.
Important points to remember for java overflow and underflow
- Overflow or underflow conditions never throw a run time exception
- Flowed output is predictable and reproducible. That is, its behaviour is the same every time you run the program.
Example source code for overflow and underflow
public class OverflowUnderflow {
public static void main(String args[]){
//roll over effect to lower limit in overflow
int overflowExample = 2147483647;
System.out.println("Overflow: "+ (overflowExample + 1));
//roll over effect to upper limit in underflow
int underflowExample = -2147483648;
System.out.println("Underflow: "+ (underflowExample - 1));
byte b = 127;
// following line uncommented results in compilation error
// constants are checked at compile time for size
// b = b*b;
double d = 1e308;
System.out.println(d + "*10= " + d*10);
//gradual underflow
d = 1e-305 * Math.PI;
System.out.print("gradual underflow: " + d + "\n ");
for (int i = 0; i < 4; i++)
System.out.print(" " + (d /= 100000));
}
}
Output:
Overflow: -2147483648 Underflow: 2147483647 1.0E308*10= Infinity gradual underflow: 3.141592653589793E-305 3.1415926535898E-310 3.141592653E-315 3.142E-320 0.0


