Java int type literals

Introduction

Any whole number value is an integer literal, for examples are 1, 2, 3, and 42.

1, 2, 3, and 42 are all decimal values, which is a base 10 number.

We can use two other bases in integer literals:

  • octal (base 8)
  • hexadecimal (base 16).

Octal values

Octal values are denoted in Java by a leading zero.

We cannot create a normal decimal numbers with a leading zero.

The octal number can only have digits from 0 to 7.

09 will produce an error from the compiler, since 9 is outside of the range of octal: 0 to 7.

Hexadecimal

We create a hexadecimal constant with a leading zero-x, (0x or 0X).

The range of a hexadecimal digit is 0 to 15, so A through F (or f) are substituted for 10 through 15.

Value assignment

When a literal value is assigned to a byte or short variable, and if the literal value is within the range of the target type there will no generated error.

An integer literal can always be assigned to a long variable.

To specify a long literal, explicitly tell the compiler that the literal value is of type long.

You do this by appending an upper- or lowercase L to the literal.

For example, 0x7ffffffffffffffL or 99999999999999999L.

An integer can also be assigned to a char as long as it is within range.

Binary literal

We can specify integer literals using binary.

By prefixing the value with 0b or 0B.

For example, the following code specifies the decimal value 10 using a binary literal:

int x = 0b1010; 

Underscore

We can embed one or more underscores in an integer literal to make it easier to read for large integer literals.

When the literal is compiled, the underscores are discarded.

For example, given

int x = 123_456_789; 

The value given to x will be 123,456,789.

The underscores will be ignored.

Underscores can only be used to separate digits and they cannot come at the beginning or the end of a literal.

We can use more than one underscore between two digits.

For example, this is valid:

int x = 123___456___789; 

For example, the following code combines the binary values in four-digits units, as shown here:

int x = 0b1101_0101_0001_1010; 



PreviousNext

Related