Search code examples
javaintmultiplicationprimitive-typessystem.out

Printing large multiplied numbers in java


I'm doing an AP Comp Sci Review sheet and I do not understand why when I compile

System.out.println(365 * 24 * 3600 * 1024 * 1024 * 1024); the answer is 0. I understand that an int is 32 bits and has a maximum of 2147483647 and could not give you 3386152216166400 but why wouldn't it give an overflow exception error or a similar error?


Solution

  • From the Java Language Specification,

    The integer operators do not indicate overflow or underflow in any way.

    That's why you are not getting any exception.

    The results are specified by the language as follows,

    If an integer multiplication overflows, then the result is the low-order bits of the mathematical product as represented in some sufficiently large two's-complement format. As a result, if overflow occurs, then the sign of the result may not be the same as the sign of the mathematical product of the two operand values.

    Integer.MAX_VALUE + 1 == Integer.MIN_VALUE
    
    Integer.MIN_VALUE - 1 == Integer.MAX_VALUE 
    

    That's why you are getting zero as the result.