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