Java Keywords - Complete Reference
Learn all Java keywords and reserved words with detailed explanations, usage examples, and best practices. Keywords are reserved words that have special meaning in Java and cannot be used as identifiers.
53 Keywords
Reserved in Java
Cannot be Identifiers
Reserved for Language
Case Sensitive
All in lowercase
1. What are Java Keywords?
Keywords are reserved words in Java that have predefined meanings and purposes. These words cannot be used as identifiers (variable names, method names, class names, etc.) because they are part of the Java language syntax itself.
Key Characteristics
- Total 53 keywords in Java (as of Java 17)
- All keywords are in lowercase
- Cannot be used as identifiers
- Some keywords are unused (
goto,const) - Keywords define the structure of Java programs
- Each keyword has specific syntax rules
Categories of Keywords
- Access Modifiers: public, private, protected
- Class-related: class, interface, enum
- Control Flow: if, else, switch, case
- Loop Control: for, while, do, break, continue
- Exception Handling: try, catch, finally, throw, throws
- Modifiers: static, final, abstract, synchronized
Quick Reference: All Java Keywords
Here are all 53 Java keywords. Try to memorize these as they form the foundation of Java programming:
2. Complete Java Keywords Reference Table
This comprehensive table lists all Java keywords with their category, description, and importance level:
| Keyword | Category | Description | Importance | Example Usage |
|---|---|---|---|---|
abstract |
Modifier | Used to declare abstract classes and methods that must be implemented by subclasses | High | abstract class Animal { abstract void sound(); } |
boolean |
Data Type | Declares a variable that can hold only true or false values | High | boolean isJavaFun = true; |
break |
Control | Terminates loops or switch statements | High | for(int i=0; i<10; i++) { if(i==5) break; } |
byte |
Data Type | 8-bit integer data type (-128 to 127) | Medium | byte age = 25; |
case |
Control | Used in switch statements to define different cases | High | case 1: System.out.println("One"); break; |
catch |
Exception | Catches exceptions generated by try statements | High | catch(Exception e) { e.printStackTrace(); } |
char |
Data Type | 16-bit Unicode character | High | char grade = 'A'; |
class |
Class | Declares a new class (blueprint for objects) | High | public class HelloWorld { } |
const |
Unused | Reserved but not used (use 'final' instead) | Low | Not used in Java |
continue |
Control | Skips current iteration of a loop | High | for(int i=0; i<10; i++) { if(i==5) continue; } |
default |
Control | Default case in switch statement | High | default: System.out.println("Invalid"); |
do |
Loop | Starts a do-while loop (executes at least once) | High | do { ... } while(condition); |
double |
Data Type | 64-bit floating-point number | High | double pi = 3.14159; |
else |
Control | Alternative condition in if-else statements | High | if(x>0) {...} else {...} |
enum |
Class | Declares an enumeration (fixed set of constants) | Medium | enum Color { RED, GREEN, BLUE } |
extends |
Inheritance | Indicates that a class inherits from another class | High | class Dog extends Animal { } |
final |
Modifier | Makes a variable constant, prevents inheritance or overriding | High | final double PI = 3.14159; |
finally |
Exception | Block that always executes after try-catch | High | finally { System.out.println("Cleanup"); } |
float |
Data Type | 32-bit floating-point number | Medium | float price = 19.99f; |
for |
Loop | Starts a for loop | High | for(int i=0; i<10; i++) { } |
goto |
Unused | Reserved but not used in Java | Low | Not used in Java |
if |
Control | Tests a condition | High | if(age >= 18) { } |
implements |
Interface | Used by a class to implement an interface | High | class MyClass implements MyInterface { } |
import |
Package | Imports packages or classes | High | import java.util.ArrayList; |
instanceof |
Operator | Checks if an object is an instance of a class | Medium | if(obj instanceof String) { } |
int |
Data Type | 32-bit integer | High | int count = 10; |
interface |
Class | Declares an interface | High | interface Drawable { void draw(); } |
long |
Data Type | 64-bit integer | Medium | long population = 7800000000L; |
native |
Modifier | Indicates a method implemented in native code | Low | public native void method(); |
new |
Object | Creates new objects | High | String str = new String("Hello"); |
package |
Package | Declares a package | High | package com.example.myapp; |
private |
Access | Access modifier - accessible only within class | High | private int secretCode; |
protected |
Access | Access modifier - accessible within package and subclasses | High | protected void display() { } |
public |
Access | Access modifier - accessible from anywhere | High | public static void main(String[] args) |
return |
Control | Returns a value from a method | High | return result; |
short |
Data Type | 16-bit integer | Medium | short temperature = -10; |
static |
Modifier | Belongs to class rather than instances | High | static int count = 0; |
strictfp |
Modifier | Restricts floating-point calculations for portability | Low | strictfp class Calculator { } |
super |
Reference | Refers to parent class methods or constructors | High | super(); // calls parent constructor |
switch |
Control | Starts a switch statement | High | switch(day) { case 1: ... } |
synchronized |
Modifier | Provides thread safety for methods or blocks | Medium | synchronized void method() { } |
this |
Reference | Refers to current object | High | this.name = name; |
throw |
Exception | Throws an exception explicitly | High | throw new Exception("Error"); |
throws |
Exception | Declares exceptions a method can throw | High | void readFile() throws IOException |
transient |
Modifier | Prevents serialization of fields | Low | transient int tempData; |
try |
Exception | Starts a block of code to handle exceptions | High | try { riskyCode(); } |
void |
Return | Indicates a method returns no value | High | public void display() { } |
volatile |
Modifier | Ensures variable visibility across threads | Medium | volatile boolean running = true; |
while |
Loop | Starts a while loop | High | while(condition) { } |
- High: Used in almost every Java program. Must understand thoroughly.
- Medium
- Low: Rarely used or for advanced/specialized scenarios.
3. Important Keywords with Examples
Here are detailed examples of some of the most important Java keywords in action:
The 'static' Keyword
The static keyword is used for memory management. Static members belong to the class rather than instances.
public class StaticExample {
// Static variable - shared by all instances
static int count = 0;
// Instance variable - separate for each object
int id;
public StaticExample() {
count++; // Increment static counter
id = count; // Assign unique ID
}
// Static method - can be called without creating object
public static void displayCount() {
System.out.println("Total objects created: " + count);
}
// Instance method - requires object
public void displayId() {
System.out.println("My ID: " + id);
}
public static void main(String[] args) {
// Call static method without object
StaticExample.displayCount();
// Create objects
StaticExample obj1 = new StaticExample();
StaticExample obj2 = new StaticExample();
StaticExample obj3 = new StaticExample();
// Call static method
StaticExample.displayCount(); // Output: Total objects created: 3
// Call instance methods
obj1.displayId(); // Output: My ID: 1
obj2.displayId(); // Output: My ID: 2
}
}
The 'final' Keyword
The final keyword can be used with variables, methods, and classes to restrict modification.
public class FinalExample {
// Final variable - cannot be changed (constant)
final double PI = 3.14159;
final int MAX_SPEED; // Can be initialized in constructor
// Final method - cannot be overridden
public final void displayInfo() {
System.out.println("This method cannot be overridden");
}
public FinalExample() {
MAX_SPEED = 120; // Initialize final variable in constructor
}
public double calculateArea(double radius) {
// PI cannot be changed here
return PI * radius * radius;
}
}
// Final class - cannot be extended
final class SecurityManager {
public void checkAccess() {
System.out.println("Access checked");
}
}
// This would cause compilation error:
// class ExtendedSecurityManager extends SecurityManager { }
The 'synchronized' Keyword
The synchronized keyword prevents thread interference and memory consistency errors.
public class SynchronizedExample {
private int counter = 0;
// Synchronized method - only one thread can execute at a time
public synchronized void increment() {
counter++;
}
// Synchronized block - more fine-grained control
public void incrementWithBlock() {
// Non-critical code can run concurrently
System.out.println("Processing...");
// Only this block is synchronized
synchronized(this) {
counter++;
System.out.println("Counter: " + counter);
}
// More non-critical code
System.out.println("Done processing");
}
public int getCounter() {
return counter;
}
public static void main(String[] args) {
SynchronizedExample example = new SynchronizedExample();
// Multiple threads accessing synchronized methods
Thread t1 = new Thread(() -> {
for(int i = 0; i < 1000; i++) {
example.increment();
}
});
Thread t2 = new Thread(() -> {
for(int i = 0; i < 1000; i++) {
example.incrementWithBlock();
}
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Final counter value: " + example.getCounter());
}
}
4. Common Mistakes and Best Practices
- Using keywords as identifiers:
int class = 10;❌ (class is a keyword) - Misspelling keywords:
publikinstead ofpublic❌ - Using reserved words in wrong context: Using
breakoutside loops ❌ - Case sensitivity:
Publicinstead ofpublic❌ - Forgetting required keywords: Missing
classkeyword in class declaration ❌
Best Practices
- Always use
finalfor constants - Use appropriate access modifiers (
private,protected,public) - Prefer
interfaceoverabstract classwhen possible - Use
try-with-resourcesfor automatic resource management - Mark fields as
volatilefor thread visibility - Use
@Overrideannotation when overriding methods
Memory Management Keywords
new- Allocates memory for objectsstatic- Memory allocated at class loadingfinal- May enable compiler optimizationstransient- Excludes fields from serializationvolatile- Ensures visibility across threads