Java Keywords

Java keywords are reserved words. You use them to build Java programs. Each keyword has a special meaning to the Java compiler. This helps you write clear and functional code.

What are Java Keywords?

A Java keyword is a reserved identifier. The Java programming language uses it for a specific purpose. You cannot use keywords as variable names, method names, or any other identifiers. They are the fundamental elements of Java syntax.

Java keywords provide the structure and logic for your code. They help you define data types, create classes, control program execution, and handle errors. Knowing them helps you write correct and efficient Java programs.

For example, using public allows access to elements from any other class. Using private restricts access to only within the declaring class. This level of control is crucial for managing your code’s security and maintainability.

Learn Java from scratch with this comprehensive Java course, covering everything from fundamentals like variables and control structures to advanced object-oriented programming concepts such as classes, inheritance, and polymorphism.

Categories of Java Keywords

Java keywords fall into several categories. Understanding these helps you see their roles in programming.

  • Access Modifiers: Control the visibility of classes, methods, and variables. This impacts who can use or see parts of your code.
  • Data Types: Define the kind of information a variable can hold. This determines how much memory is used and what operations are valid.
  • Control Flow: Manage the order in which your program’s statements run. This creates the logic and decision-making capabilities.
  • Class, Method, and Variable Modifiers: Alter how classes, methods, and variables behave. This includes making them static, constant, or abstract.
  • Exception Handling: Manage errors and unexpected events that happen while your program is running. This prevents crashes and allows for graceful recovery.
  • Object-Oriented Programming (OOP): Support features like inheritance, polymorphism, and encapsulation. These are core concepts for building complex, modular software.
  • Literals: Represent fixed, constant values directly in your code.
  • Unused: Reserved by Java but not currently active in the language.

The Complete List of Java Keywords

Here is a full list of Java keywords with detailed explanations.

Access Modifiers

These keywords control the visibility and accessibility of classes, methods, and variables. You use them to enforce encapsulation and define the API of your classes.

  • public: Use this to make a class, method, or variable accessible from any other class, regardless of package. This is suitable for elements intended for broad use.
    Example: public class MyAPI { public String fetchData() { return "data"; } }
  • private: This limits access to within the declaring class only. You use private to hide implementation details and protect the internal state of an object.
    Example: class BankAccount { private double balance; public void deposit(double amount) { this.balance += amount; } }
  • protected: This allows access within the same package and by subclasses (even if they are in different packages). It’s useful when you want to allow limited access for related classes in an inheritance hierarchy.
    Example: class Parent { protected String familyName; } class Child extends Parent { void display() { System.out.println(familyName); } }

Data Types

These keywords define the type of data that variables can store. Choosing the correct data type helps manage memory efficiently and ensures that operations are valid for the stored values.

  • byte: A 8-bit signed integer. It holds whole numbers from -128 to 127. Use byte when memory is a concern and the values are small, like processing raw binary data.
    Example: byte age = 30;
  • short: A 16-bit signed integer. It holds whole numbers from -32,768 to 32,767. It’s useful for small integer values where int might be overkill for memory.
    Example: short year = 2025;
  • int: A 32-bit signed integer. This is the default integer data type in Java and is commonly used for general-purpose whole numbers.
    Example: int customerId = 123456;
  • long: A 64-bit signed integer. Use long for very large whole numbers that exceed the capacity of int, such as timestamps or population counts. Remember to append L or l to the literal.
    Example: long galaxyStars = 100_000_000_000L;
  • float: A single-precision 32-bit floating-point number. Use float for decimal numbers when memory is a primary concern or precision requirements are moderate. Append f or F.
    Example: float temperature = 23.5f;
  • double: A double-precision 64-bit floating-point number. This is the default floating-point data type. Use double for general-purpose decimal numbers where higher precision is needed.
    Example: double precisePi = 3.1415926535;
  • boolean: Represents a logical value: true or false. It’s used for conditional logic and flags.
    Example: boolean isCompleted = false;
  • char: A single 16-bit Unicode character. It stores individual characters like letters, numbers, or symbols. Enclose characters in single quotes.
    Example: char grade = 'A';

Control Flow

These keywords manage the order of execution of statements in a program. They allow your program to make decisions, repeat actions, and handle different scenarios.

  • if: Executes a block of code only if a specified condition is true. It’s the most basic decision-making construct.
    Example: if (age >= 18) { System.out.println("Eligible to vote"); }
  • else: Executes a block of code if the preceding if condition (and any else if conditions) is false. It provides an alternative path when the primary condition is not met.
    Example: else { System.out.println("Not eligible to vote"); }
  • switch: Provides a more efficient way to handle multiple decision paths based on the value of a single variable (or expression). It’s cleaner than a long chain of if-else if statements.
    Example: switch (month) { case 1: System.out.println("January"); break; case 2: System.out.println("February"); break; }
  • case: Defines a specific value to match within a switch statement. When the switch expression matches a case value, the code under that case executes.
    Example: (See switch example above)
  • default: The fallback block in a switch statement. Its code runs if none of the case values match the switch expression. It is optional.
    Example: switch (choice) { case 'A': System.out.println("Option A"); break; default: System.out.println("Invalid option"); }
  • while: Creates a loop that continues to execute its code block as long as a specified condition remains true. The condition is checked before each iteration.
    Example: int count = 0; while (count < 5) { System.out.println(count); count++; }
  • do: Creates a loop that executes its code block at least once, and then continues to loop as long as a specified condition remains true. The condition is checked after each iteration.
    Example: int num = 10; do { System.out.println(num); num--; } while (num > 5);
  • for: Provides a concise way to create loops with initialization, a termination condition, and an iteration step all in one line. It’s often used when you know how many times you want to loop.
    Example: for (int i = 0; i < 10; i++) { System.out.println("Iteration " + i); }
  • break: Immediately exits the innermost loop or switch statement. It stops the current control flow and moves execution to the statement immediately following the loop/switch.
    Example: for (int i = 0; i < 10; i++) { if (i == 5) break; System.out.println(i); } (Prints 0, 1, 2, 3, 4)
  • continue: Skips the current iteration of a loop and immediately proceeds to the next iteration. It does not exit the loop entirely.
    Example: for (int i = 0; i < 5; i++) { if (i == 2) continue; System.out.println(i); } (Prints 0, 1, 3, 4)
  • return: Exits the current method and, if the method has a non-void return type, sends a value back to the caller.
    Example: public int add(int a, int b) { return a + b; }

Class, Method, and Variable Modifiers

These keywords alter the fundamental behavior and characteristics of classes, methods, and variables.

  • class: The fundamental keyword for declaring a new class. A class acts as a blueprint or template for creating objects, defining their properties (fields) and behaviors (methods).
    Example: class Car { String model; int year; }
  • extends: Used in a class declaration to indicate that a class inherits from another class. This means the new class (subclass) gains the fields and methods of the existing class (superclass).
    Example: class SportsCar extends Car { boolean hasTurbo; }
  • implements: Used in a class declaration to indicate that a class provides the concrete implementation for an interface. A class can implement multiple interfaces.
    Example: class MyRobot implements Movable, Attackable { /* methods defined in interfaces */ }
  • static: Declares a static member (field, method, or nested class). Static members belong to the class itself, not to individual objects. You access them using the class name, not an object instance.
    Example: public class MathOperations { public static final double PI = 3.14159; public static int sum(int a, int b) { return a + b; } }
  • final: Makes an entity unchangeable. For variables, their value can only be assigned once. For methods, they cannot be overridden by subclasses. For classes, they cannot be extended (inherited from).
    Example: final int MAX_ATTEMPTS = 3; public final void printDetails() { /* ... */ } public final class ImmutableClass { /* ... */ }
  • abstract: Declares an abstract class or method. An abstract class cannot be instantiated directly and often contains abstract methods, which have no implementation and must be overridden by concrete subclasses.
    Example: public abstract class Animal { public abstract void makeSound(); 
  • native: Used to declare a method whose implementation is provided by platform-dependent native code (e.g., C or C++). This is used when Java cannot directly perform an operation or for performance-critical tasks.
    Example: public native void processImage(byte[] imageData);
  • synchronized: Primarily used for multithreading. It creates a critical section of code that only one thread can execute at a time, preventing data corruption from concurrent access (race conditions).
    Example: public synchronized void incrementCounter() { counter++; }
  • transient: Marks a field to be excluded when an object is serialized. This is useful for sensitive data (like passwords) or data that can be recomputed.
    Example: private transient String sessionToken;
  • volatile: Used for multithreading. It ensures that a variable’s value is always read from and written to main memory, not from a thread’s local cache. This guarantees visibility of changes across threads.
    Example: private volatile boolean shutdownFlag;
  • strictfp: Ensures that floating-point computations within a method or class strictly adhere to the IEEE 754 standard for floating-point arithmetic. This provides consistent results across different Java Virtual Machines (JVMs) but can sometimes reduce performance.
    Example: public strictfp double calculatePreciseValue() { /* ... */ }

Exception Handling

These keywords help manage errors and exceptional conditions that might occur during your program’s execution, allowing for robust and fault-tolerant applications.

  • try: Encloses a block of code that might throw an exception. This is the first part of an exception-handling construct.
    Example: try { int result = 10 / 0; }
  • catch: Handles a specific type of exception if one occurs in the preceding try block. You can have multiple catch blocks for different exception types.
    Example: catch (ArithmeticException e) { System.out.println("Cannot divide by zero."); }
  • finally: Executes a block of code whether an exception occurred in the try block or not. This is commonly used for cleanup operations like closing files or network connections.
    Example: finally { System.out.println("Resource cleanup completed."); }
  • throw: Explicitly throws an exception from your code. You create an exception object and then throw it to signal an error condition.
    Example: if (amount <= 0) { throw new IllegalArgumentException("Amount must be positive."); }
  • throws: Declared in a method signature to indicate that the method might throw one or more specified checked exceptions. This forces callers of the method to either handle the exception or declare it themselves.
    Example: public void readFile(String filePath) throws IOException { FileReader reader = new FileReader(filePath); /* ... */ }
  • assert: Used for debugging and testing. It checks if a condition is true. If the condition is false, it throws an AssertionError. Assertions can be enabled or disabled at runtime.
    Example: assert age > 0 : "Age must be positive, received: " + age;

Object-Oriented Programming (OOP)

These keywords are fundamental to Java’s object-oriented nature, enabling concepts like encapsulation, inheritance, and polymorphism.

  • new: The keyword used to create a new instance of a class (an object) in memory. It allocates memory for the object and calls its constructor.
    Example: MyClass myObject = new MyClass();
  • this: Refers to the current object within a method or constructor. It can be used to distinguish instance variables from local variables, or to call other constructors of the same class.
    Example: public void setName(String name) { this.name = name; } or public MyClass(int value) { this(value, "default"); }
  • super: Refers to the immediate parent (superclass) of the current object. It’s used to call a superclass constructor, or to access overridden methods or fields of the superclass.
    Example: class Child extends Parent { public Child() { super(); } // Calls parent constructor }
  • instanceof: A binary operator that tests if an object is an instance of a particular class or interface (or a subclass/implementation thereof). It returns true or false.
    Example: if (myShape instanceof Circle) { ((Circle) myShape).getRadius(); }
  • void: Indicates that a method does not return any value. Used when a method performs an action but doesn’t produce a result to be used by the caller.
    Example: public void printMessage() { System.out.println("Hello"); }
  • interface: Declares an interface. An interface is a contract that defines a set of abstract methods (and sometimes default methods or constants) that implementing classes must provide. It supports multiple inheritance of type.
    Example: interface Flyable { void fly(); }
  • enum: Declares an enumerated type. Enums are a special class type that represent a fixed set of named constants. They are useful for defining a collection of related values, like days of the week or states.
    Example: enum TrafficLight { RED, YELLOW, GREEN }

Literals

These keywords represent constant values directly embedded in your code.

  • null: A special literal representing the absence of an object reference. It indicates that a variable does not currently point to any object in memory.
    Example: String userName = null;

Unused Keywords

These keywords are reserved by Java but are not currently in use. You cannot use them as identifiers for variables, methods, or classes.

  • const: Reserved, but not used. Java uses the final keyword for declaring constants instead.
  • goto: Reserved, but not used. Java does not support goto statements, unlike some other languages (like C++), as their use can lead to complex and hard-to-read “spaghetti code.” Java favors structured control flow.

Best Practices for Using Java Keywords

You can follow these practices to write clean, effective Java code.

  • Choose the Right Access Modifier: Do not make everything public. Use private for internal details. Use protected for members intended for subclasses. This enhances encapsulation and reduces coupling.
  • Use final for Immutability: Declare variables final when their values should not change after initialization. This makes your code safer and easier to reason about.
  • Master Control Flow: Understand when to use if-else, switch, for, while, break, and continue. Select the most readable and efficient control flow statement for each scenario.
  • Effective Exception Handling: Use try-catch-finally blocks to gracefully handle errors. Do not just catch generic Exception; catch specific exceptions. Throw custom exceptions when appropriate.
  • Leverage OOP Keywords: Use class, extends, implements, abstract, and interface to design robust object-oriented systems. This promotes code reusability and maintainability.
Avatar photo
Great Learning Editorial Team
The Great Learning Editorial Staff includes a dynamic team of subject matter experts, instructors, and education professionals who combine their deep industry knowledge with innovative teaching methods. Their mission is to provide learners with the skills and insights needed to excel in their careers, whether through upskilling, reskilling, or transitioning into new fields.

Academy Pro Subscription

Grab 50% off
on Top Courses - Free Trial Available

×
Scroll to Top