Java keywords are words the Java language reserves for its own use — like class, public, static and if. Because the compiler gives them a fixed meaning, you can't use them as names for variables, methods or classes. Java 21 has 51 reserved keywords, plus a set of contextual keywords such as var and record that only act as keywords in certain places.

🎯 What you'll learn
  • The complete list of all 51 Java keywords and what each one does
  • The difference between reserved keywords, contextual keywords and literals (true, false, null)
  • Where var, record and yield can and can't be used
  • The compiler errors you get when you use a keyword as a name — and how to fix them

How Many Keywords Are There in Java?

There are 51 reserved keywords in current Java (Java 9 and later). Java 8 had 50; Java 9 added the underscore _. On top of those, Java has 16 contextual keywords (also called restricted keywords or restricted identifiers) that behave like keywords only in a specific context. Every word in the tables below was checked against the Java 21 compiler.

KindCountCan you use it as a variable name?
Reserved keywords51No — compile error
Contextual keywords16Yes, in most places (see below)
Literals: true, false, null3No — they are not keywords, but they are reserved values
Advertisement

List of All 51 Java Keywords

Grouped by what they do, so they're easier to remember:

KeywordWhat it doesGroup
publicVisible everywhereAccess modifiers
protectedVisible in the same package and in subclassesAccess modifiers
privateVisible only inside the same classAccess modifiers
classDeclares a classClasses, interfaces and objects
interfaceDeclares an interfaceClasses, interfaces and objects
enumDeclares a fixed set of constantsClasses, interfaces and objects
extendsInherits from a class (or interface from interface)Classes, interfaces and objects
implementsA class takes on an interfaceClasses, interfaces and objects
newCreates an objectClasses, interfaces and objects
thisThe current objectClasses, interfaces and objects
superThe parent class (its methods, fields or constructor)Classes, interfaces and objects
instanceofChecks an object's typeClasses, interfaces and objects
abstractClass or method without a full implementationClasses, interfaces and objects
packageDeclares the package of the fileClasses, interfaces and objects
importUses classes from another packageClasses, interfaces and objects
byte8-bit whole numberPrimitive types and void
short16-bit whole numberPrimitive types and void
int32-bit whole numberPrimitive types and void
long64-bit whole numberPrimitive types and void
float32-bit decimal numberPrimitive types and void
double64-bit decimal numberPrimitive types and void
charA single 16-bit characterPrimitive types and void
booleantrue or falsePrimitive types and void
voidA method returns nothingPrimitive types and void
ifRuns code when a condition is trueFlow control
elseRuns code when the if condition is falseFlow control
switchChooses a branch by valueFlow control
caseOne branch of a switchFlow control
defaultFallback branch of a switch; default method in an interfaceFlow control
forLoop with a counter or over a collectionFlow control
whileLoop while a condition is trueFlow control
doLoop that runs at least once (do … while)Flow control
breakLeaves a loop or switchFlow control
continueSkips to the next loop iterationFlow control
returnLeaves a method, optionally with a valueFlow control
tryStarts a block that may throw an exceptionException handling
catchHandles an exceptionException handling
finallyAlways runs after try/catchException handling
throwThrows an exceptionException handling
throwsDeclares exceptions a method may throwException handling
assertChecks a condition while testing (enabled with -ea)Exception handling
staticBelongs to the class, not to objectsModifiers
finalCannot be changed, overridden or extendedModifiers
synchronizedOnly one thread at a timeModifiers
volatileEvery thread sees the latest valueModifiers
transientSkipped when an object is serializedModifiers
nativeImplemented in another language (C/C++)Modifiers
strictfpStrict floating-point rules (no effect since Java 17)Modifiers
gotoReserved; using it is a compile errorReserved but not used
constReserved; use final insteadReserved but not used
_Underscore — a keyword since Java 9; unnamed variables in newer JavaReserved but not used

Contextual Keywords: var, record, yield and More

These words are only keywords in a particular place, so older code that used them as names still compiles. The compiler confirms all 16 can be used as variable names — but five of them (var, yield, record, sealed, permits) cannot be used as class or type names.

Contextual keywordWhere it acts as a keywordUsable as a class name?
varLocal variable type inference: var list = new ArrayList<String>(); (Java 10+)No
recordDeclares a record class: record User(String name) {} (Java 16+)No
yieldReturns a value from a switch expression (Java 14+)No
sealed, permits, non-sealedSealed classes that limit which classes may extend them (Java 17+)sealed/permits: No
whenGuards in pattern-matching switch: case String s when s.isEmpty() (Java 21)Yes
module, requires, exports, opens, open, to, uses, provides, with, transitiveOnly inside module-info.java (Java 9 modules)Yes

Java Keywords Example Program

This small program uses more than 25 keywords — each one is marked in a comment:

public class KeywordsDemo {

    enum Level { BEGINNER, ADVANCED }              // enum

    interface Greeter { String greet(String name); } // interface

    static final int MAX_TESTS = 3;                 // static, final, int

    public static void main(String[] args) {        // public, static, void
        int passed = 0;
        for (int i = 1; i <= MAX_TESTS; i++) {      // for
            boolean ok = (i % 2 != 0);              // boolean
            if (ok) {                               // if / else
                passed++;
            } else {
                continue;                           // continue
            }
        }
        Level level = (passed >= 2) ? Level.ADVANCED : Level.BEGINNER;
        Greeter g = name -> "Hello, " + name;
        try {                                       // try / catch / finally
            System.out.println(g.greet("tester"));
            System.out.println("Passed " + passed + " of " + MAX_TESTS + " -> " + level);
            if (passed < 0) throw new IllegalStateException("impossible"); // throw, new
        } catch (IllegalStateException e) {
            System.out.println("Error: " + e.getMessage());
        } finally {
            System.out.println("Done");
        }
    }
}

Output

Hello, tester
Passed 2 of 3 -> ADVANCED
Done

How it works: enum and interface declare types; static final makes a constant; the for loop uses if/else and continue; and try/catch/finally handles errors — finally runs every time, which is why "Done" is always printed.

Common Mistakes

  1. Using a keyword as a variable name. The error message doesn't say "keyword", which confuses beginners:
    int class = 5;
    Bad.java:3: error: not a statement
            int class = 5;
            ^
    Bad.java:3: error: ';' expected
    Fix: choose another name such as className or clazz.
  2. Thinking Java keywords are case-insensitive. Keywords are all lowercase, so Class, Main or String are not keywords — int Class = 5; compiles (though it's bad style).
  3. Calling true, false or null keywords. They're literals. You still can't use them as names, but in interviews say "literals", not keywords.
  4. Thinking main or String is a keyword. main is just a method name the JVM looks for, and String is a class in java.lang.
  5. Trying to use goto or const. Both are reserved but unused — the compiler rejects them. Use labelled break/continue instead of goto, and final instead of const.

Practice Exercises

  1. Without looking, write down the 8 primitive-type keywords. Check them against the table.
  2. Write a class that uses static, final, switch, case, default and break, and predict its output before running it.
  3. Interview question: explain the difference between final, finally and finalize() (hint: only two of them are keywords).

Key Takeaways

  • Java 21 has 51 reserved keywords (including _) and 16 contextual keywords.
  • true, false and null are literals, not keywords — but they are still reserved.
  • var, yield, record, sealed and permits can be variable names but not class names.

📚 Official documentation: Java Language Specification: Keywords (Java 21) · dev.java: Learn Java

Frequently Asked Questions

How many keywords are there in Java?

Java has 51 reserved keywords (Java 9 and later, including the underscore _) plus 16 contextual keywords such as var, record and yield. Java 8 had 50 reserved keywords.

Are true, false and null keywords in Java?

No. They are literals. You still cannot use them as names for variables, methods or classes.

Is main a keyword in Java?

No. main is an ordinary method name that the JVM looks for to start a program. String is a class, not a keyword, either.

Is var a keyword in Java?

var is a contextual keyword (a reserved type name) added in Java 10. You can still name a variable var, but you cannot name a class var.

Why are goto and const reserved in Java?

They were reserved so they could never be used by mistake. Neither has any meaning in Java, and the compiler rejects both.