Literal Formats for Integers

This section describes 4 literal formats for integer values: decimal, hex, octal and binary integer literals. The default integer literal data type is 'int'.

Java supports literals for 2 integer data types in 4 formats described below:

1. Decimal Integer Literal - Basic rules on decimal integer literals:

• A sequence of decimal digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9, with no leading 0s can be used to represent a positive integer values in "int" data type. Examples are: 911 and 1024.
• To specify values in "long" data type, suffix L or l can be added. Examples are: 911L and 1024l.
• To increase readability, _ can be used as group separators. Examples are: 9_11L and 1_024.

2. Hex Integer Literal - Basic rules on hex integer literals:

• A sequence of hex digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, a, B, b, C, c, D, d, E, e, F and f, with a prefix of 0x or 0X can be used to represent an integer values in "int" data type. Examples are: 0x38F and 0X400.
• To specify values in "long" data type, suffix L or l can be added. Examples are: 0x38FL and 0X400l.
• To increase readability, _ can be used as group separators. Examples are: 0xDada_Cafe and 0X400_400L.
• If the first bit of a 32-bit "int" or the 64-bit "long" literal is set to 1, it will be evaluated as a negative integer. Examples are: 0x8000_0000 and 0x8000_0000_0000_0000L.

3. Octal Integer Literal - Basic rules on octal integer literals:

• A sequence of octal digits: 0, 1, 2, 3, 4, 5, 6, and 7, with a prefix of 0 can be used to represent an integer values in "int" data type. Examples are: 01617 and 02000.
• To specify values in "long" data type, suffix L or l can be added. Examples are: 01617L and 02000l.
• To increase readability, _ can be used as group separators. Examples are: 033_266_545_376 and 02000_2000L.
• If the first bit of a 32-bit "int" or the 64-bit "long" literal is set to 1, it will be evaluated as a negative integer. Example is: 020000000000.

4. Binary Integer Literal - Basic rules on binary integer literals:

• A sequence of octal digits: 0, and 1, with a prefix of 0b or 0B can be used to represent an integer values in "int" data type. Examples are: 0b1110001111 and 0B10000000000.
• To specify values in "long" data type, suffix L or l can be added. Examples are: 0b1110001111L and 0B10000000000l.
• To increase readability, _ can be used as group separators. Examples are: 0b11_1000_1111L and 0B10_000_000_000.
• If the first bit of a 32-bit "int" or the 64-bit "long" literal is set to 1, it will be evaluated as a negative integer. Example is: 0b1000_0000_0000_0000_0000_0000_0000_0000.

Last update: 2014.