Topic 16 of 119 2. Fundamentals of Java Programming Interactive Tutorial

Reserved Words in Java: Keyword Categories and Usage

15 mins read Last updated: 22 Aug 2026 17,768 views

Direct Answer & Core Concept

Reserved words, or keywords, are words the Java compiler claims for its own use, so you can never use them as class, variable or method names. Java has 50 traditional keywords, and Java 9 added a 51st in the form of a lone underscore. They fall into clear groups: primitive data types (int, boolean, double), control flow (if, else, switch, for, while), object-oriented words (class, interface, new, extends, implements, this, super, instanceof), access and other modifiers (public, private, protected, static, final, abstract), package handling (package, import) and exception handling (try, catch, finally, throw, throws). Two more, const and goto, are reserved but unusable, while true, false and null are reserved literals rather than keywords.

Detailed Explanation & Mechanics

1. What Are Reserved Words in Java?

A reserved word, also called a keyword, is a word the Java compiler has claimed for its own use. It already means something to the language, so you are not allowed to use it as a name for your own classes, variables or methods.

Write this and the compiler stops you immediately:

Main.java
Run Online
int class = 50;
// ERROR: class is a keyword and cannot be used as a variable name

The reason Java is strict about this is safety. If you were allowed to name a variable class, then every existing program would become ambiguous, and old code could suddenly stop compiling. Reserved words guarantee that a piece of code always means the same thing.

Architecture Diagram
HOW THE COMPILER TREACHES A NAME

    totalPrice   ──►  looks in the keyword list first
                        |
                        +── not a keyword ──► treat it as YOUR identifier
                        |
                        +── is a keyword  ──► syntax error, always

    Keywords are reserved for the whole language, everywhere, all the time.
  • Java has 50 traditional keywords, and Java 9 added a 51st reserved word which is a lone underscore.
  • true, false and null are reserved literals rather than keywords, but they behave exactly the same way for naming.
  • Modern releases added contextual keywords such as var, record, sealed, permits and yield, which only act as keywords in specific positions.

2. Keyword vs Literal vs Identifier: The Three-Way Confusion

Beginners often merge these three ideas. One line of code contains all three, which makes it a useful starting point.

Architecture Diagram
ONE LINE, THREE DIFFERENT THINGS

    int   totalPrice   =   500;
     |        |            |
     |        |            +--► LITERAL   a fixed value typed directly
     |        +---------------► IDENTIFIER a name YOU invented
     +------------------------► KEYWORD    a word owned by Java

  KEYWORD    int, class, return, if, while, new, this
  LITERALS   500, 3.14, 'A', true, false, null
  IDENTIFIER totalPrice, customerAge, calculateTotal
  • Keywords cannot be used anywhere as names, not even for a package.
  • Literals cannot be used as names either, so true and null are permanently off limits.
  • Identifiers are your own words. Anything that is neither a keyword nor a literal belongs here.

3. The Complete Java Reserved Word List, Grouped by Category

Reserved words are much easier to learn once you group them by what they do. Here is the whole picture in one place.

CategoryKeywordsTypical Use
Primitive data typesboolean byte short int long char float double voidDeclaring variables and method return types
Control flowif else switch case default while do for break continue returnDecisions, loops and jumping
Object orientedclass interface enum extends implements new this super instanceofBuilding types and relating them
Access modifierspublic protected privateControlling who can reach a member
Other modifiersstatic final abstract synchronized volatile transient native strictfpChanging behaviour and memory semantics
Packagespackage importOrganising and importing code
Exception handlingtry catch finally throw throwsDealing with errors at runtime
AssertionsassertDeveloper-only sanity checks
Reserved, never usedconst gotoReserved for possible future use

You do not need to memorise this table by heart. The next sections walk through each group with a working example, so the words stick because you have seen them do something.

4. Primitive Data Type Keywords

These eight keywords are the simplest and the first you will meet. Each one maps to exactly one primitive type in the language.

  • boolean stores true or false.
  • byte, short, int and long store whole numbers of increasing size.
  • char stores a single 16-bit character.
  • float and double store decimal numbers, with double being the default for decimals.
  • void is the odd one out. It is not a data type you declare variables with, but it is the return type of a method that hands back nothing.
Main.java
Run Online
public class DataTypes {
    public static void main(String[] args) {
        boolean isEnrolled = true;
        byte smallCount = 12;
        short mediumCount = 3200;
        int count = 250000;
        long phoneNumber = 9876543210L;
        char grade = 'A';
        float ratio = 0.75f;
        double price = 1499.99;
        System.out.println(isEnrolled + " " + smallCount + " " + mediumCount);
        System.out.println(count + " " + phoneNumber + " " + grade);
        System.out.println(ratio + " " + price);
    }
}

Notice that long values need an L suffix and float values need an f suffix. Without them Java treats the literal as a different type, which is a very common beginner error.

5. Control Flow Keywords

Control flow keywords decide which code runs and in what order. They are the vocabulary of every decision your program makes.

  • if and else choose between two branches.
  • while and do while repeat code, with do while running the body at least once.
  • for repeats a known number of times and is the loop you will use most.
  • break leaves a loop or switch immediately.
  • continue skips to the next iteration of a loop.
  • return leaves the current method and hands back an optional value.
  • switch, case and default give you a multi-way choice that reads better than a long chain of else if blocks.
Main.java
Run Online
public class ControlFlowDemo {
    public static void main(String[] args) {
        int score = 82;
        if (score < 40) {
            System.out.println("Fail");
        } else if (score < 70) {
            System.out.println("Average");
        } else {
            System.out.println("Pass");
        } for (int i = 1;
        i

6. Object-Oriented Keywords

These are the words that make Java an object-oriented language in the first place.

  • class declares a new reference type.
  • interface declares a contract of methods.
  • enum declares a fixed set of named constants.
  • new creates an object in memory.
  • extends creates an inheritance link between classes.
  • implements connects a class to the interfaces it promises to honour.
  • this points at the current object.
  • super points at the parent class.
  • instanceof checks the runtime type of a reference.
Main.java
Run Online
class Vehicle {
    void start() {
        System.out.println("Vehicle started");
    }
}class Car extends Vehicle implements Comparable {
    private final String model;
    Car(String model) {
        this.model = model;
    } // this refers to this object
    @Override public int compareTo(Car other) {
        return this.model.compareTo(other.model);
    } void showModel() {
        System.out.println("Model: " + model + ", parent is " + super.getClass().getSimpleName() + " from " + super.toString().split("@")[0]);
    }
}public class OopDemo {
    public static void main(String[] args) {
        Car car = new Car("Swift");
        // new creates the object
        car.start();
        // inherited from Vehicle
        Object reference = car;
        if (reference instanceof Car c) {
            // instanceof narrows the type
            System.out.println("Confirmed: " + c.model);
        }
    }
}

7. Access Modifiers: public, protected and private

These three keywords decide who is allowed to touch a class or one of its members.

ModifierSame ClassSame PackageSubclass ElsewhereAnywhere Else
publicYesYesYesYes
protectedYesYesYesNo
privateYesNoNoNo
no modifier (default)YesYesNoNo
  • Use private by default and open access only when there is a real reason.
  • Use protected for members a subclass genuinely needs to reuse.
  • Use public for the small surface of API that other code is meant to call.

8. Other Modifier Keywords

Beyond visibility, Java has modifiers that change how a member behaves.

  • static makes a member belong to the class rather than to each object.
  • final stops a variable being reassigned, a method being overridden, or a class being extended.
  • abstract demands that a class or method be completed by a subclass.
  • synchronized protects shared resources from concurrent access.
  • volatile guarantees visibility of a variable across threads.
  • transient stops a field being serialised.
  • native marks a method implemented outside Java, in another language.
  • strictfp is now a no-op because Java 17 always uses strict floating point.
Main.java
Run Online
public class Shape {
    static final double PI = 3.14159;
    // constant shared by all shapes
    private String name;
    // every object has its own copy
    private transient int cache;
    // never written to a file
    public Shape(String name) {
        this.name = name;
    } public String getName() {
        return name;
    } public double area() {
        throw new UnsupportedOperationException("Subclass must override");
    }
}abstract class Circle extends Shape {
    private final double radius;
    Circle(double radius) {
        super("Circle");
        this.radius = radius;
    } @Override public double area() {
        return PI * radius * radius;
    }
}

9. Package Keywords: package and import

package and import control how classes are organised and found.

  • package places a class inside a named folder structure.
  • import lets you refer to a class without typing its full name.
  • Naming a package with a reserved word fails, because each part must be a legal identifier, so com.int.banking is illegal while com.integer.banking is fine.
Main.java
Run Online
package com.mycompany.billing.payment;
import java.util.List;
import java.time.LocalDate;
public class PaymentService {
    public void settle(List invoiceIds, LocalDate on) {
        System.out.println("Settled " + invoiceIds.size() + " invoices on " + on);
    }
}

10. Exception Handling Keywords

Java uses five keywords to deal with runtime errors, and this is one area where the language design is unusually tidy.

  • try marks the block of code that might fail.
  • catch states what happens when a particular exception is thrown.
  • finally always runs, whether or not an exception occurred, which makes it ideal for releasing resources.
  • throw raises an exception yourself.
  • throws declares in the method signature that an exception may escape.
Main.java
Run Online
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileDemo {
    // throws says: this method may hand an IOException back to the caller
    static int countLines(String path) throws IOException {
        int lines = 0;
        try(BufferedReader reader = new BufferedReader(new FileReader(path))) {
            while (reader.readLine() != null) {
                lines++;
            }
        } finally {
            System.out.println("Finished reading " + path);
        } return lines;
    } public static void main(String[] args) {
        try {
            System.out.println(countLines("data.txt"));
        } catch (IOException e) {
            System.out.println("Could not read the file: " + e.getMessage());
        }
    }
}

The try-with-resources form shown above is worth learning early, because it closes the file for you and needs no finally block at all.

11. Reserved but Unusable: const and goto

Two keywords are reserved by the Java specification but were never given any meaning. Using them is a compile error rather than a feature.

  • const was reserved because other languages needed a way to declare compile-time constants. Java solved that with final instead.
  • goto was reserved because structured loops made it unnecessary, and unlimited jumps make code hard to follow.
Main.java
Run Online
// int const = 10;   ERROR: const is reserved and has no meaning in Java
// goto skip;        ERROR: goto is reserved and has no meaning in Java
// int goto = 1;     ERROR: same reason
int constant = 10;
// use a descriptive name, or declare it final
int constant = 10;
// and never reassign it
  • Never name your own variables const or goto out of habit from C or C++.
  • If you need a constant, declare it static final, which is exactly what the constants keyword list in the earlier table describes.

12. Contextual Keywords in Modern Java

Newer Java versions have added words that only behave like keywords in specific positions. Elsewhere they are ordinary identifiers, which is why you can still write a variable called record.

Architecture Diagram
CONTEXTUAL KEYWORDS ARRIVED OVER TIME

  Java 9     │  _            a lone underscore became reserved
  Java 10    │  var          local type inference
  Java 14    │  yield        value from a switch expression
  Java 16    │  record       immutable data carrier class
  Java 17    │  sealed       restricts who may extend a class
             │  permits      lists the allowed subclasses
             │  non-sealed   opts back out of a sealed hierarchy
             └────────────────────────────────────────────
  • var asks the compiler to infer a local variable type from its initialiser, and you can still use var as a variable or method name.
  • record creates a compact immutable data class, and you can still write a variable called record.
  • sealed and permits create controlled inheritance hierarchies, useful for pattern matching.
  • yield is used inside a switch expression to return a value, and it is not the same as return.

13. Errors Caused by Keywords and How to Fix Them

Almost everyone meets these errors once. The fix is nearly always renaming something.

What You WroteCompiler SaysHow To Fix It
int class = 50;invalid character, illegal start of expressionRename to clazz or courseCount
boolean null = false;null is a reserved literalUse isNull instead
public void final() { }modifier not allowed hereRename the method
package com.new.banking;new is a keywordUse com.newbank.banking
int const = 1;const is reservedDeclare it static final
int _ = 5;as of Java 9 this is an errorName the variable properly
enum Status { CLASS, NEW }enum constants are identifiersUse CLASSIC and FRESH
  • Keywords are matched as whole words only, so ClassFactory and recordCount are perfectly legal.
  • That is exactly why good style adds a meaningful suffix such as ClassLoader or RecordEntry instead of an ugly one.
  • Package names have the same rule, since each dot-separated part must be a legal identifier.

14. Java Reserved Words Cheat Sheet

Keep this table close while you write your first programs. It is the whole keyword story on one screen.

QuestionAnswer
How many reserved words?50 keywords, plus a lone underscore since Java 9
Are true, false and null keywords?They are reserved literals, but they cannot be names either
Can I use a keyword inside a longer name?Yes, because keywords match whole words only
Are const and goto usable?No, they are reserved but have no meaning in Java
Is var a keyword?No, it is a reserved type name and only special in a type position
Can a package contain a keyword?No, every part must be a legal identifier
Are enum constants keywords?No, they are identifiers and must follow naming rules
What is the safest naming habit?Keep your own names far away from the keyword list

Now that you can recognise every reserved word on sight, the next topic, Java variables, becomes much easier because you already know which names are available to you.

Runnable Code Example: Reserved Words in Java

Java 17+
Main.java
Run Online
public class ReservedWordsDemo {
    // Modifier keywords
    static final int MAX_ATTEMPTS = 3;
    // OOP keyword: extends an existing class
    static class BaseAccount {
        double balance = 0;
    } static class SavingsAccount extends BaseAccount {
        double interestRate = 0.05;
    } public static void main(String[] args) {
        // Primitive data type keywords
        int attempts = 0;
        double balance = 1500.50;
        boolean isActive = true;
        char grade = 'A';
        long phoneNumber = 9876543210L;
        // Object-oriented keyword: new creates an object
        SavingsAccount account = new SavingsAccount();
        account.balance = balance;
        // instanceof is a reserved operator keyword
        if (account instanceof BaseAccount) {
            System.out.println("Savings account is also a BaseAccount");
        } // Control flow keywords: if, else, for, continue
        for (int i = 1;
        i <= MAX_ATTEMPTS;
        i++) {
            if (attempts >= MAX_ATTEMPTS && isActive) {
                System.out.println("Account is locked after " + attempts + " attempts");
                break;
            } attempts++;
        } // switch, case and default
        switch (grade) {
            case 'A': System.out.println("Grade: Excellent");
            break;
            default: System.out.println("Grade: " + grade);
        } // package and import are keywords you rarely see in a single file
        // try, catch, finally, throw, throws handle errors
        try {
            int safeDivisor = 0;
            System.out.println(balance / safeDivisor);
        } catch (ArithmeticException e) {
            System.out.println("Handled: " + e.getMessage());
        } finally {
            System.out.println("Always runs: phone " + phoneNumber);
        } // Class-level keyword: this refers to the current object
        System.out.println("Static context has no this, so we print directly.");
    }
}

Common Java Technical Interview Questions & Answers

Interview Prep
Q1

How many reserved words does Java have?

Java has 50 traditional keywords, and Java 9 added a 51st reserved word which is a lone underscore. In addition, true, false and null are reserved literals that also cannot be used as identifiers, and modern releases added contextual keywords such as var, record, sealed, permits and yield.
Q2

Why can I not name a variable class or int?

Because class and int are reserved by the language and carry a fixed meaning that the compiler relies on. If you were allowed to shadow them, existing programs would stop compiling, so Java rejects such names immediately.
Q3

What is the difference between a keyword and a reserved word?

They mean the same thing in Java. The official specification calls them reserved words or keywords interchangeably, and the term restricted identifier is used for a few words with limited allowed uses.
Q4

Are const and goto keywords in Java?

They are reserved by the specification but were never implemented, so writing them in your code produces a compile error. They were reserved in early designs in case the language ever needed them.
Q5

Is true a keyword in Java?

Technically true is a boolean literal rather than a keyword, along with false and null. The practical difference is nil, because all three are reserved and cannot be used as identifiers.
Q6

What is a contextual keyword?

A contextual keyword is a word that is treated specially only in a particular position, and behaves like an ordinary identifier elsewhere. var, record, sealed, permits and yield are contextual, so for example you may still use record as a variable name.
Q7

Is var a keyword in Java?

var was added in Java 10 as a reserved type name, not a keyword. The compiler infers the type from the initialiser, and you can still write a variable, method or package called var, although it is poor practice.
Q8

Can a keyword be used as part of a longer identifier?

Yes. Keywords are banned only as complete identifiers. A class named ClassFactory or a variable named instanceofCount is perfectly legal, because the compiler matches whole words.
Q9

Can a package name contain a keyword?

No. Each dot-separated part of a package name must itself be a legal identifier, so com.int.banking is illegal while com.integer.banking is fine.
Q10

Can an enum constant be a keyword?

No. Enum constants are identifiers, so they must follow the same rules and cannot be keywords such as NEW or CLASS. You may however write an enum constant named new_value.
Q11

What is strictfp and why is it rarely used?

strictfp forced strict, reproducible floating point maths on old hardware where intermediate results could be evaluated in extended precision. Since Java 17 the default behaviour is always strict, so the keyword remains only for compatibility and triggers a deprecation warning.

Key Takeaways, Best Practices & Clean Code Rules

Java Best Practice & Production Rules

Treat keywords as off limits, not as suggestions, and never try to build a clever naming scheme that plays with words like record, sealed or var. Keep your identifiers in a different mental space: use getRecordCount rather than recordCount, and call a boolean isSealed instead of sealed. If you must work around a keyword, append a meaningful word such as ClassLoader or RecordEntry rather than an ugly suffix like clazz or k1ass. Do not name anything const, goto or _ out of habit carried over from C or C++. When you read unfamiliar code, recognising a keyword by sight tells you immediately what kind of statement you are looking at, which is a large part of why keywords are so powerful for readability.
We value your privacy & transparency

OperateTools uses cookies and local storage to ensure basic tool functionality, preserve preferences, and analyze aggregated traffic. We never sell your personal data or index your document files. Learn more in our Privacy Policy.