In Java, a literal is a source code representation of a fixed value. They are represented directly in the code and are used to represent values such as integers, floating-point numbers, characters, and strings. The following literals are available in Java:
- Integral Literals / Integer Literals
- Floating Point Literals
- Boolean Literals
- String Literals
1. Integral Literals / Integer Literals
These can be written in decimal (base 10), hexadecimal (base 16) or octal (base 8) notation. The Integer Literals are:
long number = 12345; int n = 1223; short s = 12; byte b = 13; char c = 'A';
In the above example all the values
A are integer literals.
2. Floating Point Literals
These represent decimal values and are written with a decimal point and an optional exponent. Following are the floating point literals:
float f = 123.45f; double d = 12345.6789;
Any values assigned to these data types are literals. Hence, the value
12345.6789 are floating point literals.
3. Boolean Literals
The value assigned to boolean variables is literals. Hence, the value
false boolean literals.
4. String Literals
The value assigned to the String type is all literal. These are sequences of characters enclosed in double quotes.
The value inside double quote ” are string literals. For example:
"5", "true", "Radha Krishnan", "123.45", "1234.4567"
5. Null Literals
The null literal is the special literal
null that represents a null reference, which is a reference that does not refer to any object.
Student student = null;
In the following integral literal it is very hard to read the value.
int number = 986456354;
But, after JDK version 1.7 Java has started to support underscore ‘_’ inside integral literals so that we can separate literals and easily read the representation of the word by the developer/programmer. If we try to read the value it is very hard but in the following example, we can easily read it like Ninety-Eight Crore Sixty Four Lakhs Fifty Six Thousands Three Hundred Fifty Four.
int number = 98_64_56_354;
During the compile time, the compiler automatically removes these extra characters inside the integral literal and keeps only the number so that it does not affect the actual value.
Leave a Reply