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:
int class = 50;
// ERROR: class is a keyword and cannot be used as a variable nameThe 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.
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.