Question

JLS 3.10.1. Integer Literals http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.1 states

The largest decimal literal of type int is 2147483648.

At the same time this line

int x = 2147483648;

produces a compile error

The literal 2147483648 of type int is out of range

Is JLS wrong?

Was it helpful?

Solution 3

The largest decimal literal of type int is 2147483648 (231).

All decimal literals from 0 to 2147483647 may appear anywhere an int literal may appear. 

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

OTHER TIPS

It is poorly worded IMHO. What it's trying to say us that in this expression:

-2147483648

The minus sign is not part of the integer literal, rather the minus sign is the unary minus operator and 2147483648 is the int literal, and integer literal 2147483648 may only appear in this exact expression.

Is JLS wrong?

No, the JLS is being specific - differentiate between an int variable and an "int literal", i.e. decimal literal of type int.

The range of an int variable is -2,147,483,648..2,147,483,647 (i.e. -(2^31)..2^31-1)

The largest decimal literal the compiler will parse in Java code and use in an int context is 2,147,483,648, but it can only be used as the operand of the unary '-' operator, that is to say, you can only use it in only one way - to construct the most negative decimal value an int can hold: -22147483648.

In that section of the JLS you mention, section 3.10.1 Integer Literals, where it says:

The largest decimal literal of type int is 2147483648 (2^31).

is also says a few lines later:

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top