Decimal Integer literals

suggest change

Integer literals provide values that can be used where you need a byte, short, int, long, or char value. (This example focuses on the simple decimal forms. Other examples explain how to write literals in octal, hexadecimal, and binary, and how underscores improve readability.)

Ordinary integer literals

The simplest and most common form of integer literal is a decimal integer literal. For example:

0       // The decimal number zero       (type 'int')
1       // The decimal number one        (type 'int')
42      // The decimal number forty two  (type 'int')

You need to be careful with leading zeros. A leading zero causes an integer literal to be interpreted as octal not decimal.

077    // This literal actually means 7 x 8 + 7 ... or 63 decimal!

Integer literals are unsigned. If you see something like -10 or +10, these are actually expressions using the unary - and unary + operators.

An integer literal of this form has type int and must fall in the range zero to 231 (2,147,483,648).

Note that 231 is 1 greater than Integer.MAX_VALUE. Literals from 0 through 2147483647 can be used anywhere, but it is a compilation error to use 2147483648 without a preceding unary - operator. (That form is reserved for expressing Integer.MIN_VALUE.)

int max = 2147483647;     // OK
int min = -2147483648;    // OK
int tooBig = 2147483648;  // ERROR

Long integer literals

Literals of type long are expressed by adding an L suffix. For example:

0L          // The decimal number zero       (type 'long')
1L          // The decimal number one        (type 'long')
2147483648L // The value of Integer.MAX_VALUE + 1

long big = 2147483648;    // ERROR
long big2 = 2147483648L;  // OK

Note that the distinction between int and long literals is significant in other places. For example

int i = 2147483647;
long l = i + 1;           // Produces a negative value because the addition is
                          // performed with 32-bit arithmetic and overflows
long l2 = i + 1L;         // Produces the (intuitively) correct value.

Reference: JLS 3.10.1 - Integer Literals

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents