Keywords & reserved words in Java
Reserved keywords, contextual keywords (var, record, yield, sealed) and literals true/false/null.
int class = 5; won't compile. But int var = 5; does! Why does Java treat these two words so differently?Reserved keywords
Words like class, int, if, while, return and static are part of Java's grammar. Their meaning is fixed, so they can never be used as names.
int class = 5; // error: keyword
int klass = 5; // okReserved but unused
goto and const are reserved keywords even though Java doesn't use them for anything. They're blocked on purpose, so C-style habits can't sneak in.
String is not a keyword
It feels built in, but String is just a class in the java.lang package, like System and Integer. Java's keywords are all lowercase: int is a keyword, String is a class name.
Literals: true, false, null
true, false and null are technically literals (values), not keywords. They still can't be used as names, so in practice they behave just like keywords.
Contextual keywords
var, record, yield and sealed are contextual keywords: special only in certain positions. var is special only where a type is written. Elsewhere it's an ordinary name, which kept older code that used these words compiling.
Your turn
Is this legal Java? What does it print?
var var = 3;
System.out.println(var * 2);6Compile errorvarvar
Show the answer
6. The first var sits in the type position, so it means "infer the type". The second is just a variable named var. Legal, but please don't do this at work!
In real projects
When Java 10 added var, making it a full keyword would have broken every program with a variable named var. Contextual keywords let Java evolve without breaking millions of lines of old code.
Key takeaways
- Reserved keywords can never be identifiers
- goto and const are reserved even though Java doesn't use them
- Contextual keywords (var, record, yield, sealed) are special only in context
- true, false and null are literals
Since Java 9 a lone underscore _ is a keyword. Java 22 gave it a job: naming variables you deliberately don't use.
Practice questions
Which of these is NOT a reserved keyword?
- String
- goto
- const
- static
Check your answer
String. String is just the name of a class in java.lang. goto and const are reserved even though they have no meaning in Java, which prevents C-style misuse.
What does this print?
int var = 5;
System.out.println(var + 1);- Compile error
- 6
- var1
- 51
Check your answer
6. var is a contextual keyword (a reserved type name). It's only special where a type is expected, so it still works as a variable name, though it's best avoided.