Why is there no overflow when the size of the byte exceeds the size?

Possible duplicate:
Why don't Java Number data types overlap?

In Java, when you keep increasing the value of Byte and when it exceeds the size capacity, why doesn't it throw an exception at runtime? For instance:

 public static void main(String[] args) { byte b = 127; ++b; System.out.println(b); } 

The above code will print -128 . Wouldn't it be better if it throws a RuntimeException ? Why is it designed this way?

In the same case, for other primitive types, for Integer :

 int c = 2147483647; ++c; System.out.println(c); 

The above code prints -2147483648 .

+4
source share
3 answers

Integer overflow is actually quite useful in computing. If he threw exceptions, many smart algorithms would suddenly break down or become impractical. For example, everything related to fixed-point arithmetic suddenly throws exceptions.

The fact is that overflow is usually not a problem, because we limit our programs to prevent it (if this leads to problems). In other cases, we develop programs that specifically use it.

Do not think of overflow as "a value that exceeds its maximum size." This is technically impossible. The bits simply wrap around and remain within these data types.

If you need to check for overflow and want to throw exceptions, you can do this:

 byte b = 127; byte oldb = b; b++; if( b < oldb ) { // Calamity!!! Raise an exception! } 

Do not be afraid of your whole limits. Learn to understand and work with them.

+5
source

The JVM Specs states: "Although an overflow may occur, executing the iadd command never throws an exception at run time."

+1
source

The principle of working with integers and floating point arithmetic is based on how the same operations in C work, which are based on how processors work. Overflow or underflow does not throw an exception (others are flags, which, unfortunately, cannot be accessed by java). There is only one operation that throws an exception and which is a whole division by zero, which causes processor interruption in many types of processors. Floating point division by zero is defined as Not-A-Number, so this does not cause interruption.

0
source

All Articles