Skip to content
Java getting started 7 min read

Java Keywords

Java keywords are words that the language has claimed for its own. You cannot use them as variable names, class names, or method names — they are the building blocks of the language itself. Knowing them helps you write valid code and understand error messages like "expected identifier" when you accidentally name something class or return.

What Is a Keyword?

A keyword (also called a reserved word) is a word with a fixed meaning baked into the Java language specification. The compiler treats every keyword as a special token rather than a user-defined identifier.

int class = 5;   // COMPILE ERROR — 'class' is a keyword
int myClass = 5; // Fine — not a keyword

Java currently has 67 reserved keywords (as of Java 21). Two of them — goto and const — are reserved but not used; they exist to prevent confusion for developers migrating from C/C++. Three special literals (true, false, null) behave like keywords and also cannot be used as identifiers.

Note: Keywords are always lowercase. class, int, and while are keywords; Class, Int, and While are not (though using them as names would be confusing — follow the naming conventions).

Full Keyword Reference

The table below groups all 67 keywords by their role in the language.

Primitive Data Types

These eight keywords declare the built-in primitive types. See Data Types for sizes and ranges.

KeywordWhat it represents
byte8-bit signed integer
short16-bit signed integer
int32-bit signed integer
long64-bit signed integer
float32-bit floating-point
double64-bit floating-point
char16-bit Unicode character
booleantrue or false value
int age = 30;
double price = 9.99;
boolean active = true;
char grade = 'A';

Class, Interface & Object Structure

These keywords define the shape and relationships of your types.

KeywordPurpose
classDeclare a class
interfaceDeclare an interface
enumDeclare an enumeration
recordDeclare a record (Java 16+)
extendsInherit from a superclass
implementsImplement one or more interfaces
abstractMark a class or method as abstract
newCreate an object instance
thisReference the current object
superReference the parent class
instanceofTest an object’s type
voidDeclare a method with no return value
public class Animal {
    String name;
}

public class Dog extends Animal implements Runnable {
    @Override
    public void run() {
        System.out.println(name + " runs!");
    }
}

See Classes & Objects, Inheritance, and Interfaces for deep dives on these.

Access & Scope Modifiers

KeywordMeaning
publicAccessible from anywhere
privateAccessible only within the declaring class
protectedAccessible within the package and subclasses
staticBelongs to the class, not to any instance
finalCannot be extended / overridden / reassigned
abstractMust be implemented by a subclass
synchronizedOne thread at a time (used in concurrency)
volatileAlways read from main memory (used in concurrency)
transientExclude field from serialization
nativeMethod implemented in native code (C/C++)
strictfpEnforce strict floating-point precision (deprecated in Java 17)
public class BankAccount {
    private double balance;       // private: hidden from outside
    public static final double MIN_BALANCE = 0.0; // public + static + final

    public synchronized void deposit(double amount) { // synchronized: thread-safe
        balance += amount;
    }
}

The static keyword, final keyword, and access modifiers each have their own full pages.

Control Flow

These keywords direct the execution path through your program.

KeywordPurpose
ifConditional branch
elseAlternative branch
switchMulti-branch selector
caseA branch within switch
defaultFallback branch in switch (also used in interfaces)
forCounted loop
whileCondition-tested loop
doBody-first loop (do-while)
breakExit a loop or switch
continueSkip to the next loop iteration
returnExit a method and optionally return a value
public class ControlDemo {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            if (i == 3) continue;  // skip 3
            if (i == 5) break;     // stop at 5
            System.out.println(i);
        }
    }
}

Output:

1
2
4

Explore these in detail: if-else, switch, for loop, while loop, break, continue.

Exception Handling

KeywordPurpose
tryWrap code that might throw an exception
catchHandle a thrown exception
finallyAlways-runs block after try/catch
throwManually throw an exception
throwsDeclare checked exceptions a method may throw
public class SafeDivide {
    public static int divide(int a, int b) throws ArithmeticException {
        return a / b;
    }

    public static void main(String[] args) {
        try {
            System.out.println(divide(10, 0));
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero: " + e.getMessage());
        } finally {
            System.out.println("Done.");
        }
    }
}

Output:

Cannot divide by zero: / by zero
Done.

See Exception Handling for the full picture.

Package & Import

KeywordPurpose
packageDeclare the package this file belongs to
importBring a class or package into scope
package com.devcraftly.demo;

import java.util.ArrayList;
import java.util.List;

public class Example {
    List<String> items = new ArrayList<>();
}

Learn more in Packages.

Type-Checking & Casting

Object obj = "Hello";

if (obj instanceof String s) {          // pattern matching (Java 16+)
    System.out.println(s.toUpperCase()); // HELLO
}

The instanceof keyword, including its modern pattern-matching form, is covered on the instanceof Operator page.

Module System (Java 9+)

Java 9 introduced the module system with a handful of context-sensitive keywords — they are only reserved inside module-info.java files and can still be used as identifiers elsewhere:

module, requires, exports, opens, uses, provides, with, to, transitive, open

// module-info.java
module com.devcraftly.app {
    requires java.base;
    exports com.devcraftly.api;
}

See Java 9 Modules for details.

Unused / Reserved-Only Keywords

KeywordStatus
gotoReserved but not used — left over from C
constReserved but not used — use final instead

Attempting to use either causes a compile error, even though the compiler itself never does anything with them.

Special Literals

Three tokens behave exactly like keywords — they are case-sensitive and cannot be identifiers:

LiteralMeaning
trueBoolean true value
falseBoolean false value
nullAbsence of an object reference
boolean isReady = true;
String name = null;   // no object assigned yet

System.out.println(isReady);  // true
System.out.println(name);     // null

Warning: True, False, and Null (capital first letter) are NOT keywords — they are valid (though terrible) variable names. Stick to lowercase as the spec requires.

Quick Summary: All 67 Keywords at a Glance

abstract    assert      boolean     break       byte
case        catch       char        class       const*
continue    default     do          double      else
enum        extends     final       finally     float
for         goto*       if          implements  import
instanceof  int         interface   long        native
new         package     private     protected   public
record      return      short       static      strictfp
super       switch      synchronized this        throw
throws      transient   try         var**        void
volatile    while

* = reserved but not used
** = var is a reserved type name since Java 10, not a traditional keyword — it can still be used as a method or package name (though you shouldn’t)

Under the Hood

When the Java compiler (javac) lexes your source file, it reads the character stream and produces tokens. Keywords are identified during this tokenization phase — before parsing even begins. The lexer compares each identifier-shaped token against a fixed lookup table; if it matches, the token is tagged as a keyword type rather than an identifier type.

This means the compiler catches a misused keyword immediately and precisely: the error points to the exact column where you wrote class as a variable name, before any semantic analysis occurs.

Why can’t you use keywords as identifiers?
The grammar rules for Java would become ambiguous. For example, if if were also a valid variable name, the parser could not determine whether if (x) starts a conditional statement or an expression involving a variable called if. Reserving these tokens removes the ambiguity entirely.

Context-sensitive keywords (like record, sealed, permits, yield) work differently — they were introduced later and made context-sensitive to preserve backward compatibility with existing code that may already use those names as identifiers.

Tip: If you ever get a compiler error about an unexpected token and you are not sure why, check whether you accidentally used a keyword as an identifier. Modern IDEs highlight reserved words in a distinct color to prevent this.

  • Variables — learn the rules for naming identifiers (which must avoid all keywords)
  • Data Types — the eight primitive-type keywords explained in depth
  • Control Statementsif, switch, for, while, break, continue in action
  • Access Modifierspublic, private, protected, and package-private explained
  • static Keyword — one of the most powerful and commonly misunderstood keywords
  • final Keyword — use final for constants, immutable variables, and sealed hierarchies
Last updated June 13, 2026
Was this helpful?