Concept Explanation
A literal is a value written literally into your code. In int score = 100;, the 100 is an integer literal. Variables are labelled boxes; literals are the things you put in them.
Java has a literal form for each kind of data, and a few notation tricks worth knowing.
Literals by Type
// Integer literals
int decimal = 42;
int binary = 0b101010; // 0b prefix -> 42
int octal = 052; // leading 0 -> 42
int hex = 0x2A; // 0x prefix -> 42
// Long needs an L suffix when the value exceeds int range
long population = 8_100_000_000L;
// Floating point: double by default, F forces float
double pi = 3.14159;
float ratio = 2.5F;
double scientific = 1.6e-19; // 0.00000000000000000016
// Character literals use SINGLE quotes
char grade = 'A';
char newline = '\n';
char unicode = '\u0041'; // also 'A'
// String literals use DOUBLE quotes
String greeting = "Hello";
// Boolean and null
boolean active = true;
String missing = null;
Underscores for Readability
Since Java 7 you may place _ inside numeric literals. The compiler ignores them entirely:
int million = 1_000_000;
long cardNum = 1234_5678_9012_3456L;
int bitMask = 0b1010_0101;
This is purely for human eyes — 1_000_000 and 1000000 are the same value.
Text Blocks (Java 15+)
For multi-line strings, triple quotes beat endless \n:
String json = """
{
"name": "Ada",
"role": "engineer"
}
""";
Common Mistakes
- Missing the L:
long big = 10000000000;fails — the literal is treated as anintbefore assignment and overflows. - Missing the F:
float f = 3.14;fails, because3.14is adouble. Write3.14F. - Accidental octal:
int code = 0755;is 493, not 755. A leading zero means octal. - Quote confusion:
'Hello'is invalid — single quotes hold exactly one character.
Best Practices
- Underscore long numbers:
50_000_000is far easier to verify than50000000. - Uppercase suffixes: Prefer
100Lover100l— lowercase L looks like the digit 1. - Name your magic numbers:
final double TAX_RATE = 0.08;beats scattering0.08through your code.
Practice Exercises
- The Four Notations: Write the number 255 as a decimal, binary, octal, and hexadecimal literal, then print all four and confirm they match.
- The Overflow: Try
long distance = 9999999999;without theL, read the error, then fix it. - The Readable Constant: Declare the speed of light in metres per second as a
longusing underscores for grouping.