Java integer literals

Integer Literal : Integer Data Type in Java Programming

Theoretically Literal means - Any number,Text or Other information that represents a VALUE.

Different Values that can be assigned to Integer Variable (Integer Literal are) :

  1. Decimal Literals
  2. Octal Literals
  3. Hexadecimal Literals
  4. Binary Literals
  5. Long Literals
  6. Values with Underscore in Between
[468x60]
Literal Type Assignment Statement Explanation
Decimal Type
int num = 20;
Decimal 20 is assigned to the variable num
Octal Type
int num = 020;
020” is octal number , so first octal number is converted into integer and then it is assigned to variable “num
Hexadecimal Type
int num = 0x20;
0×20” is hexadecimal number ,
It is first converted into Decimal then
assigned to variable “num
Binary Type
int num = 0b1010;
0b1010” is binary number , assigned to the variable “num” after converting it into decimal number
Long Type
long num = 563L;
562L” is long number , assigned to the variable “num

Using Underscore in Integer Literal

  1. In JDK 7, we can embed one or more underscores in an integer literal.
  2. It makes easier to read large integer literals.
  3. When the literal is compiled, the underscores are discarded.
int num = 19_90;
  1. Java compiler will discard ‘_‘ from the above number and will assign 1990 to variable “num”. Thus it is as good as writing -
int num = 1990;
Literal Using Underscore Actual Value
Integer Literal 45_89 4589
Octal Literal 045_23 Equivalent Octal : 04523
Hexadecimal Literal 0x56_23 Equivalent Hex : 0×5623
Binary Literal 0b1000_1001 Equivalent Binary : 10001001
[468x60]

Note : Using Underscore in Integer

  1. Don’t Use Underscore as first and last character.
  2. It is used to read long number easily.

Literals in Java : Integer | Float | Character | Boolean