00:00

Keywords in Java – Complete List with Examples

Keywords are words with a special meaning in the Java language, such as class, if, return and static. The compiler reserves them, so you cannot use them as names for variables, methods or classes.

This tutorial lists every Java keyword grouped by purpose, explains the newer contextual keywords such as var, record and yield, and shows what happens when you misuse a keyword.

1. What Are Keywords?

Think of keywords as the grammar words of Java. Just as "if", "while" and "return" have fixed meanings in instructions, Java's keywords tell the compiler how to read your code: class starts a class, int names a type, for starts a loop.

  • All keywords are written in lowercase.
  • Reserved keywords can never be used as identifiers.
  • true, false and null look like keywords but are literals; they are also reserved.
  • Contextual keywords are special only in certain places and can otherwise be used as names.

2. Keywords in a Real Program

A small program already uses many keywords. The comments mark them:

KeywordsInAction.java
import java.util.List;

public class KeywordsInAction {                       // public, class
    private static final int LIMIT = 3;               // private, static, final, int

    interface Shape { double area(); }                // interface, double
    record Square(double side) implements Shape {     // record (contextual), implements
        public double area() { return side * side; } // return
    }

    public static void main(String[] args) {          // void
        List<Shape> shapes = List.of(new Square(2), new Square(3), new Square(5));   // new
        int count = 0;
        for (Shape s : shapes) {                      // for
            if (count >= LIMIT) break;                // if, break
            if (s instanceof Square sq && sq.side() > 2) {   // instanceof
                System.out.println("Big square, area " + sq.area());
            } else {                                  // else
                System.out.println("Small square, area " + s.area());
            }
            count++;
        }
        try {                                         // try
            throw new IllegalStateException("demo");  // throw
        } catch (IllegalStateException e) {           // catch
            System.out.println("Caught: " + e.getMessage());
        } finally {                                   // finally
            System.out.println("finally always runs");
        }
    }
}
Output
Small square, area 4.0
Big square, area 9.0
Big square, area 25.0
Caught: demo
finally always runs

3. Reserved Keywords Grouped by Purpose

Java has 51 reserved keywords (including _). Here they are grouped by what they do:

GroupKeywords
Primitive typesboolean, byte, char, short, int, long, float, double, void
Classes, interfaces, packagesclass, interface, enum, extends, implements, package, import
Access modifierspublic, protected, private
Other modifiersstatic, final, abstract, synchronized, volatile, transient, native, strictfp
Conditionsif, else, switch, case, default
Loops and jumpsfor, while, do, break, continue, return
Exceptionstry, catch, finally, throw, throws, assert
Objects and referencesnew, this, super, instanceof
Reserved but unusedgoto, const
Unnamed variable (Java 9+ keyword)_

4. What Each Keyword Means

KeywordMeaning
abstractClass that cannot be instantiated, or method without a body.
assertChecks a condition during testing (enabled with -ea).
breakExits a loop or switch.
case / defaultBranches in a switch; default also marks interface default methods.
catch / finally / tryHandle exceptions; finally always runs.
classDeclares a class.
continueSkips to the next loop iteration.
do / while / forLoops.
enumDeclares a fixed set of constants.
extends / implementsInherit from a class / implement an interface.
finalCannot be changed, overridden or extended.
if / elseConditional branches.
import / packageUse classes from other packages / declare the current package.
instanceofTests an object's type (with pattern matching since Java 16).
interfaceDeclares an interface.
nativeMethod implemented in another language (C/C++).
newCreates an object.
returnEnds a method, optionally returning a value.
staticBelongs to the class rather than to objects.
strictfpStrict floating-point rules (has no effect since Java 17, where all arithmetic is strict).
super / thisRefer to the parent class / the current object.
switchMulti-way branch statement or expression.
synchronizedAllows only one thread at a time in a method or block.
throw / throwsThrow an exception / declare that a method may throw one.
transientField skipped during serialization.
voidMethod returns nothing.
volatileField always read from and written to main memory, visible to all threads.

Detailed tutorials: this, super, final, static, transient, volatile, native and strictfp.

5. Contextual Keywords

Newer Java features added words that are keywords only in specific positions. That way, old programs that used these words as names still compile.

Contextual keywordSinceUsed for
varJava 10Local variable type inference.
yieldJava 14Return a value from a switch expression block.
recordJava 16Declare a record class.
sealed, non-sealed, permitsJava 17Restrict which classes may extend a class or interface.
whenJava 21Guard condition in a pattern case.
module, open, requires, exports, opens, uses, provides, to, with, transitiveJava 9Module declarations in module-info.java.

Because they are contextual, this surprising code is legal:

ContextualKeywords.java
public class ContextualKeywords {
    public static void main(String[] args) {
        // Contextual keywords are only special in certain places,
        // so they can still be used as ordinary names elsewhere:
        int record = 5;
        String yield = "yield as a variable name";
        var var = record * 2;          // 'var' used as a type AND as a name

        System.out.println(record + ", " + var + ", " + yield);

        // ...and as keywords where they have meaning:
        String size = switch (var) {
            case 10 -> "ten";
            default -> {
                yield "other";           // 'yield' returns a value from a switch block
            }
        };
        System.out.println("size = " + size);
    }
}
Output
5, 10, yield as a variable name
size = ten

Legal does not mean recommended: avoid naming variables after contextual keywords in new code.

6. Reserved Literals: true, false and null

true and false are the two boolean values, and null means "no object". They are not technically keywords, but they are reserved, so you cannot use them as names either.

7. goto and const

goto and const are reserved but do nothing. Java's designers kept them out of the language (labeled break/continue replace goto, and final replaces const) while still reserving them, so that C and C++ programmers get a clear error instead of confusing behaviour.

8. Using a Keyword as a Name

Trying to name a variable class or using goto gives compile errors such as:

javac output (excerpt)
Bad.java:2: error: <identifier> expected
    int class = 1;
       ^
Bad.java:3: error: illegal start of expression
    void m() { goto end; }

Choose a different name, such as className or clazz (a common convention).

9. Tips for Remembering Keywords

  • All keywords are lowercase; String, System and Integer are class names, not keywords.
  • main is not a keyword; it is just the name of the entry-point method.
  • IDEs highlight keywords in a different colour, which helps spot mistakes.
  • Learn keywords together with the feature they belong to (exceptions, loops, OOP) rather than as a list.

10. Summary

  • Keywords are reserved words with fixed meanings; they cannot be used as identifiers.
  • Java has 51 reserved keywords, including the unused goto and const and the underscore _.
  • true, false and null are reserved literals.
  • Contextual keywords such as var, record, yield, sealed and when are special only in certain positions.

Related Tutorials

Reference: Java Language Specification §3.9: Keywords