Why does int i = 1024 * 1024 * 1024 * 1024 compile without error?

There’s nothing wrong with that statement; you’re just multiplying 4 numbers and assigning it to an int, there just happens to be an overflow. This is different than assigning a single literal, which would be bounds-checked at compile-time.

It is the out-of-bounds literal that causes the error, not the assignment:

System.out.println(2147483648);        // error
System.out.println(2147483647 + 1);    // no error

By contrast a long literal would compile fine:

System.out.println(2147483648L);       // no error

Note that, in fact, the result is still computed at compile-time because 1024 * 1024 * 1024 * 1024 is a constant expression:

int i = 1024 * 1024 * 1024 * 1024;

becomes:

   0: iconst_0      
   1: istore_1      

Notice that the result (0) is simply loaded and stored, and no multiplication takes place.


From JLS §3.10.1 (thanks to @ChrisK for bringing it up in the comments):

It is a compile-time error if a decimal literal of type int is larger than 2147483648 (231), or if the decimal literal 2147483648 appears anywhere other than as the operand of the unary minus operator (§15.15.4).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)