Java Keywords

In Java, keywords are reserved words that have a predefined meaning in the language. These words form the core building blocks of Java’s syntax and cannot be used as identifiers (such as variable names, class names, or method names).

✔️ Example :
int age;

In this statement, int is a keyword that tells the compiler the variable age is of integer type (32-bit signed two’s complement integer). We cannot use int as a variable name, class name, or method name. Attempting to do so results in a compilation error.

What are Keywords in Java?

A keyword is a word that is reserved by Java because it has a special function in the language. Java has a total of 53 keywords (as of Java SE 17), and they cannot be redefined by the user.

Why Are Keywords Important?

  • Keywords define the structure and behavior of a Java program.
  • They instruct the compiler to perform specific actions.
  • Prevent the use of meaningful reserved words for other purposes, ensuring consistency.

Classification of Java Keywords

Let’s classify some of the most important Java keywords by their functionality:

1️⃣ Access Modifiers

In Java, Access Modifiers are keywords used to control the visibility and accessibility of classes, methods, and variables. They define which parts of your program can access a particular class member (variable, method, or constructor).

  • public, private, protected
✔️Example:
public class MyClass {
    private int data;  // Private variable

    public void display() {  // Public method
        System.out.println(data);
    }
}

2️⃣ Class, Interface, Inheritance Related

  • class, interface, extends, implements

Example:

public interface Animal {
    void sound();
}

public class Dog implements Animal {
    public void sound() {
        System.out.println("Bark");
    }
}

public class AnimalTester {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.sound();
    }
}

3️⃣ Data Type Keywords

  • int, boolean, char, double, float, long, short, byte

Example:

public class DataTypes {
    public static void main(String[] args) {
        int number = 100;
        double price = 99.99;
        boolean isAvailable = true;
        char grade = 'A';

        System.out.println("Number: " + number);
        System.out.println("Price: " + price);
        System.out.println("Available: " + isAvailable);
        System.out.println("Grade: " + grade);
    }
}

4️⃣ Control Flow Keywords

  • if, else, switch, case, default, for, while, do, break, continue, return

Example:

public class ControlFlowExample {
    public static void main(String[] args) {
        int number = 5;

        if (number > 0) {
            System.out.println("Positive Number");
        } else {
            System.out.println("Non-positive Number");
        }

        for (int i = 0; i < 3; i++) {
            System.out.println("Loop iteration: " + i);
        }
    }
}

5️⃣ Exception Handling Keywords

  • try, catch, finally, throw, throws

Example:

public class ExceptionExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero");
        } finally {
            System.out.println("Execution completed");
        }
    }
}

6️⃣ Object Creation and Memory Management

  • new, this, super

Example:

class Parent {
    Parent() {
        System.out.println("Parent constructor");
    }
}

class Child extends Parent {
    Child() {
        super();  // Calls Parent constructor
        System.out.println("Child constructor");
    }
}

public class ObjectCreation {
    public static void main(String[] args) {
        Child child = new Child();
    }
}

7️⃣ Concurrency Keywords

  • synchronized, volatile

Example:

class Counter {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public int getCount() {
        return count;
    }
}

8️⃣ Miscellaneous

  • static, final, abstract, const, native, strictfp, transient

Example of final and static:

public class ConstantsExample {
    public static final double PI = 3.14159;

    public static void main(String[] args) {
        System.out.println("Value of PI: " + PI);
    }
}

🚨 Keywords You Should Never Use as Identifiers

int class = 10;   // ❌ Invalid — 'class' is a reserved keyword

Complete List of Java Keywords (for Reference)

There are 51 standard keywords in Java that cannot be used as identifiers.

KeywordDescription
abstractUsed with classes/methods. An abstract class cannot be instantiated directly. An abstract method must be implemented by a child class.
assertEnables testing of assumptions in the program.
booleanRepresents true or false values.
breakTerminates a loop (for, while, do-while) or a switch block.
byteStores integer values from -128 to 127.
caseA block in a switch statement.
catchHandles exceptions after a try block.
charStores a single character.
classDefines a class.
constReserved keyword (use final instead).
continueSkips the current iteration in a loop.
defaultSpecifies the default block in switch, or default methods in interfaces.
doExecutes a block repeatedly while a condition is true.
double64-bit floating-point number.
elseProvides alternative in if-else.
enumDefines a type with a fixed set of constants.
extendsInheritance from a superclass.
finalPrevents reassignment of variables, method overriding, or subclassing.
finallyCode that executes after a try-catch, regardless of outcome.
float32-bit floating-point number.
forLoop that executes a set of statements repeatedly.
gotoReserved but not used.
ifConditional branch.
implementsImplements an interface.
importImports classes, packages, or interfaces.
instanceofChecks object type at runtime.
int32-bit integer.
interfaceDeclares an interface.
long64-bit integer.
nativeDeclares platform-dependent methods.
newCreates new objects.
packageDefines a package for organizing classes.
privateAccess limited to the current class.
protectedAccessible in current package or subclass.
publicAccessible from anywhere.
returnReturns a value from a method.
short16-bit integer.
staticBelongs to the class, not an instance.
strictfpEnforces strict floating-point behavior.
superRefers to parent class object.
switchMultiple execution paths based on a variable.
synchronizedEnsures thread safety.
thisRefers to the current object.
throwExplicitly throws an exception.
throwsDeclares exceptions a method can throw.
transientPrevents serialization of variables.
tryWraps code expected to throw exceptions.
voidMethod returns no value.
volatileVariable is always read from main memory.
whileLoops while condition is true.
_ (Underscore)Since Java 9, used to prevent underscores as unused identifiers.

⚠️ Special Notes

  • The keywords const and goto are reserved but not currently used in Java.
  • The literals true, false, and null are not keywords but literals. Still, they cannot be used as identifiers.
  • Keywords such as strictfp, assert, and enum were added in later JDK versions:
    • strictfp → JDK 1.2
    • assert → JDK 1.4
    • enum → JDK 1.5
  • Newer Java features, such as sealed classes, records, and JPMS (Java Platform Module System), introduced contextual keywords.

▶️Contextual Keywords

These words act as keywords in certain contexts but are valid as identifiers otherwise.

KeywordDescription
exportsUsed for exporting modules.
moduleDeclares a module.
non-sealedUsed with sealed classes.
openDeclares an open module.
opensExports a module for reflection.
permitsDefines allowed subclasses for sealed classes.
providesUsed in module definition to specify service providers.
recordDefines a compact data class.
requiresSpecifies dependencies between modules.
sealedRestricts class extension.
toUsed in module declarations.
transitiveRequires transitive dependencies.
usesSpecifies a service interface for the module system.
varInferred local variable type.
withUsed in module declarations.
yieldReturns a value from a switch expression.

✔️Example of Contextual Keyword record

public record Person(String name, int age) {}

public class RecordExample {
    public static void main(String[] args) {
        Person person = new Person("Alice", 30);
        System.out.println(person.name() + " - " + person.age());
    }
}

🎯 Summary

Java keywords are the backbone of the language’s syntax. Understanding them is essential for writing clean, efficient, and error-free code. By mastering how and where to use them, developers can write maintainable and optimized Java applications.

Java developer with 9+ years of IT experience, sharing tutorials and tips to help learners master Java programming.

Leave a Reply

Your email address will not be published. Required fields are marked *