Java Keywords Reference: Every Keyword, Contextual Keyword and Literal
A complete Java keywords list for Java 21+: all 51 reserved keywords, 17 contextual keywords such as var, record, sealed and yield, and the literals true, false and null, with meanings, the version that introduced each and links to the lessons.
kvi5hnuCode Sprout team member12 min readOn this page
This final article is a reference card for every word that has special meaning in the Java language. Bookmark it. When you meet an unfamiliar keyword in someone else's code, or wonder whether you may name a variable record or module, the answer is here. Every entry links back to the lesson in this course that explains it.
Three kinds of special words
The Java Language Specification (JLS §3.9) distinguishes three groups:
- Reserved keywords can never be used as identifiers. That's 51 words, including
constandgoto, which are reserved but unused, and the underscore_, which has been a keyword since Java 9. - Contextual keywords act as keywords only in specific positions and are ordinary identifiers everywhere else. That's 17 words. Older editions of the JLS, and many books, split them into restricted keywords (special only inside a
module-info.java, such asexports,requiresandto) and restricted identifiers (identifiers unless used in certain positions, such asvar,record,sealed,permitsandyield). Since Java 17 the JLS uses the single term contextual keyword. - Literals:
true,falseandnulllook like keywords but are technically literals. You still can't use them as names.
The complete list
| Kind | Count |
|---|---|
| reserved keyword | 51 |
| contextual keyword | 17 |
| literal | 3 |
| Word | Meaning | Kind | Since | Covered in |
|---|---|---|---|---|
abstract | declares an abstract class or method (no body) | reserved | 1.0 | 49 |
assert | checks an internal invariant; enabled with -ea | reserved | 1.4 | 72 |
boolean | the primitive type with values true and false | reserved | 1.0 | 11 |
break | leaves a switch statement or loop, optionally a labeled one | reserved | 1.0 | 24 |
byte | the 8-bit signed integer type | reserved | 1.0 | 10 |
case | a label in a switch statement or expression | reserved | 1.0 | 16, 23 |
catch | the clause of a try statement that handles an exception | reserved | 1.0 | 69 |
char | the type for UTF-16 code units | reserved | 1.0 | 11 |
class | defines a class; X.class is a class literal | reserved | 1.0 | 30, 53 |
const | reserved, not used (use static final) | reserved | 1.0 | — |
continue | skips to the end of the current loop iteration | reserved | 1.0 | 24 |
default | the default label of a switch; a default method in an interface; an annotation element default | reserved | 1.0 | 23, 58, 106 |
do | the top of a do/while loop | reserved | 1.0 | 22 |
double | the 64-bit double-precision floating-point type | reserved | 1.0 | 10 |
else | the alternative branch of an if statement | reserved | 1.0 | 21 |
enum | defines an enumerated type | reserved | 5 | 50 |
exports | exports a package of a module | contextual | 9 | 112 |
extends | names the superclass or superinterfaces; an upper bound of a type variable or wildcard | reserved | 1.0 | 41, 77, 79 |
false | one of the two boolean values | literal | 1.0 | 11 |
final | a constant, a class that can't be extended, or a method that can't be overridden | reserved | 1.0 | 12, 43 |
finally | the part of a try statement that always runs | reserved | 1.0 | 70 |
float | the 32-bit single-precision floating-point type | reserved | 1.0 | 10 |
for | a counted loop or an enhanced for-each loop | reserved | 1.0 | 22, 26 |
goto | reserved, not used | reserved | 1.0 | — |
if | a conditional statement | reserved | 1.0 | 21 |
implements | names the interfaces a class implements | reserved | 1.0 | 57 |
import | imports a type or package (and static members with import static) | reserved | 1.0 | 36 |
instanceof | tests the runtime type of an object, optionally with a pattern | reserved | 1.0 | 43, 52 |
int | the 32-bit signed integer type | reserved | 1.0 | 10 |
interface | defines an interface; @interface defines an annotation type | reserved | 1.0 | 57, 106 |
long | the 64-bit signed integer type | reserved | 1.0 | 10 |
module | declares a module | contextual | 9 | 111 |
native | a method implemented in platform code (JNI or the Foreign Function API) | reserved | 1.0 | — |
new | allocates an object or an array | reserved | 1.0 | 29, 26 |
non-sealed | a subtype of a sealed type that may be extended freely | contextual | 17 | 51 |
null | the null reference | literal | 1.0 | 29 |
open | makes all packages of a module open for deep reflection | contextual | 9 | 113 |
opens | opens a package of a module for deep reflection | contextual | 9 | 113 |
package | declares the package of a compilation unit | reserved | 1.0 | 36 |
permits | lists the permitted direct subtypes of a sealed type | contextual | 17 | 51 |
private | accessible only inside the top-level class that declares it | reserved | 1.0 | 31 |
protected | accessible in the same package and in subclasses | reserved | 1.0 | 43 |
provides | declares that a module provides an implementation of a service | contextual | 9 | 115 |
public | accessible from everywhere (subject to module exports) | reserved | 1.0 | 30 |
record | declares a record class, a transparent carrier of immutable data | contextual | 16 | 35 |
requires | declares that a module depends on another module | contextual | 9 | 112, 115 |
return | returns from a method, optionally with a value | reserved | 1.0 | 30 |
sealed | a class or interface with a controlled set of direct subtypes | contextual | 17 | 51 |
short | the 16-bit signed integer type | reserved | 1.0 | 10 |
static | a member of the class, not of an instance; a static nested class; import static; requires static | reserved | 1.0 | 32, 64, 115 |
strictfp | strict floating-point rules; obsolete since Java 17, where all arithmetic is strict | reserved | 1.2 | 13 |
super | the superclass constructor or method; a lower bound of a wildcard | reserved | 1.0 | 41, 79 |
switch | a selection statement or expression | reserved | 1.0 | 16, 23 |
synchronized | a method or block that holds an object's intrinsic lock | reserved | 1.0 | 98 |
this | the implicit parameter of a method; calls another constructor of this class | reserved | 1.0 | 30, 34 |
throw | throws an exception | reserved | 1.0 | 68 |
throws | declares the checked exceptions a method can throw | reserved | 1.0 | 67 |
to | part of a qualified exports or opens declaration | contextual | 9 | 115 |
transient | marks a field that is skipped by serialization | reserved | 1.0 | — |
transitive | modifies requires: readability passes on to clients | contextual | 9 | 115 |
true | one of the two boolean values | literal | 1.0 | 11 |
try | a block whose exceptions are handled; try-with-resources | reserved | 1.0 | 69, 70 |
uses | declares that a module consumes a service | contextual | 9 | 115 |
var | declares a local variable whose type is inferred; lambda parameters | contextual | 10 | 12, 60 |
void | marks a method that returns no value | reserved | 1.0 | 30 |
volatile | a field that is read and written coherently across threads | reserved | 1.0 | 99 |
when | introduces a guard of a case pattern | contextual | 21 | 52 |
while | a loop, or the end of a do/while loop | reserved | 1.0 | 22 |
with | names the implementation classes in a provides declaration | contextual | 9 | 115 |
yield | produces the value of a switch expression block | contextual | 14 | 16 |
_ | the underscore: an unnamed variable or pattern (final in Java 22) | reserved | 9 | 52 |
A few entries need a remark:
constandgotoare reserved so that C and C++ habits produce a clear compile error. Java hasstatic finalconstants and labeledbreak/continueinstead.strictfpstill compiles but has had no effect since Java 17 (JEP 306). All floating-point arithmetic is strict now, andjavac -Xlintwarns about the redundant modifier.nativeandtransientbelong to topics beyond this course: calling native code (JNI, or the Foreign Function & Memory API final in Java 22) and object serialization._was an ordinary identifier until Java 8. Java 9 made it a keyword. Java 21 previewed it and Java 22 finalized it (JEP 456) as an unnamed variable or pattern, as incatch (NumberFormatException _)orcase Point(var x, _).exports,module,open,opens,provides,requires,to,transitive,usesandwithonly matter insidemodule-info.java. In ordinary code you can use them freely as names.non-sealedis the only hyphenated keyword. Becausenon-sealedisn't a valid identifier, adding it couldn't break any program.
Keywords by topic
If you prefer to learn them in groups:
- Primitive types:
boolean,byte,char,short,int,long,float,double, plusvoidfor "no value". - Control flow:
if,else,switch,case,default,yield,when,for,while,do,break,continue,return. - Exceptions:
try,catch,finally,throw,throws,assert. - Declaring types:
class,interface,enum,record,extends,implements,sealed,non-sealed,permits. - Modifiers:
public,protected,private,static,final,abstract,synchronized,volatile,transient,native,strictfp. - Objects and references:
new,this,super,instanceof, plus the literalnull. - Organizing code:
package,import, and the module wordsmodule,open,requires,transitive,exports,opens,to,uses,provides,with. - Local inference and placeholders:
var,_.
Asking the compiler
The javax.lang.model.SourceVersion class answers keyword questions for any Java version. isKeyword(word, version) is true for reserved keywords and for the literals true, false and null. isName(word, version) tells you whether a dotted name may be used as a qualified identifier. The program below checks a selection of words against Java 21, shows that _ wasn't yet a keyword in Java 8, uses several contextual keywords as perfectly legal variable and field names, and asks the in-process compiler (javax.tools.JavaCompiler) which declarations it accepts with --release 21.
import java.io.IOException;
import java.net.URI;
import java.nio.file.*;
import java.util.*;
import javax.lang.model.SourceVersion;
import javax.tools.*;
public class Solution {
// contextual keywords are ordinary identifiers in most positions
static int record = 1, module = 2, sealed = 3, permits = 4, when = 5, with = 6, to = 7;
static Path out;
static String check(String code) {
JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
var source = new SimpleJavaFileObject(URI.create("string:///Test.java"), JavaFileObject.Kind.SOURCE) {
@Override public CharSequence getCharContent(boolean ignore) { return code; }
};
var diags = new DiagnosticCollector<JavaFileObject>();
var fm = javac.getStandardFileManager(null, Locale.ROOT, null);
boolean ok = javac.getTask(null, fm, diags, List.of("--release", "21", "-d", out.toString()), null, List.of(source)).call();
if (ok) return "compiles";
return "error: " + diags.getDiagnostics().get(0).getMessage(Locale.ROOT).lines().findFirst().orElse("");
}
public static void main(String[] args) throws IOException {
out = Files.createTempDirectory("kw");
System.out.println("-- SourceVersion.isKeyword(word, RELEASE_21) --");
List<String> words = List.of("class", "goto", "const", "strictfp", "_", "true", "null",
"var", "record", "yield", "sealed", "non-sealed", "module", "exports", "when");
for (String w : words)
System.out.printf(" %-10s keyword: %-5s usable as a variable name: %s%n",
w, SourceVersion.isKeyword(w, SourceVersion.RELEASE_21),
SourceVersion.isName(w, SourceVersion.RELEASE_21));
System.out.println(" _ was a keyword in Java 8? " + SourceVersion.isKeyword("_", SourceVersion.RELEASE_8));
System.out.println("-- contextual keywords used as identifiers --");
var var = "var is a variable here";
String yield = "yield";
System.out.println(" " + var + ", " + yield + ", sum of fields = "
+ (record + module + sealed + permits + when + with + to));
System.out.println("-- what javac --release 21 accepts --");
Map<String, String> tests = new LinkedHashMap<>();
tests.put("int goto = 1;", "class Test { int goto = 1; }");
tests.put("class var {}", "class var {}");
tests.put("class record {}", "class record {}");
tests.put("String module, open, to;", "class Test { String module, open, to; }");
tests.put("enum Kind { sealed, permits }", "enum Kind { sealed, permits }");
tests.put("int strictfp = 0;", "class Test { int strictfp = 0; }");
tests.put("var x = null;", "class Test { void f() { var x = null; } }");
tests.forEach((label, code) -> System.out.printf(" %-30s -> %s%n", label, check(code)));
try (var files = Files.walk(out)) {
files.sorted(Comparator.reverseOrder()).forEach(f -> f.toFile().delete());
}
}
}
-- SourceVersion.isKeyword(word, RELEASE_21) --
class keyword: true usable as a variable name: false
goto keyword: true usable as a variable name: false
const keyword: true usable as a variable name: false
strictfp keyword: true usable as a variable name: false
_ keyword: true usable as a variable name: false
true keyword: true usable as a variable name: false
null keyword: true usable as a variable name: false
var keyword: false usable as a variable name: true
record keyword: false usable as a variable name: true
yield keyword: false usable as a variable name: true
sealed keyword: false usable as a variable name: true
non-sealed keyword: false usable as a variable name: false
module keyword: false usable as a variable name: true
exports keyword: false usable as a variable name: true
when keyword: false usable as a variable name: true
_ was a keyword in Java 8? false
-- contextual keywords used as identifiers --
var is a variable here, yield, sum of fields = 28
-- what javac --release 21 accepts --
int goto = 1; -> error: <identifier> expected
class var {} -> error: 'var' not allowed here
class record {} -> error: 'record' not allowed here
String module, open, to; -> compiles
enum Kind { sealed, permits } -> compiles
int strictfp = 0; -> error: <identifier> expected
var x = null; -> error: cannot infer type for local variable x
non-sealed is neither a keyword nor a usable name to SourceVersion, because the hyphen means it can never be an identifier anyway. The last test shows a classic var pitfall. var x = null; doesn't compile because null has no type from which to infer one.
Common questions
Can I name a variable var, record or yield?
var and record can be variable names, because they're contextual keywords. You can't name a type var, record, yield, sealed or permits. A method called yield can be declared, but calls to it must be qualified, as in this.yield(), to avoid confusion with the yield statement.
Is _ still a valid variable name?
No. It has been a keyword since Java 9. Since Java 22 it stands for an unnamed variable or pattern that you don't use, such as catch (Exception _) or case Point(var x, _).
Why are const and goto reserved if Java doesn't use them?
So that programmers coming from C and C++ get a clear compile error instead of surprising behavior. Java uses static final for constants and labeled break and continue for jumps.
Are true, false and null keywords?
Technically they are literals, not keywords, but you can't use them as identifiers either.
Does strictfp still do anything?
No. Since Java 17 (JEP 306), all floating-point operations are strict, and the modifier has no effect. The compiler accepts it, and -Xlint warns that it is redundant.
API reference
| Method | Description |
|---|---|
static boolean SourceVersion.isKeyword(CharSequence s, SourceVersion version) | true if s is a keyword or literal in that version (Java 9+) |
static boolean SourceVersion.isIdentifier(CharSequence name) | true if name is syntactically an identifier (it may still be a keyword) |
static boolean SourceVersion.isName(CharSequence name, SourceVersion version) | true if name is a valid (qualified) name that is not a keyword |
static SourceVersion SourceVersion.latestSupported() | the newest version the current compiler supports |
JavaCompiler ToolProvider.getSystemJavaCompiler() | the in-process javac |
Summary
- Java has 51 reserved keywords, 17 contextual keywords and 3 literals (
true,false,null). - Contextual keywords such as
var,record,yield,sealed,permits,whenand the module words stay usable as identifiers, which keeps old code compiling. Some of them can't be used as type names. constandgotoare reserved but unused,strictfpis obsolete, and_now declares unnamed variables and patterns.SourceVersion.isKeywordandisNameanswer "is this a keyword?" for any language version.
Practice Questions
Which of these lines compile: int record = 5; class record {} String module = "m"; int goto = 1;
int record = 5; and String module = "m"; compile because both are contextual keywords used as variable names. class record {} fails because record can't name a type, and int goto = 1; fails because goto is a reserved keyword.
Are true, false and null keywords?
No, they're literals. You still can't use them as identifiers, and SourceVersion.isKeyword reports them as true for convenience.
Why was var made a contextual keyword rather than a reserved one?
To preserve source compatibility. Existing code that used var as a variable, method or package name keeps compiling. Only type declarations named var, which conventional naming rules discourage anyway, became illegal.
What does the underscore mean in catch (IOException _) and since when is it allowed?
It declares an unnamed exception parameter, one you deliberately don't use. _ has been a keyword since Java 9, previewed for unnamed variables in Java 21 and final in Java 22.
Name the words that have special meaning only inside module-info.java.
module, open, requires, transitive, exports, opens, to, uses, provides and with. Outside a module declaration they're ordinary identifiers. static keeps its role in requires static, but it's a reserved keyword everywhere.
Congratulations on finishing the Core Java course! You've gone from installing the JDK through objects, generics, collections, concurrency, annotations and the module system. Keep this reference handy, write lots of code, and come back to any lesson whenever you need a refresher. When you're ready for the libraries that real applications are built on (streams, files, XML, networking, databases, date and time, security, Swing and native code), continue with the second course: Java Streams Explained: From Loops to Stream Pipelines.
Previous: Java Module Services, requires transitive and static, and Module Tools Back to the start: What Is Java? The Language, the Platform, and the JVM Explained
Related reading

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.