Why does JLS claim the largest int literal is 2147483648?

JLS 3.10.1. Integer Literals 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; 

creates a compilation error

 The literal 2147483648 of type int is out of range 

Is JLS Wrong?

+4
source share
3 answers

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. 

This is a compile-time error if the decimal literal of type int is greater than 2147483648 (231), or if the decimal literal 2147483648 appears anywhere except as an operand of the unary minus operator (ยง15.15.4).

+3
source

He poorly formulated IMHO. What is he trying to tell us in that expression:

 -2147483648 

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

+6
source

Is JLS Wrong?

No, JLS is specific - to distinguish between an int variable and an "int literal", that is, a decimal literal of type int.

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

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

In this JLS section, you mention section 3.10.1 Integer literals , which say:

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

also says a few lines later:

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

+5
source

Source: https://habr.com/ru/post/1479085/


All Articles