Why is inti = 1024 * 1024 * 1024; compiled without errors?

Asked 2 years ago, Updated 2 years ago, 65 views

The expression range of int is from -2147483648 to 2147483647. So inti = 2147483648; and then in Eclipse, you get a red underline for "2147483648." inti = 1024 * 1024 * 1024 * 1024; this compiles well.

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

        inti = 2147483648; // Error
        int j = 1024 × 1024 × 1024 × 1024; // No error

    }
}

It's a basic question, but why?

java int

2022-09-21 15:55

1 Answers

There's nothing wrong with that phrase. It's just an operation that multiplies four numbers, and it only causes an overflow. That's different from just assigning a single character, but at compile time, we do a boundary check.

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

This syntax checks that the string crosses a boundary. If the boundary is crossed, it is not assigned.

System.out.println(2147483648L); // no error If you tell the string that it is Long, the compilation is good.


2022-09-21 15:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.