When the maximum value of integer is exceeded (overflow) then the minimum value is assigned to it.
Ex- System.out.println(Integer.MAX_VALUE+1);
Output: -2147483648
Here instead of throwing an exception, the program returns an incorrect value.
How does this feature help the programmers or designers in any way?
Asked
Active
Viewed 79 times
-2

Cache Staheli
- 3,510
- 7
- 32
- 51

Nirmalya Kar
- 511
- 4
- 9
-
This is not an incorrect value, it is absolutely correct - an Integer in Java is a signed 32 bit number - adding 1 to its MAX value loops it back round to its lowest value .. which it what you've got ... http://stackoverflow.com/a/5131206/4252352 – Mark Apr 13 '16 at 00:13
-
Absolutely right on data type point of view @MarkKeen. But when a developer writes code for a calculation (like: int x=3*1000000000) then he do not expect a negative value to be assigned to the variable x. That why I say it as a wrong value on developer point of view. I faced this problem in my project while calculating 3% of a number. I was in misconception that java will through an exception or error but will never calculate a wrong result. – Nirmalya Kar Apr 13 '16 at 19:56
-
So, this is just an opinion on how'd you prefer the overflow to work : Throw an exception, rather than producing an unexpected result? This is an unanswerable question - This is how it works and you already know this, you just have work accordingly, i.e. coding checking / testing / correct variable assigning (int, long etc..). I can't say that there is a programming language out there that does exactly as every person wants and expects ... – Mark Apr 14 '16 at 12:47
2 Answers
0
I just don't think the original implementers of java wanted the overhead of having to check to see if a computation caused an overflow. You can check programatically. For example, How does Java handle integer underflows and overflows and how would you check for it?
It's how traditional C and C++ will handles integers as well, so there is a precedent.

Community
- 1
- 1

Brian Thorpe
- 317
- 2
- 13
-1
It makes code run faster, by not needing to check for overflow after every single arithmetic operation.

SLaks
- 868,454
- 176
- 1,908
- 1,964