Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Overflow Handling in Java

Status
Not open for further replies.

madhes

Programmer
Apr 16, 2001
18
US
Hi,
Is there any direct way to find, whether overflow occured in a computation, in Java. For eg., assume the following code segment:
Code:
byte a = 10, b = 120, c = a + b;
here, overflow occured and 'c' wil have a wrong value, instead of 130, (since a byte can hold only upto +128). I just want to know is there any specific way to check whether overflow occured or not.
thanks,
madhes
 
Actually, the code:
Code:
byte a  = 10;
byte b  = 120;
byte c = a + b;
Does not compile with my version of javac, instead it complains:
[tt]
Overflow.java:line-no: possible loss of precision
found: int
required: byte
byte c = a + b;
^
1 error
[/tt]
What you should do therefore is:
Code:
try {
    int c = a + b;
    if( (byte)c != c ) {
        throw new Exception( "byte overflow occured" );
    }
} catch( Exception e ) {
    e.printStackTrace();
}
Anyone with a more elegant answer? Cheers Neil :)
 
Thanks.
The results are casted to the upper types, for only byte and short. If the operands are of integer types, the result will be again an integer, & compiler will not throw any error. Since we use int and long in our applications widely, i need a mechanism to detect the overflow.
Consider the following example,
Code:
int a = Integer.MAX_VALUE, b = 2; 
long c = a + b; (or) int c = a + b;
The above expression, gives the result as -2147483647, which is wrong. When we cast the result into long, then we get the correct result.
i.e.,
Code:
long c = (long) a + b; // CORRECT, now c = 2147483649.
OK.
Now i come to my problem. Since, java doesnt have any mechanism to handle the overflow, i wrote the code like, for adding two integers,
Code:
boolean isOverFlow(int a, int b) {
    long result = (long) a + b;
    if (result < Integer.MIN_VALUE || result > Integer.MAX_VALUE) {
        return true;
    }
    return false;
}
I just want to know, is there any better mechanism than this.
thanks,
Madhes.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top