Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does JLS state that the largest int literal is 2147483648?

Tags:

java

jls

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?

like image 904
Evgeniy Dorofeev Avatar asked Dec 09 '22 15:12

Evgeniy Dorofeev


2 Answers

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.

like image 60
Bohemian Avatar answered Jan 18 '23 01:01

Bohemian


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.

like image 32
Bert F Avatar answered Jan 18 '23 03:01

Bert F