Search code examples
javanumbersdoubleinteger-overflowdouble-precision

different overflow policy for Double and Integer. why?


this code

System.out.println(Double.MAX_VALUE+12345 == Double.MAX_VALUE);
System.out.println(Integer.MAX_VALUE+12345 == Integer.MAX_VALUE);

returns

true
false

Please clarify this difference.


Solution

  • The rules are the same, it's just that Double.MAX_VALUE is so large that 12345 is roughly 300 orders of magnitude (10300 times) smaller. Adding a number that is so much smaller than Double.MAX_VALUE does not change its value. Adding a number that is of the same order of magnitude would make a difference, though:

    Double.MAX_VALUE + 1E300
    

    produces a positive infinity result, which is not the same as Double.MAX_VALUE (demo)