🔥 What are Literals in Java?
Definition
Literals in Java are fixed, constant values that you write directly in your code. These are “hardcoded” values that represent themselves.
📦 Examples of Literals (Directly Represented Values)
| Type | Example | Explanation |
|---|---|---|
| Integer Literal | 100, -25 | Whole numbers |
| Floating-point Literal | 3.14, -0.001 | Decimal numbers |
| Character Literal | 'A', '9' | Single characters (always in single quotes) |
| String Literal | "Hello", "Java" | Text (always in double quotes) |
| Boolean Literal | true, false | Boolean values |
| Null Literal | null | Special literal representing “no object” |
✅ Simple Rule
If you type it directly into your code, and it’s a fixed value (not a variable or expression), it’s a literal.
🚫 What is NOT a Literal?
Here are things that are NOT literals:
| Not Literal | Example | Explanation |
|---|---|---|
| Variable | int x = 10; | x is not a literal (but 10 is) |
| Expression | 5 + 3 | This is an expression (combines literals to compute a result) |
| Method Call Result | Math.sqrt(4) | This is a computed value, not a literal |
| Object Reference | new String("hello") | new String(...) creates an object, not a literal |
📝 Special Case: String Pool
Even though "Hello" is a literal, when you do:
String s = "Hello";
The literal "Hello" gets stored in the String Pool, but s itself is a variable that points to it.
The literal is "Hello" — the value written directly in the code.
🔧 Quick Test
Which of these are literals?
int x = 5; // 5 is a literal, x is not.
String s = "Java"; // "Java" is a literal, s is not.
boolean b = true; // true is a literal, b is not.
double pi = 3.14159; // 3.14159 is a literal, pi is not.
int sum = x + 10; // 10 is a literal, x + 10 is an expression.
System.out.println("Hi"); // "Hi" is a literal.
✅ Summary Table
| Example | Is Literal? | Why? |
|---|---|---|
"Hello" | ✔️ | Direct value written into the code |
42 | ✔️ | Direct value written into the code |
true | ✔️ | Direct value written into the code |
myVariable | ❌ | This is a variable name, not a literal |
x + y | ❌ | Expression, not a literal |
new Object() | ❌ | Creates an object, not a literal |