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).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…