Java integer literals
Contents
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) :
- Decimal Literals
- Octal Literals
- Hexadecimal Literals
- Binary Literals
- Long Literals
- Values with Underscore in Between
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
- In JDK 7, we can embed one or more underscores in an integer literal.
- It makes easier to read large integer literals.
- When the literal is compiled, the underscores are discarded.
int num = 19_90;
- 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 |
Note : Using Underscore in Integer
- Don’t Use Underscore as first and last character.
- It is used to read long number easily.
Literals in Java : Integer | Float | Character | Boolean