Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why no overflow when byte exceeds size? [duplicate]

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.

like image 627
Karthik Avatar asked Jul 31 '12 04:07

Karthik


2 Answers

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.

like image 197
paddy Avatar answered Nov 15 '22 02:11

paddy


It is stated in the JVM Specs: "Despite the fact that overflow may occur, execution of an iadd instruction never throws a runtime exception."

like image 43
Andriy Plokhotnyuk Avatar answered Nov 15 '22 03:11

Andriy Plokhotnyuk