Possible Duplicate:
Why don't Java Number datatypes overflow?
In Java, when keeping on incrementing a Byte
value and when it exceeds the size capacity, why is it not throwing any runtime exception ? For example:
public static void main(String[] args) {
byte b = 127;
++b;
System.out.println(b);
}
The above code will print -128
. Will it not be better if it throws RuntimeException
? Why is it designed this way?
Same case for other primitive types too, for Integer
:
int c = 2147483647;
++c;
System.out.println(c);
The above code prints -2147483648
.
Integer overflow is actually quite useful in computing. If it threw exceptions, lots of clever algorithms would suddenly break or become impractical. For example, anything involving fixed-point arithmetic would suddenly be plagued with exceptions.
The thing is, overflow is not normally a problem because we put limits into our programs to prevent it from happening (if it would lead to problems). Other times, we design programs to specifically exploit it.
Don't think of overflow as "a value exceeding its maximum size". That is not technically possible. The bits simply wrap around and stay within that data type's limits.
If you need to check for overflow and want to generate exceptions, you can do this:
byte b = 127;
byte oldb = b;
b++;
if( b < oldb ) {
// Calamity!!! Raise an exception!
}
Do not fear your integer limits. Learn to understand and work with them.
It is stated in the JVM Specs: "Despite the fact that overflow may occur, execution of an iadd instruction never throws a runtime exception."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With