Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

The limit of int is from -2147483648 to 2147483647.

If I input

int i = 2147483648;

then Eclipse will prompt a red underline under "2147483648".

But if I do this:

int i = 1024 * 1024 * 1024 * 1024;

it will compile fine.

public class Test {
    public static void main(String[] args) {        

        int i = 2147483648;                   // error
        int j = 1024 * 1024 * 1024 * 1024;    // no error

    }
}

Maybe it's a basic question in Java, but I have no idea why the second variant produces no error.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
149 views
Welcome To Ask or Share your Answers For Others

1 Answer

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...