Why java Number / Numeric datatypes such as (Integer/Long/…) doesnt throw overflow exception?
For example: We get mathematically wrong answer for following
Integer val = Integer.MAX_VALUE * 2;
System.out.println("Max val unexpected" + val);
** Max val unexpected-2**
I know; at the core these datatypes use primitive java datatypes.
Still , isn’t a good idea to prevent wrong answer by throwing something like..ValueOverflowException.
Thought of extending and adding this behaviour but these all classes are final..
Please post your thoughts & opinions.
Those types are just wrappers for the primitive types, and so it would be unexpected if they behaved differently. One reason those types do not throw those exceptions is that it would be incredibly costly if such checks were performed, and these integral types on the processor don’t trigger interrupts when they overflow (whereas, by contrast, the floating point types can trigger interrupts for various events). If you are looking to support arbitrary precision, then you might be interested in the BigInteger type.