Literals
Literals are constant values written directly in the code. They represent fixed values assigned to variables.
Example:
int a = 10;
int b = 20;
int c = scan.nextInt();
System.out.println("Hello, World!");
Explanation:
In the above example:
- 10 and 20 are integer literals
- "Hello, World!" is a string literal
- scan.nextInt() is not a literal — it's a method call.
Note:
From Java 7 onwards, the underscore (_) is allowed in numeric literals (except at the beginning or end of the number or next to a decimal point) to improve readability
❌ Invalid:
int salary = 95,000; // Comma is not allowed in numeric literals
✅ Valid:
int salary = 95_000; // Underscore used for readability
You can use underscores in:
- Integer literals
- Floating-point literals
- Binary, Hex, and Octal numbers
Summary:
- Literals are constant fixed values in Java code.
- They can be of types like int, float, char, string, boolean, etc.
- Underscores can be used in numeric literals to improve readability (since Java 7).
- Do not confuse method calls or variable names with literals.