Literals in Java
Decimal, hex 0x, binary 0b, octal 0, underscores, L and f/d suffixes, char literals.
017 is not seventeen. 3000000000 won't compile, even in a long. Literals hide surprising rules; let's crack them.Values written in code
A literal is a value typed directly into code: 42, 3.14, 'A', "hi", true. Integer literals can be written in four bases, all meaning the same number here:
int dec = 31;
int hex = 0x1F; // hexadecimal
int bin = 0b11111; // binary
int oct = 037; // octal!The leading-zero trap
A leading 0 makes an integer literal octal (base 8). 017 is 1×8 + 7 = 15, not seventeen. Padding numbers with zeros "to line them up" silently changes their values.
int a = 17; // 17
int b = 017; // 15!Your turn
Hex, octal and binary walk into a println. What does it print?
System.out.println(0x20 + 020 + 0b100);52140Compile error
Show the answer
0x20 is hex 32, 020 is octal 16, 0b100 is binary 4: 32 + 16 + 4 = 52.
Underscores for readability
Since Java 7 you can group digits with underscores: 1_000_000 is one million. The compiler ignores them. They're only allowed between digits: 1_000_ and _1000 don't work as numbers.
int million = 1_000_000; // ok
int bad = 1_000_; // errorSuffixes pick the type
An integer literal is an int unless it ends with L (long). A decimal literal is a double unless it ends with f (float); d is optional. Single quotes make a char, double quotes a String.
long big = 3_000_000_000L;
float f = 1.5f;
double d = 1.5; // d optional
char c = 'A';
String s = "A";Your turn
What happens?
float price = 1.5;
System.out.println(price);1.5Compile error1.50
Show the answer
Compile error. 1.5 is a double literal, and a double can't go into a float without a cast. Write 1.5f. Same idea: long n = 3000000000; fails with "integer number too large", because without L it's an int literal. Write 3000000000L.
In real projects
Hex shows up constantly: colors like 0xFF5733, byte values in network protocols, file signatures. Binary literals make bit flags readable, and underscores make 1_000_000_000 reviewable at a glance.
Key takeaways
- 0x1F hex, 0b101 binary, 017 octal (leading zero!)
- 1_000_000: underscores only between digits
- L suffix → long; f suffix → float; d optional for double
- 'A' is a char, "A" is a String
Write long literals with a capital L. 10l is legal, but the lowercase l looks almost exactly like the digit 1, so it reads like 101.
Practice questions
What does this print?
System.out.println(010 + 0x10 + 0b10);- 26
- 30
- 101010
- Compile error
Check your answer
26. 010 is octal (8), 0x10 is hex (16) and 0b10 is binary (2): 8 + 16 + 2 = 26.
What does this print?
long big = 3000000000;
System.out.println(big);- Compile error
- 3000000000
- -1294967296
- Throws ArithmeticException
Check your answer
Compile error. Without an L suffix, 3000000000 is an int literal, and it's too large for int. javac reports "integer number too large". Write 3000000000L.