Skip to content
Home Java Java Keywords and Identifiers Explained — Rules, Reserved Words and Real Mistakes

Java Keywords and Identifiers Explained — Rules, Reserved Words and Real Mistakes

Where developers are forged. · Structured learning · Free forever.
📍 Part of: Java Basics → Topic 10 of 13
Master Java keywords and identifiers with this Senior Editor's guide.
🧑‍💻 Beginner-friendly — no prior Java experience needed
In this tutorial, you'll learn
Master Java keywords and identifiers with this Senior Editor's guide.
  • Java has 53 reserved keywords — every one is always lowercase, and none can ever be used as an identifier name, period.
  • 'const' and 'goto' are reserved keywords in Java even though they do nothing — you still cannot use them as variable or class names.
  • A valid identifier starts with a letter, $ or _ — never a digit — and contains only letters, digits, $ or _ with no spaces or special characters.
✦ Plain-English analogy ✦ Real code with output ✦ Interview questions
Quick Answer

Think of Java like a board game with a rulebook. The keywords are the official rule words printed in the rulebook — words like 'if', 'while', and 'class' that the game already owns and you can never rename. Identifiers are the names YOU write on your player tokens, your pieces, and your score sheets — things like 'playerScore' or 'boardSize'. The game lets you name your pieces almost anything, but you can't steal a word that's already in the rulebook. That's the whole distinction in one sentence.

Every Java program you'll ever write is built from two raw ingredients: words the Java language owns, and words you invent yourself. Get the distinction wrong and your code won't even compile — you'll stare at a red error wondering why Java is rejecting a perfectly normal-looking name. At io.thecodeforge, we emphasize that mastering these fundamentals prevents the 'silly' syntax errors that slow down enterprise delivery.

In this guide, we'll break down exactly what every Java keyword is and why it exists, how to write valid identifiers that pass strict code reviews, and the naming conventions senior developers use so your code looks professional. We'll also cover LeetCode-standard interview questions on this topic to ensure you're ready for your next technical screening.

By the end, you'll know the three most common mistakes beginners make and precisely how to avoid them in a production environment.

What Are Java Keywords? The 53 Words That Belong to Java, Not You

A keyword in Java is a word that the Java language specification has permanently reserved for its own use. You cannot use a keyword as a name for a class, variable, method, or anything else you create. The compiler recognizes these words and treats them as instructions, not labels.

Java currently has 53 reserved keywords. Some execute control flow ('if', 'for'), some define structure ('class', 'interface'), and some manage data types ('int', 'boolean'). Notably, two words — 'const' and 'goto' — are reserved but have no function in Java; they are kept only to ensure that developers coming from C++ don't use them, and to keep the door open for future language updates. Keywords are always lowercase. While 'Class' is technically a valid identifier, it violates every professional standard at io.thecodeforge and should be avoided.

io/thecodeforge/basics/KeywordDemonstration.java · JAVA
123456789101112131415161718192021222324252627
package io.thecodeforge.basics;

/**
 * io.thecodeforge: Demonstration of Java Keywords in context.
 */
public class KeywordDemonstration { 

    public static void main(String[] args) {
        // 'int' is a keyword; 'studentAge' is an identifier
        int studentAge = 17;

        // 'boolean' is a keyword; 'isEnrolled' is an identifier
        boolean isEnrolled = true;

        // 'if' and 'else' provide control flow
        if (studentAge >= 18) {
            System.out.println("Status: Adult");
        } else {
            System.out.println("Status: Minor");
        }

        // 'for' loop using 'int' for the counter
        for (int i = 1; i <= 3; i++) {
            System.out.println("Processing batch: " + i);
        }
    }
}
▶ Output
Status: Minor
Processing batch: 1
Processing batch: 2
Processing batch: 3
🔥Quick Reference:
The two keywords 'const' and 'goto' are reserved but unused in Java. They produce a compile error if you try to use them as identifiers, even though Java has no actual 'goto' statement. This is intentional — Java's designers anticipated they might need them later.

What Are Identifiers? The Names YOU Give to Everything in Your Code

An identifier is a user-defined name for program elements like variables, methods, and classes. At io.thecodeforge, we follow the 'Clean Code' philosophy: identifiers should be descriptive and follow Java's lexical rules.

Rule 1 — Starting Characters: Must start with a letter (A-Z, a-z), a dollar sign ($), or an underscore (_). It CANNOT start with a digit. Rule 2 — Subsequent Characters: Can include digits (0-9), but no spaces or special characters like @, #, or -. Rule 3 — Keyword Collision: You cannot use any of the 53 reserved words. Rule 4 — Case Sensitivity: 'ForgeVariable' and 'forgeVariable' are two completely different identifiers to the JVM.

io/thecodeforge/basics/IdentifierRulesDemo.java · JAVA
123456789101112131415161718
package io.thecodeforge.basics;

public class IdentifierRulesDemo {
    public static void main(String[] args) {
        // --- VALID IDENTIFIERS ---
        int studentAge = 20;           
        double $accountBalance = 1500.75; 
        boolean _isActive = true;      
        String firstName = "Maria";    

        // --- INVALID IDENTIFIERS (Will not compile) ---
        // int 2playerScore = 10;   // ERROR: Starts with digit
        // int player score = 10;   // ERROR: Contains space
        // int class = 10;          // ERROR: 'class' is a keyword

        System.out.println("Identifier Check: Success");
    }
}
▶ Output
Identifier Check: Success
💡Pro Tip:
Even though starting identifiers with $ or _ is technically legal, real-world Java convention avoids both. The $ sign is reserved in practice for generated code (like inner classes). The underscore as a single-character identifier (_) was deprecated in Java 9 and will eventually become a keyword itself. Stick to plain camelCase names like 'studentAge' and 'calculateTotal'.

Naming Conventions — The Unwritten Rules Every Java Developer Follows

While the compiler enforces rules, the community enforces conventions. Following these makes your code 'Greppable' and professional. At io.thecodeforge, we strictly adhere to these standards:

  1. Classes/Interfaces: PascalCase (e.g., PaymentProcessor).
  2. Methods/Variables: camelCase (e.g., processPayment, userToken).
  3. Constants: SCREAMING_SNAKE_CASE (e.g., DEFAULT_TIMEOUT).
  4. Packages: Lowercase with reverse-domain naming (e.g., io.thecodeforge.util).
io/thecodeforge/basics/NamingConventionsShowcase.java · JAVA
12345678910111213141516171819202122232425
package io.thecodeforge.basics;

public class NamingConventionsShowcase { 

    // Static Constant
    private static final int MAX_RETRY_COUNT = 3;

    // Instance Variable
    private String developerName;

    public NamingConventionsShowcase(String developerName) {
        this.developerName = developerName;
    }

    // Instance Method
    public void executeTask() {
        System.out.println("Task executed by: " + developerName);
    }

    public static void main(String[] args) {
        NamingConventionsShowcase forgeDev = new NamingConventionsShowcase("Alex");
        forgeDev.executeTask();
        System.out.println("Max Retries: " + MAX_RETRY_COUNT);
    }
}
▶ Output
Task executed by: Alex
Max Retries: 3
🔥Interview Gold:
Interviewers often ask: 'What's the difference between a keyword and an identifier in Java?' The precise answer: a keyword is a reserved token with a predefined meaning in the Java language spec that cannot be used as an identifier. An identifier is a user-defined name for a program element (variable, class, method) that follows Java's four naming rules. Knowing this distinction cold will impress any interviewer.
AspectJava KeywordsJava Identifiers
DefinitionReserved by JVMDefined by Developer
Count53 (Fixed)Infinite
CaseStrictly LowercaseCase-sensitive (Mixed)
Examplespublic, static, voidforgeService, user_id
UsageControl/Data/StructureLabeling/Naming

🎯 Key Takeaways

  • Java has 53 reserved keywords — every one is always lowercase, and none can ever be used as an identifier name, period.
  • 'const' and 'goto' are reserved keywords in Java even though they do nothing — you still cannot use them as variable or class names.
  • A valid identifier starts with a letter, $ or _ — never a digit — and contains only letters, digits, $ or _ with no spaces or special characters.
  • 'true', 'false', and 'null' are technically literals, not keywords, but they're still reserved — however 'True' (capital T) IS a legal identifier, just a terrible one to use.

⚠ Common Mistakes to Avoid

    Starting a variable name with a digit — e.g. writing 'int 2players = 5;' — Java immediately throws a compile error: 'illegal start of expression'. Fix it by putting a letter, $ or _ first: 'int player2Count = 5;' or 'int twoPlayers = 5;'.
    Fix

    it by putting a letter, $ or _ first: 'int player2Count = 5;' or 'int twoPlayers = 5;'.

    Using a Java keyword as a variable name — e.g. writing 'int class = 3;' expecting it to mean 'class number'. The compiler rejects this with 'error: illegal start of expression' because 'class' is permanently reserved. Fix it with a descriptive alternative: 'int classNumber = 3;' or 'int gradeLevel = 3;'.
    Fix

    it with a descriptive alternative: 'int classNumber = 3;' or 'int gradeLevel = 3;'.

    Thinking Java keywords are case-insensitive — e.g. writing 'Int studentAge = 20;' with a capital I, expecting Java to treat it as the 'int' keyword. Java is fully case-sensitive, so 'Int' is NOT a keyword — it's treated as an unknown type name, causing 'error: cannot find symbol'. Always write keywords in lowercase exactly as they appear in the spec.

    n the spec.

Interview Questions on This Topic

  • QIdentify the invalid identifiers in this list: _myVar, $amount, 1stPlace, const, Main, class.
  • QWhy are 'const' and 'goto' reserved in Java if they have no functionality?
  • QIs 'String' a keyword? Explain why or why not using the distinction between keywords and classes.
  • QExplain the 'unnamed variable' feature introduced in Java 21 regarding the underscore (_) identifier.
  • QHow does the JVM handle identifiers in terms of memory compared to keywords?

Frequently Asked Questions

How many keywords are there in Java?

Java has 53 reserved keywords as of Java 17, including familiar ones like 'class', 'int', 'if', 'for', and 'return'. Two of them — 'const' and 'goto' — are reserved but have never been given any actual function in Java. All 53 are off-limits as identifier names.

Is 'String' a keyword in Java?

No — 'String' is not a keyword; it's a class in the Java standard library (java.lang.String). Because it's a class name rather than a keyword, it starts with a capital S. However, 'string' in lowercase is neither a keyword nor a built-in type in Java — you'd get a compile error using it as a type name. Always use 'String' with a capital S.

Can I use an underscore _ as a variable name in Java?

Technically yes in older Java versions, but a single underscore _ as a standalone identifier was deprecated in Java 9 and produces a compile-time error in Java 21 and beyond, where it's been repurposed as an unnamed variable pattern. Avoid using _ alone as any identifier — use descriptive names instead.

🔥
Naren Founder & Author

Developer and founder of TheCodeForge. I built this site because I was tired of tutorials that explain what to type without explaining why it works. Every article here is written to make concepts actually click.

← PreviousComments in JavaNext →Java Access Modifiers
Forged with 🔥 at TheCodeForge.io — Where Developers Are Forged