Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 201 · Getting Started

Java Keywords and Identifiers

See every reserved Java keyword grouped by purpose, the contextual keywords like var, record, sealed and yield, the literals true, false and null, and the rules for identifiers.

Every name in a Java program is either chosen by Java or chosen by you. Keywords are the words Java reserves for its own grammar: class, int, if, return and about fifty others. Identifiers are the names you invent for your classes, methods and variables. The two must never collide, so knowing the keyword list and the exact naming rules saves you from some of the most confusing compiler errors.

This lesson lists all of Java's reserved keywords grouped by what they do, explains the newer contextual keywords such as var, record and yield, and spells out precisely what makes a valid identifier.

Keywords at work

You've already used many keywords without thinking about it. Here's a small program that uses more than a dozen of them. Each one has a fixed meaning that you can't change:

Java Keywords in a real program

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The keywords here are public, class, static, final, int, boolean, return, void, new, for, if and else. Words like Main, PASS_MARK, passed, score, scores and args are identifiers chosen by the programmer. And String and System? They look built-in, but they're ordinary class names from the standard library, so technically they're identifiers too. Editors color keywords differently, which helps you tell them apart.

The reserved keywords

Java has 51 reserved keywords. They can never be used as names, anywhere. Here they are grouped by purpose, with the lesson where each group is taught:

Purpose Keywords
Primitive types and void boolean, byte, char, short, int, long, float, double, void
Control flow if, else, switch, case, default, for, do, while, break, continue, return
Exceptions try, catch, finally, throw, throws, assert
Declaring types class, interface, enum, extends, implements
Access modifiers public, protected, private
Other modifiers static, final, abstract, synchronized, volatile, transient, native, strictfp
Objects and references new, this, super, instanceof
Packages package, import
Reserved but unused goto, const
Special _ (underscore)

Where to learn them: primitive types in Primitive Data Types; control flow from if, else if and else to break, continue and Labels; exceptions in Exceptions and try-catch; classes and modifiers throughout the Object-Oriented Programming chapter; synchronized and volatile in Synchronization and Race Conditions; transient in Serialization; package and import in Packages and Imports.

A few of these deserve a word of explanation:

  • goto and const do nothing at all. Java's designers reserved them so that C and C++ programmers wouldn't accidentally use them, and to keep the option open. Neither was ever given a meaning. (Use final for constants, and labeled break instead of goto.)
  • strictfp is obsolete. It once forced strict floating-point math, but since Java 17 all floating-point math is strict, and the compiler warns that the keyword isn't needed.
  • native marks a method implemented in another language, such as C, through the Java Native Interface. You'll rarely write it yourself.
  • _ became a keyword in Java 9. Since Java 22 it has a job: naming an unnamed variable you don't intend to use (see below).

All keywords are lowercase. Because Java is case-sensitive, Class, INT and For are not keywords. Class is even a real class in the standard library. Using them as names is legal, but deeply confusing, so don't.

What happens when you use a keyword as a name

The compiler's message, unfortunately, rarely says "that's a keyword". Run this program:

Java A keyword as a variable name (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

You get five errors, starting with not a statement and ';' expected. The parser saw the keyword class where it expected a name and got thoroughly confused. When the compiler reports strange syntax errors around a name that looks perfectly fine, check whether the name is a keyword. The same happens with int new = 1;, String goto = ""; or boolean default = true;.

The literals true, false and null

Three more words look like keywords but are technically literals, fixed values written directly in code:

  • true and false are the two values of type boolean.
  • null means "no object": a reference that doesn't point anywhere. You'll meet it properly in Classes and Objects.

The difference between keyword and literal is a fine point of the language specification. In practice they follow the same rule: you can't use true, false or null as names. Trying boolean true = false; fails just like a keyword would.

Contextual keywords

Newer Java features needed new keywords, but adding a reserved word breaks every existing program that happened to use it as a name. A variable called record or var was perfectly legal in 2010. So since Java 9, new keywords are contextual: they have a special meaning only in the specific place where the grammar expects them, and they stay ordinary identifiers everywhere else.

Contextual keyword Special meaning Since
var infers a local variable's type: var count = 0; Java 10
yield returns a value from a switch expression block Java 14
record declares a record class Java 16
sealed, non-sealed, permits restrict which classes may extend a type Java 17
when adds a guard condition to a case pattern Java 21
module, open, requires, exports, opens, uses, provides, to, with, transitive module declarations in module-info.java (and import module declarations) Java 9

Because they're contextual, this program compiles, although it's terrible style:

Java Contextual keywords as plain names

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Look at the last line: it prints non-sealed = 7. Outside a class declaration, non-sealed is just non minus sealed. It's a keyword only where the grammar expects a class modifier, as in non-sealed class Truck extends Vehicle. (It's also the only Java keyword that contains a hyphen.)

Some contextual keywords are a bit more restricted. var, yield, record, sealed and permits can't be used as type names: class var {} fails with 'var' not allowed here and the explanation as of release 10, 'var' is a restricted type name. Since class names start with a capital letter by convention, this almost never matters.

Identifier rules

An identifier is any name you create: for a class, interface, record, enum, method, variable, parameter, field, package or label. The rules are precise:

  1. It may contain letters, digits, the underscore _ and the dollar sign $.
  2. It must not start with a digit. item2 is fine; 2item isn't.
  3. It must not be a reserved keyword or the literals true, false or null.
  4. It can't be just an underscore, _, which is a keyword.
  5. It has no length limit, and it is case-sensitive: total, Total and TOTAL are three different identifiers.

No spaces, hyphens or other punctuation are allowed. first-name is read as first - name, and first name as two separate names. Use firstName instead.

"Letters" means Unicode letters, so names in other alphabets are legal. Most teams stick to English names in ASCII letters anyway, so that everyone can type and read them.

Java Valid identifiers

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The program prints 28. Try uncommenting the invalid lines one at a time to see how the compiler reacts. As with keywords, the messages are usually generic syntax errors like ';' expected or not a statement.

Tip: Legal isn't the same as good. Avoid $ (the compiler itself uses it for generated names, such as nested classes like Outer$Inner) and avoid leading underscores, which are a habit from other languages. Follow the conventions from Java Syntax: camelCase for variables and methods, PascalCase for types, UPPER_SNAKE_CASE for constants.

The underscore: unnamed variables (Java 22)

Sometimes Java's grammar forces you to name a variable you'll never use: a loop variable when you only count iterations, or an exception you catch but don't inspect. Since Java 22, you can write _ instead. It tells both the compiler and the reader "this value is intentionally ignored":

Java Unnamed variables with _

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

An unnamed variable can't be read. Writing IO.println(_); is a compile error, underscore not allowed here. And because it has no name, you can declare _ several times in the same block without a "variable already defined" error. You'll use _ more with record patterns in Pattern Matching.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. Which of these is a valid Java identifier?

    Identifiers can't start with a digit, can't contain a hyphen, and can't be a reserved keyword such as final. secondPlace follows every rule (and the camelCase convention).
  2. 2. Does int var = 5; compile?

    var is special only where a type is expected in a local declaration. As a variable name it is legal, though confusing. It can't be used as a class name.
  3. 3. Which word is reserved in Java but has no meaning at all?

    goto and const are reserved so they can't be used as names, but the language never gave them a meaning. yield is a contextual keyword used in switch expressions.
  4. 4. Are Main, String and System keywords?

    String and System are classes from the standard library, and Main is a name the programmer chose. Keywords are always lowercase, like class or int.
  5. 5. What happens with for (String _ : names) { IO.println(_); } in Java 25?

    _ declares an unnamed variable, which exists only to be ignored. Reading it is a compile error (underscore not allowed here). Give the variable a real name if you need its value.

Summary

  • Keywords are reserved words with fixed meanings; Java has 51, all lowercase, and none can be used as a name.
  • goto and const are reserved but unused; strictfp is obsolete since Java 17; _ has been a keyword since Java 9.
  • true, false and null are literals, and can't be used as names either.
  • Contextual keywords (var, yield, record, sealed, non-sealed, permits, when, and the module words) are special only in certain positions.
  • Identifiers use letters, digits, _ and $, can't start with a digit, can't be a keyword or literal, and are case-sensitive.
  • Using a keyword as a name produces generic errors like not a statement, so check for keywords when a name causes odd syntax errors.
  • Since Java 22, _ names an unnamed variable you intentionally ignore.

Next: Variables, where you'll declare, initialize and update the values your programs work with.