Java Keywords and Identifiers Explained — Rules, Reserved Words and Real Mistakes
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. Understanding this distinction isn't optional homework; it's the foundation everything else in Java sits on top of.
The problem this topic solves is simple but painful: beginners pick names for variables, classes, or methods without knowing there's a list of roughly 53 words they're forbidden from using. They also sometimes write names that look fine to a human but break Java's strict naming rules — starting a variable with a number, using a space, or accidentally slipping in a special character. Java's compiler has zero tolerance for these violations.
By the end of this article you'll know exactly what every Java keyword is and why it exists, you'll be able to write valid identifiers confidently, you'll understand the naming conventions senior developers use so your code looks professional, and you'll know the three most common mistakes beginners make in this area — and precisely how to avoid them.
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 recognises these words and treats them as instructions, not labels.
Java currently has 53 reserved keywords. Some of them execute control flow — 'if', 'else', 'for', 'while', 'switch', 'break', 'continue', 'return'. Some define structure — 'class', 'interface', 'enum', 'record'. Some control access — 'public', 'private', 'protected'. Some manage data types — 'int', 'double', 'boolean', 'char', 'long', 'float', 'byte', 'short'. Some handle object-oriented concepts — 'extends', 'implements', 'super', 'this', 'new', 'instanceof'. And two words — 'const' and 'goto' — are reserved but have never actually been used in Java. They exist to prevent programmers from using them in case Java ever needs them.
Keywords are always lowercase. Java is case-sensitive, so 'Class' with a capital C is technically a valid identifier (though a terrible one), but 'class' in lowercase belongs entirely to Java. Never capitalise a keyword hoping to sneak it past the compiler — it works, but it will confuse every developer who reads your code, including future you.
// This file demonstrates Java keywords in realistic context. // Every word in CAPITALS in the comments is a keyword being used. public class KeywordDemonstration { // 'public' and 'class' are keywords // 'static', 'void', and 'int' are all keywords public static void main(String[] args) { // 'int' is a keyword — it tells Java this variable holds a whole number int studentAge = 17; // 'boolean' is a keyword — it holds only true or false boolean isEnrolled = true; // 'if' and 'else' are keywords — they control which code runs if (studentAge >= 18) { System.out.println("Student is an adult."); } else { System.out.println("Student is a minor."); } // 'for' is a keyword — it repeats a block of code for (int courseNumber = 1; courseNumber <= 3; courseNumber++) { System.out.println("Enrolled in course: " + courseNumber); } // 'return' is a keyword — it sends a value back from a method // Here it ends the main method } }
Enrolled in course: 1
Enrolled in course: 2
Enrolled in course: 3
What Are Identifiers? The Names YOU Give to Everything in Your Code
An identifier is simply a name you choose. When you write 'int studentAge = 17', the word 'int' is a keyword (Java's word) and 'studentAge' is an identifier (your word). Every class name, method name, variable name, and constant name you write is an identifier.
Java has four strict rules for what makes a valid identifier. Break any one of them and your code won't compile.
Rule 1 — Valid starting characters: An identifier must start with a letter (a–z or A–Z), a dollar sign ($), or an underscore (_). It cannot start with a digit. So 'age' is valid, '$amount' is valid, '_count' is valid, but '1age' is illegal.
Rule 2 — Valid subsequent characters: After the first character, you can use letters, digits (0–9), dollar signs, or underscores. No spaces. No hyphens. No dots. No @ symbols. So 'student_age2' is valid, but 'student-age' and 'student age' are both illegal.
Rule 3 — No keywords: You cannot use a Java keyword as an identifier. 'class', 'int', 'for', and all the others are off limits.
Rule 4 — No length limit (practically speaking): Identifiers can be as long as you need. Java has no practical maximum length. 'a' is valid. 'totalNumberOfRegisteredStudentsInSemesterOne' is valid. Keep them meaningful but not absurd.
public class IdentifierRulesDemo { public static void main(String[] args) { // --- VALID IDENTIFIERS --- int studentAge = 20; // starts with a letter — perfectly fine double $accountBalance = 1500.75; // starts with $ — unusual but legal boolean _isActive = true; // starts with _ — legal (but avoid in practice) int totalScore2024 = 985; // letter start, digit in middle — fine String firstName = "Maria"; // camelCase — the Java convention System.out.println("Student age: " + studentAge); System.out.println("Account balance: $" + $accountBalance); System.out.println("Active status: " + _isActive); System.out.println("Total score 2024: " + totalScore2024); System.out.println("First name: " + firstName); // --- THE LINES BELOW ARE COMMENTED OUT BECAUSE THEY CAUSE COMPILE ERRORS --- // int 2playerScore = 10; // ERROR: starts with a digit // int player score = 10; // ERROR: contains a space // int player-score = 10; // ERROR: hyphen is not allowed // int class = 10; // ERROR: 'class' is a reserved keyword // int player@name = 10; // ERROR: @ is not a valid character } }
Account balance: $1500.75
Active status: true
Total score 2024: 985
First name: Maria
Naming Conventions — The Unwritten Rules Every Java Developer Follows
Java's compiler only cares about the four hard rules above. But every Java developer also follows a set of naming conventions — agreed-upon styles that make code readable across teams and projects. These aren't enforced by the compiler; they're enforced by your teammates and your own sanity six months from now.
Variables and methods use camelCase: start lowercase, capitalise each subsequent word. So 'studentAge', 'calculateMonthlyPayment', 'totalItemsInCart'. Never 'StudentAge' or 'student_age' for a variable.
Classes and interfaces use PascalCase (also called UpperCamelCase): every word starts with a capital. So 'BankAccount', 'StudentEnrollmentSystem', 'PaymentProcessor'.
Constants — variables declared with 'final' and 'static' — use ALL_CAPS_WITH_UNDERSCORES. So 'MAX_LOGIN_ATTEMPTS', 'PI', 'DEFAULT_TIMEOUT_SECONDS'.
Package names use all lowercase, often reversed domain names. So 'com.thecodeforge.banking' or 'io.thecodeforge.students'.
These conventions matter enormously. When a senior developer opens your code, they can instantly tell whether you're a professional who follows standards or someone who wrote random-cased names that take extra brainpower to parse.
// This class demonstrates ALL Java naming conventions in one realistic example. // Notice how each name immediately communicates its purpose AND its type. public class NamingConventionsShowcase { // Class: PascalCase // Constants: ALL_CAPS with underscores // 'static final' means this value never changes and belongs to the class static final int MAX_STUDENTS_PER_CLASS = 30; static final double PASSING_GRADE_THRESHOLD = 60.0; // Instance variables: camelCase (lowercase first word) private String studentFullName; // 'private' keyword + camelCase identifier private int studentId; private double currentGradeAverage; // Constructor: same name as class, PascalCase public NamingConventionsShowcase(String studentFullName, int studentId) { this.studentFullName = studentFullName; // 'this' keyword refers to this object this.studentId = studentId; this.currentGradeAverage = 0.0; } // Method: camelCase, starts with a verb to show it DOES something public void recordExamScore(double examScore) { // Local variable: camelCase boolean scoreIsAbovePassingThreshold = examScore >= PASSING_GRADE_THRESHOLD; if (scoreIsAbovePassingThreshold) { this.currentGradeAverage = examScore; System.out.println(studentFullName + " passed with " + examScore + "%"); } else { System.out.println(studentFullName + " did not meet the passing threshold of " + PASSING_GRADE_THRESHOLD + "%"); } } // Method that returns a value: verb + camelCase public boolean hasPassedCourse() { return currentGradeAverage >= PASSING_GRADE_THRESHOLD; } public static void main(String[] args) { // Object name: camelCase, meaningful noun NamingConventionsShowcase enrolledStudent = new NamingConventionsShowcase("Priya Sharma", 10245); enrolledStudent.recordExamScore(74.5); System.out.println("Max class size allowed: " + MAX_STUDENTS_PER_CLASS); System.out.println("Did Priya pass? " + enrolledStudent.hasPassedCourse()); } }
Max class size allowed: 30
Did Priya pass? true
| Aspect | Java Keywords | Java Identifiers |
|---|---|---|
| Who defines them? | Java language specification | You, the programmer |
| Total count | 53 reserved keywords | Unlimited — you create as many as you need |
| Can you change their meaning? | No — meaning is fixed by the language | Yes — you name them to mean whatever you intend |
| Case sensitivity | Always lowercase (e.g. 'class', 'int') | Case-sensitive — 'Age' and 'age' are different identifiers |
| Examples | int, class, if, for, return, public | studentAge, BankAccount, calculateTotal |
| Starts with a digit? | No — none start with digits | No — identifiers cannot start with digits either |
| Can contain spaces? | No | No — use camelCase instead |
| Unused reserved words | 'const' and 'goto' are reserved but unused | N/A — all identifiers you create are used |
| Convention for casing | All lowercase, no exceptions | camelCase for variables/methods, PascalCase for classes, ALL_CAPS for constants |
🎯 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
- ✕Mistake 1: 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;'.
- ✕Mistake 2: 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;'.
- ✕Mistake 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.
Interview Questions on This Topic
- QHow many keywords does Java have, and can you name some that are reserved but never actually used in any Java program?
- QWhat are the rules for a valid Java identifier? Give me an example of an identifier that looks valid but will cause a compile error.
- QIs 'true' a Java keyword? What about 'null'? How would you classify them — and does that mean you could use 'True' (capital T) as a variable name?
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.
Written and reviewed by senior developers with real-world experience across enterprise, startup and open-source projects. Every article on TheCodeForge is written to be clear, accurate and genuinely useful — not just SEO filler.