Java Keywords & Identifiers
This guide explains what keywords and identifiers are in Java, their rules, best practices, and examples. It’s beginner-friendly, interview-ready, and optimized for Google ranking.
What Are Keywords in Java?
- Keywords are reserved words in Java that have a special meaning in the language.
- You cannot use keywords as names for variables, classes, methods, or identifiers.
- Java has 52 keywords (depending on version) and 5 reserved literals like
true,false,null.
List of Java Keywords (Java 17)
| Keyword | Keyword | Keyword | Keyword |
|---|---|---|---|
| abstract | assert | boolean | break |
| byte | case | catch | char |
| class | const* | continue | default |
| do | double | else | enum |
| extends | final | finally | float |
| for | goto* | if | implements |
| import | instanceof | int | interface |
| long | native | new | package |
| private | protected | public | return |
| short | static | strictfp | super |
| switch | synchronized | this | throw |
| throws | transient | try | void |
| volatile | while | yield | record |
| sealed | permits | non-sealed | var |
| module | open | requires | exports |
⚠️ const and goto are reserved but not used in Java.
What Are Identifiers in Java?
- Identifiers are names you give to classes, methods, variables, and other elements in Java.
- They help uniquely identify these program elements in your code.
Rules for Identifiers
- Must start with a letter,
$, or_. - Can contain letters, digits,
$, or_. - Cannot be a keyword.
- Java is case-sensitive (
age≠Age). - No spaces or special characters allowed.
Valid & Invalid Identifiers Examples
| Valid Identifiers | Invalid Identifiers |
|---|---|
int age; | int 2age; // starts with digit |
String studentName; | String student-name; // invalid char |
double _salary; | int class; // keyword |
Naming Conventions (Best Practices)
| Element | Convention | Example |
|---|---|---|
| Class | PascalCase | StudentDetails |
| Method | camelCase | calculateSalary() |
| Variable | camelCase | totalSalary |
| Constant | UPPERCASE | MAX_AGE |
| Package | lowercase | com.example.project |
Following conventions improves readability, collaboration, and maintainability.
Example Program Using Keywords & Identifiers
public class Student {
// Instance Variables (Identifiers)
String studentName;
int age;
final double PI = 3.14159; // Constant
// Method
public void displayInfo() {
System.out.println("Name: " + studentName);
System.out.println("Age: " + age);
System.out.println("PI Value: " + PI);
}
public static void main(String[] args) {
Student s1 = new Student();
s1.studentName = "John";
s1.age = 25;
s1.displayInfo();
}
}
Output:
Name: John
Age: 25
PI Value: 3.14159
