Java Keywords Reference for Java 17

Java keywords have language-defined roles and cannot be used like arbitrary names.

Lesson 120 of 127Intermediate13 min read

Java keywords have language-defined roles and cannot be used like arbitrary names. A reference should distinguish reserved keywords, contextual keywords, and literals instead of presenting one misleading mixed list. This page follows Java 17: it has fifty-one reserved keywords and sixteen contextual keywords. The tables group every member by purpose, then the examples show how those words shape real control flow and object declarations. String, System, println, and main are familiar names, but they are not reserved Java keywords.

All Java 17 reserved keywords by purpose

PurposeKeywords
Primitive typesboolean, byte, short, int, long, char, float, double
Declarations and type relationshipsclass, interface, enum, package, import, extends, implements, new, instanceof
Access controlpublic, protected, private
Modifiers and coordinationabstract, final, static, synchronized, native, strictfp, transient, volatile
Decisions and repetitionif, else, switch, case, default, for, while, do, break, continue
Method and assertion flowreturn, void, assert
Exceptionstry, catch, finally, throw, throws
Current and parent objectsthis, super
Reserved without ordinary useconst, goto, _

These categories are a reading aid, not separate lexical classes. synchronized can introduce a method modifier or a synchronized statement. default also appears in interface method declarations. A word's exact meaning follows the grammar surrounding it.

Contextual keywords depend on their location

PurposeContextual keywords
Module declarations and directivesmodule, open, requires, transitive, exports, opens, to, uses, provides, with
Data and inheritance declarationsrecord, sealed, non-sealed, permits
Local type inferencevar
Producing a switch-expression resultyield

A contextual word is interpreted according to its grammatical position. That does not mean it is permitted as every possible identifier elsewhere: Java restricts certain type and method names to avoid ambiguity. For example, var denotes inferred local typing in a suitable declaration, but you cannot declare a class named var. Match the language release before using words added by later Java versions.

Literals and API names are different

true and false are boolean literals, while null is the null literal. They are not keywords in the specification's classification, but they still cannot be ordinary identifiers. String names a platform class, System names another class, and println names a method. The launcher recognizes the conventional main method signature, yet main itself remains an identifier. Distinguishing these categories helps you read unfamiliar APIs without assuming every commonly seen word belongs to Java's grammar.

Read modifiers through their actual guarantee

private limits access, final prevents particular reassignment or extension according to its declaration context, and static associates a member with the class rather than an instance. volatile supports specific visibility guarantees; it does not make arbitrary compound updates atomic. transient affects the default serialization of fields, and native declares a method implemented outside ordinary Java code. strictfp remains reserved but is unnecessary for new Java 17 code because floating-point evaluation is consistently strict.

Control-flow words make different decisions

break exits a targeted enclosing loop or switch, while continue proceeds with the next loop iteration. return exits a method, optionally carrying its result. throw raises an exception object at runtime; throws declares possible exceptions in a method signature. finally defines cleanup-related flow, while final is a different word with different roles. assert expresses an assertion that can be disabled, so do not use it as the only validation of ordinary user input.

Use the specification when version details matter

The Java 17 Language Specification keyword section is the authoritative classification for this baseline. An underscore alone is reserved in Java 17, while longer identifiers can contain underscores. const and goto remain reserved without implementing ordinary Java statements. Learn useful categories and examples instead of trying to use every keyword in one program. Later releases can introduce or finalize features, so document the project's target release alongside its build configuration.

Practice tasks and checks

Read KeywordFlow and classify each highlighted-looking word yourself: grammar keyword, identifier, literal, or operator. Then change the skip rule from nonpositive values to values below five and predict the total. In KeywordException, remove the optional unchecked throws clause and verify that runtime behavior is unchanged; keep the actual throw and catch. In KeywordContext, replace var with the explicit Meter type and compare the result. Finally, write one declaration using a valid longer underscore-containing identifier and explain why that differs from the reserved single underscore. Use the reference tables to verify categories, but do not try to memorize names without connecting them to statements that actually execute.

Java Summary

  • Java 17 distinguishes 51 reserved and 16 contextual keywords.
  • true, false, and null are literals rather than keywords.
  • Read a keyword through its declaration or statement context.
  • Continue with modern language features when these examples are clear.

Java Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Read loop and method keywords in context

Save this program as KeywordFlow.java. Compile it with javac KeywordFlow.java and run it with java KeywordFlow.

Expected output:

class declares the type and static makes positiveTotal callable without constructing an instance. int declares the result and local variable types. for visits each element, if checks whether it should be skipped, and continue bypasses accumulation for minus three and zero. return sends eleven to the caller. System and println participate as API names rather than grammar keywords, which is why their meanings depend on available class and method declarations.

Java
public class KeywordFlow {
    static int positiveTotal(int[] values) {
        int total = 0;
        for (int value : values) {
            if (value <= 0) continue;
            total += value;
        }
        return total;
    }
    public static void main(String[] args) {
        System.out.println(positiveTotal(new int[]{4, -3, 0, 7}));
    }
}
Output
11
Example 2

Separate throw from throws and catch

Save this program as KeywordException.java. Compile it with javac KeywordException.java and run it with java KeywordException.

Expected output:

The throws clause records a possible exception type; because this exception is unchecked, that clause is not mandatory but still documents intent. The throw statement creates the actual failure for zero. try encloses the operation and catch handles the matching exception by printing its message. new constructs the exception object. The example keeps these similarly spelled language roles distinct rather than treating every occurrence as error-handling decoration.

Java
public class KeywordException {
    static int requirePositive(int value) throws IllegalArgumentException {
        if (value <= 0) throw new IllegalArgumentException("Positive required");
        return value;
    }
    public static void main(String[] args) {
        try {
            requirePositive(0);
        } catch (IllegalArgumentException error) {
            System.out.println(error.getMessage());
        }
    }
}
Output
Positive required
Example 3

Use contextual declaration and result words

Save this program as KeywordContext.java. Compile it with javac KeywordContext.java and run it with java KeywordContext.

Expected output:

record introduces the data carrier and var infers the local variable's Meter type from its initializer. switch is a reserved keyword producing an expression result here. The default block computes an intermediate value and yield supplies five as that arm's result. yield does not return from main; execution continues to the print statement. All these constructs are supported under the lesson's Java 17 target.

Java
public class KeywordContext {
    record Meter(int units) {}
    public static void main(String[] args) {
        var meter = new Meter(3);
        int band = switch (meter.units()) {
            case 0 -> 0;
            default -> {
                int adjusted = meter.units() + 2;
                yield adjusted;
            }
        };
        System.out.println(band);
    }
}
Output
5

Java FAQ

Is main a Java keyword?

No. It is an identifier used by the conventional application entry point. Its recognized method signature matters to the launcher, but the word is not part of the reserved keyword list.

Can I use an underscore as a variable name?

Not as the single-character identifier _ in Java 17. Longer valid identifiers can contain underscores. Always check the project's language release before applying rules from examples using newer features.

Are goto and const used in Java?

No. Both are reserved so they can't be used as names, but neither does anything in the language. Java uses final for constants and labelled break and continue where other languages might use goto.

Is var a keyword in Java?

Not a full keyword. Since Java 10, var is a reserved type name: it has special meaning where a local variable's type would appear, so it can't name a class, but int var = 5; still compiles. record, yield, sealed and permits are similar contextual keywords.

Can I use a keyword with different capital letters as a name?

Technically yes, because Java is case-sensitive: Class, Int and New aren't keywords, so int Class = 5; compiles. It's very confusing to read, though, and Class clashes with the java.lang.Class type, so choose a descriptive name instead.

Java Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Multiple choiceeasy

Which item is a boolean literal rather than a keyword?

Multiple choicemedium

What does yield do in KeywordContext?

Java Quiz

2 questions to check what you learned.

  1. Which pair has different purposes despite similar spelling?

    • final and finally
    • class and class
    • int and int
  2. Are const and goto available as ordinary identifiers?

    • No; they remain reserved
    • Yes, because their statements are unused
    • Only inside main