2

I just had a hard time finding a bug which was being caused due to a large sum of positive ints being greater than Integer.MAX_VALUE.

My question is: why:

val a:Int = Integer.MAX_VALUE + 2

-> a = -2147483648 returns a negative number, as opposed as giving an overflow exception like doing:

val b:Int =999999999999999999

-> error: integer number too large

Why is not throwing an exception the standard?

2
  • because first done by Scala and another by you Commented Jul 8, 2015 at 11:10
  • 1
    The important point here is that the error you see in the val b case isn't an exception—it happens at compile-time, not runtime. Having the compiler reject invalid literals is cheap, runtime checking for overflows is expensive. Commented Jul 8, 2015 at 11:27

2 Answers 2

3

Adding checks costs performance and some code could rely on how overflows work.

If you don't want an overflow Java 8 has a solution:

Math.addExact(left, right);

https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#addExact-int-int-

Sign up to request clarification or add additional context in comments.

1 Comment

Interesting! I am currently working with java 7 but I will keep this in mind
2

Short answer: performance.

Long answer:

The basic "binary" system doesn't have anything built in to represent negative numbers, it consists of only 0's and 1's. The question is: how do we represent negative numbers using only 0's and 1's?

The standard answer is to use the two's-complement format. A simple example for a 3-bit binary system: 000 means 0, 011 means 3, 111 means -1 (makes sense as when you substract 1 from 0, you want -1), 100 means -3. If you add 1 to 011 or 3, you get 111 or -3.

Now, why doesn't that cause an overflow exception? Two reasons:

  1. Exception itself is a relatively new concept and it was too late to change the binary system the computing hardware world uses.

  2. Condition checking and throwing exception is an overhead that has a performance cost. If we want high performance, these are often unnecessary. There is performance gain if there is no explicit checking done for any overflow exception.

1 Comment

I knew the operation that generated the negative number. Also It is good to understand why the check is not taking place, thanks :).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.