Literals
1. What Is a Literal? (beginner)
A literal = value you type directly in code (not in a variable yet). 87, 3.14, 'A', "hi", true are all literals. Each has a type the compiler assumes.
2. Types with Examples (exam list)
| Literal kind | Examples | Notes |
|---|---|---|
| Integer | 10, 010 (octal!), 0xA (hex), 0b101 (binary), 1_000 |
default int; L → long |
| Floating | 3.14 (double), 3.14f (float), 1e3 (=1000.0) |
default double |
| Character | 'A', `' |
|
'(newline),'\u0041'` (=A) |
single quotes only | |
| String | "hi", `"a |
|
| b"` | double quotes, + joins |
|
| Boolean | true, false |
no 0/1 in Java! |
| Null | null |
no object (references only) |
3. Code — Literals That Surprise Beginners
public class Lit {
public static void main(String[] args) {
System.out.println(010); // 8! (leading 0 = octal)
System.out.println(0xA); // 10 (hex)
System.out.println(1_000_000); // 1000000 (_ for readability)
System.out.println('A' + 1); // 66 (char + int = int!)
System.out.println("5" + 5); // "55" (String + int = String!)
// int x = null; // ERROR — null only for objects
String s = null; // ok
}
}
4. Traps
"A"(String) ≠'A'(char) — quotes matter.010is octal (8), not ten! Never pad integers with 0.3.14is double:float f = 3.14;fails, need3.14f.
5. Exam Points
- Literal types + suffixes (
L,f,_) — 5 marks, frequent. - Octal/hex/binary + escape (
,\u) — 3 marks, frequent. - Predict output (
"5"+5,'A'+1) — 2-3 mark favourite.