In Java, a literal refers to a value that is expressed in source code exactly as it is meant to be interpreted by the compiler. In other words, a literal is a fixed value that is directly used in the code, rather than being stored in a variable or calculated at runtime.
There are several types of literals in Java:
- Integer Literals:
Integer literals represent whole numbers without a fractional part. They can be specified in decimal, hexadecimal, or octal notation. For decimal notation, the digits 0-9 are used. For hexadecimal notation, the prefix 0x or 0X is used followed by the digits 0-9 and letters A-F or a-f. For octal notation, the prefix 0 is used followed by the digits 0-7.
int a = 10; // decimal literal
int b = 0x1F; // hexadecimal literal
int c = 012; // octal literal
- Floating-Point Literals:
Floating-point literals represent numbers with a fractional part. They can be specified in either decimal or scientific notation. For decimal notation, the digits 0-9 are used, along with a decimal point. For scientific notation, the letter e or E is used to indicate the exponent.
float a = 3.14f; // decimal literal
double b = 1.23e-4; // scientific notation
- Character Literals:
Character literals represent a single character enclosed in single quotes.
char a = 'A'; // character literal
- String Literals:
String literals represent a sequence of characters enclosed in double quotes.
String a = "Hello, world!"; // string literal
- Boolean Literals:
Boolean literals represent true or false values.
boolean a = true; // boolean literal
- Null Literal:
The null literal represents a reference that does not refer to any object.
String a = null; // null literal