Java Keywords & Reserved Words
Java Keywords & Reserved Words
Java has 51 reserved keywords that have special meaning in the language. Understanding these keywords is fundamental to writing Java code.
Goal: Master all Java keywords, understand when and how to use them, and avoid common mistakes.
Key Insight: Keywords are case-sensitive and cannot be used as identifiers (variable names, method names, class names). They form the foundation of Java syntax and control program behavior.
What are Keywords?
Keywords are reserved words that have predefined meanings in Java. They cannot be used for naming variables, methods, or classes.
// ❌ WRONG - Using keyword as variable name
int class = 5; // Error: 'class' is a keyword
String public = "hi"; // Error: 'public' is a keyword
// ✅ CORRECT
int studentClass = 5;
String publicMessage = "hi";Case Sensitivity
// Keywords are lowercase and case-sensitive
public class Example { // ✅ CORRECT: 'public' is lowercase
// Public class Example { } // ❌ WRONG: 'Public' is not a keyword
}Java Keywords by Category
1. Access Modifiers (4 keywords)
Control visibility of classes, methods, and variables.
public
Accessible from anywhere.
public class MyClass {
public int publicVar = 10;
public void publicMethod() {
System.out.println("Accessible from anywhere");
}
}
// Different package
MyClass obj = new MyClass();
obj.publicMethod(); // ✅ Worksprivate
Accessible only within the same class.
public class BankAccount {
private double balance = 1000.0; // Only accessible inside this class
private void updateBalance() {
// Private method
}
public double getBalance() {
return balance; // Access private variable through public method
}
}
// Usage
BankAccount account = new BankAccount();
// account.balance; // ❌ Error: balance is private
account.getBalance(); // ✅ Worksprotected
Accessible within same package and subclasses.
// Parent class
public class Animal {
protected String species; // Accessible in subclasses
protected void makeSound() {
System.out.println("Some sound");
}
}
// Subclass (even in different package)
public class Dog extends Animal {
public void bark() {
species = "Canine"; // ✅ Can access protected member
makeSound(); // ✅ Can access protected method
}
}default (package-private)
No keyword - accessible only within same package.
// No access modifier = package-private
class PackageClass { // Only visible in same package
int packageVar; // Only accessible in same package
void packageMethod() {
// Only accessible in same package
}
}2. Class/Method/Variable Modifiers (7 keywords)
static
Belongs to class, not instance.
public class Counter {
static int count = 0; // Shared across all instances
static void increment() {
count++;
}
public static void main(String[] args) {
Counter.increment(); // Call without creating object
System.out.println(Counter.count); // Output: 1
}
}final
Cannot be changed (constant variable, non-overridable method, non-inheritable class).
// Final variable (constant)
final int MAX_SIZE = 100;
// MAX_SIZE = 200; // ❌ Error: cannot reassign
// Final method (cannot be overridden)
class Parent {
final void display() {
System.out.println("Cannot override this");
}
}
class Child extends Parent {
// void display() { } // ❌ Error: cannot override final method
}
// Final class (cannot be extended)
final class Utility {
// ...
}
// class MyUtility extends Utility { } // ❌ Error: cannot extend final classabstract
Incomplete class or method (must be overridden).
abstract class Shape {
abstract void draw(); // No implementation
void display() { // Can have concrete methods too
System.out.println("This is a shape");
}
}
class Circle extends Shape {
@Override
void draw() { // Must implement abstract method
System.out.println("Drawing circle");
}
}
// Shape s = new Shape(); // ❌ Error: cannot instantiate abstract class
Shape s = new Circle(); // ✅ Works
s.draw();synchronized
Thread-safe method or block.
public class BankAccount {
private int balance = 1000;
// Only one thread can execute this at a time
public synchronized void withdraw(int amount) {
if (balance >= amount) {
balance -= amount;
}
}
// Synchronized block
public void deposit(int amount) {
synchronized(this) {
balance += amount;
}
}
}volatile
Variable may be modified by multiple threads.
public class SharedData {
// Ensures visibility across threads
private volatile boolean flag = false;
public void setFlag() {
flag = true; // Change visible to all threads immediately
}
}transient
Field not serialized.
import java.io.Serializable;
public class User implements Serializable {
String username;
transient String password; // Won't be saved during serialization
// When object is saved, password is not included
}native
Method implemented in platform-specific code (C/C++).
public class NativeExample {
// Implementation in C/C++
public native void nativeMethod();
static {
System.loadLibrary("nativelib");
}
}3. Control Flow (11 keywords)
if, else
Conditional execution.
int age = 18;
if (age >= 18) {
System.out.println("Adult");
} else if (age >= 13) {
System.out.println("Teenager");
} else {
System.out.println("Child");
}switch, case, default
Multiple condition selection.
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Other day");
}for
Loop with initialization, condition, increment.
// Traditional for loop
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
// Enhanced for loop (for-each)
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println(num);
}while
Loop while condition is true.
int count = 0;
while (count < 5) {
System.out.println(count);
count++;
}do
Execute at least once, then check condition.
int count = 0;
do {
System.out.println(count); // Executes at least once
count++;
} while (count < 5);break
Exit loop or switch.
// Exit loop
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exit loop when i is 5
}
System.out.println(i);
}
// Exit switch
switch (value) {
case 1:
doSomething();
break; // Exit switch
}continue
Skip current iteration.
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
System.out.println(i); // Only prints odd numbers
}return
Exit method and optionally return value.
public int add(int a, int b) {
return a + b; // Return result
}
public void printMessage() {
System.out.println("Hello");
return; // Optional for void methods
}4. Exception Handling (6 keywords)
try, catch, finally
Handle exceptions.
try {
int result = 10 / 0; // May throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
} finally {
System.out.println("Always executes");
}throw
Manually throw exception.
public void validateAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
}throws
Declare exceptions method may throw.
public void readFile() throws IOException {
FileReader file = new FileReader("file.txt");
// May throw IOException
}assert
Testing condition (disabled by default).
public void divide(int a, int b) {
assert b != 0 : "Divisor cannot be zero";
int result = a / b;
}
// Enable with: java -ea ClassName5. Primitive Data Types (8 keywords)
// Integer types
byte smallNumber = 127; // 8-bit: -128 to 127
short mediumNumber = 32000; // 16-bit: -32,768 to 32,767
int number = 100000; // 32-bit: -2^31 to 2^31-1
long bigNumber = 10000000000L; // 64-bit: -2^63 to 2^63-1
// Floating-point types
float decimal = 3.14f; // 32-bit
double preciseDecimal = 3.14159265359; // 64-bit
// Character type
char letter = 'A'; // 16-bit Unicode
// Boolean type
boolean isTrue = true; // true or false6. Object-Oriented (7 keywords)
class
Define a class.
public class Student {
String name;
int age;
void study() {
System.out.println(name + " is studying");
}
}interface
Define contract (abstract methods).
public interface Drawable {
void draw(); // Abstract method (no body)
default void display() { // Default method (Java 8+)
System.out.println("Displaying");
}
}extends
Inherit from class.
class Animal {
void eat() {
System.out.println("Eating");
}
}
class Dog extends Animal { // Dog inherits from Animal
void bark() {
System.out.println("Barking");
}
}implements
Implement interface.
interface Flyable {
void fly();
}
class Bird implements Flyable {
@Override
public void fly() {
System.out.println("Flying");
}
}new
Create object instance.
Student student = new Student(); // Create new object
int[] array = new int[10]; // Create new arraythis
Reference to current object.
public class Person {
String name;
public Person(String name) {
this.name = name; // Distinguish field from parameter
}
public void display() {
this.printName(); // Call method on current object
}
private void printName() {
System.out.println(this.name);
}
}super
Reference to parent class.
class Animal {
void makeSound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
super.makeSound(); // Call parent method
System.out.println("Bark");
}
}7. Package Management (2 keywords)
package
Declare package.
package com.example.myapp; // Must be first statement
public class MyClass {
// ...
}import
Import classes from other packages.
import java.util.ArrayList; // Import single class
import java.util.*; // Import all classes
import static java.lang.Math.*; // Static import
public class Example {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
System.out.println(sqrt(16)); // Static import allows this
}
}8. Special Keywords (4 keywords)
void
Method returns no value.
public void printMessage() {
System.out.println("Hello");
// No return statement needed
}instanceof
Check object type.
Object obj = "Hello";
if (obj instanceof String) {
String str = (String) obj; // Safe to cast
System.out.println(str.toUpperCase());
}null
Null reference (absence of value).
String text = null; // No object assigned
if (text == null) {
System.out.println("Text is null");
}
// text.length(); // ❌ NullPointerExceptionenum
Define enumeration (Java 5+).
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
// Usage
Day today = Day.MONDAY;
switch (today) {
case MONDAY:
System.out.println("Start of week");
break;
case FRIDAY:
System.out.println("Almost weekend");
break;
}9. Reserved but Unused (2 keywords)
goto
Reserved but not implemented.
// goto is reserved but cannot be used in Java
// goto label; // ❌ Compile errorconst
Reserved but not implemented (use final instead).
// const is reserved but cannot be used
// const int MAX = 100; // ❌ Compile error
// Use final instead
final int MAX = 100; // ✅ CorrectComplete Keyword List (51 Total)
Access Modifiers (4)
public, private, protected, default (no keyword)
Modifiers (7)
static, final, abstract, synchronized, volatile, transient, native
Control Flow (11)
if, else, switch, case, default, for, while, do, break, continue, return
Exception Handling (6)
try, catch, finally, throw, throws, assert
Primitive Types (8)
byte, short, int, long, float, double, char, boolean
Object-Oriented (7)
class, interface, extends, implements, new, this, super
Package (2)
package, import
Special (4)
void, instanceof, null, enum
Reserved (2)
goto, const
Common Mistakes
Mistake 1: Using Keywords as Identifiers
// ❌ WRONG
int class = 5;
String return = "value";
void private() { }
// ✅ CORRECT
int studentClass = 5;
String returnValue = "value";
void makePrivate() { }Mistake 2: Case Errors
// ❌ WRONG
Public class MyClass { } // 'Public' is not a keyword
STATIC int count; // 'STATIC' is not a keyword
// ✅ CORRECT
public class MyClass { } // Lowercase
static int count; // LowercaseMistake 3: Confusing final, finally, finalize
// final - constant/non-overridable
final int MAX = 100;
// finally - always executes in try-catch
try {
// code
} finally {
// always runs
}
// finalize() - garbage collection (deprecated)
@Override
protected void finalize() {
// Called before object is garbage collected
}Mistake 4: Misusing static
public class Example {
int instanceVar = 10;
static int staticVar = 20;
// ❌ WRONG - Cannot access instance variable from static method
public static void staticMethod() {
// System.out.println(instanceVar); // Error
System.out.println(staticVar); // ✅ OK
}
// ✅ CORRECT - Instance method can access both
public void instanceMethod() {
System.out.println(instanceVar); // ✅ OK
System.out.println(staticVar); // ✅ OK
}
}Mistake 5: Breaking Without Label
// ❌ WRONG - Trying to break outer loop
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (j == 2) {
break; // Only breaks inner loop
}
}
}
// ✅ CORRECT - Using labeled break
outer:
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (j == 2) {
break outer; // Breaks outer loop
}
}
}Keywords by Frequency of Use
Very Common (Learn First)
public, private, static, void, class, new, if, else, for, while, return, int, String, this, null
Common
protected, final, abstract, try, catch, throw, throws, switch, case, break, continue, extends, implements, super, import, package
Less Common
synchronized, volatile, transient, native, instanceof, enum, assert, default, interface, do, byte, short, long, float, double, char, boolean
Rare
goto (reserved), const (reserved)
Interview Tips
Interview Questions About Keywords:
Q: What's the difference between final, finally, and finalize?
- ›
final: Makes variable constant, method non-overridable, class non-extendable - ›
finally: Block that always executes in try-catch - ›
finalize(): Method called before garbage collection (deprecated)
Q: When to use static?
- ›Utility methods that don't need object state
- ›Constants shared across all instances
- ›Factory methods
- ›Main method
Q: What's the difference between abstract class and interface?
- ›Abstract class: Can have both abstract and concrete methods, constructors, fields
- ›Interface: Only abstract methods (before Java 8), no constructors, only constants
Q: What's transient used for?
- ›Mark fields that shouldn't be serialized
- ›Example: Passwords, temporary data
Q: Can you use goto in Java?
- ›No, it's reserved but not implemented
- ›Use labeled break/continue instead
Key Takeaways
Java Keywords Summary:
Total Keywords: 51 reserved words
Categories:
- ›Access modifiers: Control visibility
- ›Class modifiers: Define behavior (static, final, abstract)
- ›Control flow: Direct program execution
- ›Exception handling: Manage errors
- ›Primitive types: Basic data types
- ›OOP: Classes, interfaces, inheritance
- ›Package: Organize code
Most Important:
- ›
public,private,protected: Access control - ›
static: Class-level members - ›
final: Constants and immutability - ›
abstract: Incomplete classes/methods - ›
class,interface: Define types - ›
extends,implements: Inheritance - ›
this,super: Object references - ›
new: Create objects - ›
if,for,while: Control flow - ›
try,catch: Exception handling
Remember:
- ›Keywords are case-sensitive (lowercase only)
- ›Cannot be used as identifiers
- ›
gotoandconstare reserved but unused - ›8 primitive types, 6 exception keywords, 11 control flow
Common Mistakes to Avoid:
- ›Using keywords as variable names
- ›Capitalizing keywords (Public instead of public)
- ›Confusing final/finally/finalize
- ›Accessing instance members from static context
Congratulations! You now know all Java keywords and how to use them correctly!
What to Read Next
Deep dive into Java's primitive and reference types.
Practice Programs
Put this topic into practice — each program has full code, output and a step-by-step explanation you can run online.
Uses this to distinguish a constructor parameter from a field of the same name.
Uses super to call a parent class's constructor and its overridden method.
A final variable assigned once and never reassigned.
Uses a static field to track a count shared across every object of a class.