Integer in parentheses not compiling - Why?
The compilation error is pretty clear: you are using the int
literal which is out of range. If you really want to do it, you may use long
literal:
int b = (int) -(2147483648L);
Or double
literal:
int b = (int) -(2147483648.0);
Max value of int is 2147483647
and min value of int is -2147483648
. But when you put 2147483648
into braces it initially consider as +2147483648
and it is not in valid for int rage.
int values go from -2147483648
to 2147483647
. So -(2147483648)
is OutOfRange because the value inside the brackets is evaluated as an int
. The max value you can put into the brackets is
Integer.MAX_VALUE //Which is equals to 2147483647
The reason is that the int
datatype has valid values in the range [-2147483648, 2147483647]
.
When you wrap 2147483648
inside parentheses, it becomes an expression that will be evaluated as an int
. However, 2147483648
is too big to fit in an int
(too big by one).
The problem does not happen for -2147483648
because it is a valid int
value.
Relevant parts of the JLS:
- adding parentheses creates a "Parenthesized Expressions" (section 15.8.5)
- an integer literal, such as
2147483648
, is treated as anint
by default (section 3.10.1)An integer literal is of type
long
if it is suffixed with an ASCII letterL
orl
(ell); otherwise it is of typeint
(§4.2.1).