☕ Java Foundations · Beginner

Keywords & reserved words in Java

Reserved keywords, contextual keywords (var, record, yield, sealed) and literals true/false/null.

🧩 The mysteryint 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;   // ok

Reserved 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.

⚠️ The trap

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.

🔮 Predict it

Your turn

Is this legal Java? What does it print?

var var = 3;
System.out.println(var * 2);
  1. 6
  2. Compile error
  3. varvar
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 the real world

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

  1. Reserved keywords can never be identifiers
  2. goto and const are reserved even though Java doesn't use them
  3. Contextual keywords (var, record, yield, sealed) are special only in context
  4. true, false and null are literals
🤯 Did you know?

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?

  1. String
  2. goto
  3. const
  4. 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);
  1. Compile error
  2. 6
  3. var1
  4. 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.

Next: two kinds of mistakes. The ones javac catches before running, and the ones that blow up while running.