Skip to content

Java Keywords

Keywords Overview

Java has 53 keywords (including reserved words), which can be categorized as follows:

  • Access Control Keywords: Control access to classes, methods, and variables
  • Class, Method, and Variable Modifiers: Define characteristics of classes, methods, and variables
  • Program Control Statements: Control program execution flow
  • Error Handling: Handle exceptions and errors
  • Package Related: Manage packages and imports
  • Primitive Data Types: Define primitive data types
  • Variable References: Handle variable references and instances
  • Reserved Words: Keywords reserved for future use

Java has a set of keywords that are reserved words and cannot be used as variable, method, class, or any other identifier names:

KeywordDescription
abstractNon-access modifier. Used for classes and methods: An abstract class cannot be used to create objects (to access it, it must be inherited from another class). An abstract method can only be used in an abstract class and does not have a body. The body is provided by the subclass (inherited from)
assertFor debugging
booleanA data type that can only store true or false values
breakBreaks out of a loop or switch block
byteA data type that can store integers from -128 to 127
caseMarks a block of code in switch statements
catchCatches exceptions generated by try statements
charA data type used to store a single character
classDefines a class
continueContinues to the next iteration of a loop
constDefines a constant. Not used - use final instead
defaultSpecifies the default block of code in a switch statement
doUsed together with while to create a do-while loop
doubleA data type that can store decimals from 1.7e−308 to 1.7e+308
elseUsed in conditional statements
enumDeclares an enumerated (unchangeable) type
exportsExports a package with a module. Added in Java 9
extendsExtends a class (indicates that a class inherits from another class)
finalNon-access modifier used for classes, attributes and methods, making them unchangeable (cannot be inherited or overridden)
finallyUsed with exceptions, a block of code that will be executed regardless of whether an exception is thrown
floatA data type that can store decimals from 3.4e−038 to 3.4e+038
forCreates a for loop
gotoNot in use, has no function
ifCreates a conditional statement
implementsImplements an interface
importUsed to import a package, class or interface
instanceofChecks whether an object is an instance of a specific class or interface
intA data type that can store integers from -2147483648 to 2147483647
interfaceUsed to declare a special type of class that only contains abstract methods
longA data type that can store integers from -9223372036854775808 to 9223372036854775808
moduleDeclares a module. Added in Java 9
nativeSpecifies that a method is not implemented in the same Java source file (but in another language)
newCreates new objects
packageDeclares a package
privateAn access modifier used for attributes, methods and constructors, making them only accessible within the declared class
protectedAn access modifier used for attributes, methods and constructors, making them accessible in the same package and subclasses
publicAn access modifier used for classes, attributes, methods and constructors, making them accessible by any other class
requiresSpecifies required libraries inside a module. Added in Java 9
returnFinishes the execution of a method, and can be used to return a value from a method
shortA data type that can store integers from -32768 to 32767
staticA non-access modifier used for methods and attributes. Static methods/attributes can be accessed without creating an object of a class
strictfpObsolete. Restricts the precision and rounding of floating point calculations
superRefers to superclass (parent) objects
switchSelects one of many code blocks to be executed
synchronizedA non-access modifier, which specifies that methods can only be accessed by one thread at a time
thisRefers to the current object in a method or constructor
throwCreates a custom error
throwsIndicates what exceptions may be thrown by a method
transientUsed to ignore an attribute when serializing an object
tryCreates a try...catch statement
varDeclares a variable. Added in Java 10
voidSpecifies that a method should not have a return value
volatileIndicates that an attribute is not cached thread-locally, and is always read from the "main memory"
whileCreates a while loop

Java keywords are predefined reserved words in the Java language with special meanings. These keywords cannot be used as variable names, method names, class names, or any other identifiers. The Java language specification defines these keywords, and they form the foundation of Java syntax.

NOTE

Note: true, false, and null are not keywords, but they are literals and reserved words, and cannot be used as identifiers.

Access Control Keywords

public

Defines public access, can be accessed by any other class.

java
public class MyClass {
    public int publicVariable = 10;
    
    public void publicMethod() {
        System.out.println("This is a public method");
    }
}

private

Defines private access, can only be accessed within the same class.

java
public class MyClass {
    private int privateVariable = 20;
    
    private void privateMethod() {
        System.out.println("This is a private method");
    }
}

protected

Defines protected access, can be accessed by classes in the same package or subclasses.

java
public class Parent {
    protected int protectedVariable = 30;
    
    protected void protectedMethod() {
        System.out.println("This is a protected method");
    }
}

class Child extends Parent {
    public void accessProtected() {
        System.out.println(protectedVariable); // Accessible
        protectedMethod(); // Can be called
    }
}

Class, Method and Variable Modifiers

static

Defines static members that belong to the class rather than instances.

java
public class StaticExample {
    static int staticVariable = 100;
    
    static void staticMethod() {
        System.out.println("Static method, static variable value: " + staticVariable);
    }
    
    public static void main(String[] args) {
        // Access directly through class name
        StaticExample.staticMethod();
        System.out.println(StaticExample.staticVariable);
    }
}

final

Defines final, unchangeable elements.

java
public class FinalExample {
    // final variable (constant)
    final int CONSTANT = 42;
    
    // final method (cannot be overridden)
    final void finalMethod() {
        System.out.println("This method cannot be overridden");
    }
}

// final class (cannot be inherited)
final class FinalClass {
    // Class content
}

abstract

Defines abstract classes or abstract methods.

java
abstract class AbstractClass {
    // Abstract method (no implementation)
    abstract void abstractMethod();
    
    // Concrete method
    void concreteMethod() {
        System.out.println("Concrete method implementation");
    }
}

class ConcreteClass extends AbstractClass {
    @Override
    void abstractMethod() {
        System.out.println("Implementing abstract method");
    }
}

synchronized

Used for multi-thread synchronization.

java
public class SynchronizedExample {
    private int count = 0;
    
    // Synchronized method
    synchronized void increment() {
        count++;
    }
    
    void anotherMethod() {
        // Synchronized block
        synchronized(this) {
            count--;
        }
    }
}

volatile

Ensures variable visibility, prevents compiler optimization.

java
public class VolatileExample {
    private volatile boolean flag = false;
    
    public void setFlag() {
        flag = true; // Immediately visible to all threads
    }
    
    public boolean getFlag() {
        return flag;
    }
}

Program Control Statements

Conditional Statements

if, else

Conditional judgment statements.

java
int score = 85;

if (score >= 90) {
    System.out.println("Excellent");
} else if (score >= 80) {
    System.out.println("Good");
} else if (score >= 60) {
    System.out.println("Pass");
} else {
    System.out.println("Fail");
}

switch, case, default

Multi-branch selection statement.

java
int dayOfWeek = 3;

switch (dayOfWeek) {
    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");
        break;
}

Loop Statements

for

For loop statement.

java
// Traditional for loop
for (int i = 0; i < 5; i++) {
    System.out.println("i = " + i);
}

// Enhanced for loop (for-each)
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
    System.out.println("Number: " + num);
}

while

While loop statement.

java
int i = 0;
while (i < 5) {
    System.out.println("while loop: " + i);
    i++;
}

do

Do-while loop statement.

java
int j = 0;
do {
    System.out.println("do-while loop: " + j);
    j++;
} while (j < 3);

Jump Statements

break

Breaks out of a loop or switch statement.

java
for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break; // Exit loop
    }
    System.out.println(i);
}

continue

Skips the current loop iteration.

java
for (int i = 0; i < 5; i++) {
    if (i == 2) {
        continue; // Skip current iteration
    }
    System.out.println(i);
}

return

Returns from a method.

java
public int calculateSum(int a, int b) {
    if (a < 0 || b < 0) {
        return -1; // Early return
    }
    return a + b; // Normal return
}

Error Handling Keywords

try, catch, finally

Exception handling mechanism.

java
public class ExceptionExample {
    public void divideNumbers(int a, int b) {
        try {
            int result = a / b;
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Division by zero error: " + e.getMessage());
        } finally {
            System.out.println("This executes regardless of exception");
        }
    }
}

throw

Throws an exception.

java
public void validateAge(int age) {
    if (age < 0) {
        throw new IllegalArgumentException("Age cannot be negative");
    }
    System.out.println("Age validation passed: " + age);
}

throws

Declares exceptions that a method may throw.

java
public void readFile(String filename) throws IOException {
    FileReader file = new FileReader(filename);
    // File reading operations
}

package

Declares a package.

java
package com.example.myproject;

public class MyClass {
    // Class content
}

import

Imports classes from other packages.

java
import java.util.ArrayList;
import java.util.List;
import java.io.*; // Import entire package

public class ImportExample {
    public void useImportedClasses() {
        List<String> list = new ArrayList<>();
        // Use imported classes
    }
}

Primitive Data Type Keywords

Java defines 8 primitive data types:

Integer Types

java
byte byteValue = 127;        // 8-bit, range: -128 to 127
short shortValue = 32767;    // 16-bit, range: -32,768 to 32,767
int intValue = 2147483647;   // 32-bit, range: -2^31 to 2^31-1
long longValue = 9223372036854775807L; // 64-bit, range: -2^63 to 2^63-1

Floating-Point Types

java
float floatValue = 3.14f;    // 32-bit single precision floating point
double doubleValue = 3.14159265359; // 64-bit double precision floating point

Character and Boolean Types

java
char charValue = 'A';        // 16-bit Unicode character
boolean booleanValue = true; // Boolean value: true or false

Variable Reference Keywords

this

Refers to the current object.

java
public class ThisExample {
    private int value;
    
    public void setValue(int value) {
        this.value = value; // Distinguish parameter from member variable
    }
    
    public ThisExample getThis() {
        return this; // Return current object
    }
}

super

Refers to the parent class.

java
class Parent {
    protected String name = "Parent";
    
    public void display() {
        System.out.println("Parent method");
    }
}

class Child extends Parent {
    private String name = "Child";
    
    public void display() {
        super.display(); // Call parent method
        System.out.println("Current class name: " + this.name);
        System.out.println("Parent class name: " + super.name);
    }
}

null

Represents a null reference.

java
String str = null; // Null reference
if (str == null) {
    System.out.println("String is null");
}

new

Creates new objects.

java
// Create objects
ArrayList<String> list = new ArrayList<>();
String str = new String("Hello");

// Create arrays
int[] numbers = new int[10];

instanceof

Checks object type.

java
Object obj = "Hello World";

if (obj instanceof String) {
    String str = (String) obj;
    System.out.println("This is a string: " + str);
}

class

Gets the Class object of a class.

java
Class<?> stringClass = String.class;
System.out.println("Class name: " + stringClass.getName());

// Can also get through object
String str = "Hello";
Class<?> objClass = str.getClass();

Other Important Keywords

void

Indicates that a method returns no value.

java
public void printMessage() {
    System.out.println("This method returns no value");
}

interface

Defines an interface.

java
interface Drawable {
    void draw(); // Interface method (default is public abstract)
    
    default void defaultMethod() {
        System.out.println("Default method");
    }
}

class Circle implements Drawable {
    @Override
    public void draw() {
        System.out.println("Drawing a circle");
    }
}

implements

Implements an interface.

java
class Rectangle implements Drawable {
    @Override
    public void draw() {
        System.out.println("Drawing a rectangle");
    }
}

extends

Inherits from a class.

java
class Animal {
    public void eat() {
        System.out.println("Animal is eating");
    }
}

class Dog extends Animal {
    public void bark() {
        System.out.println("Dog is barking");
    }
}

Reserved Words

The following are Java reserved keywords that are not currently in use, but reserved for future versions:

  • const: Constant declaration (not used, use final instead)
  • goto: Jump statement (not used, Java does not support goto)

Strict Floating Point Keyword

strictfp

Ensures portability of floating point calculations.

java
strictfp class StrictMath {
    public double calculate(double a, double b) {
        return a * b; // Calculated strictly according to IEEE 754 standard
    }
}

Assertion Keyword

assert

Used for assertion checking during debugging.

java
public void validateInput(int value) {
    assert value > 0 : "Value must be greater than 0";
    System.out.println("Input value: " + value);
}

Enumeration Keyword

enum

Defines an enumeration type.

java
enum Color {
    RED, GREEN, BLUE;
    
    public void printColor() {
        System.out.println("Color: " + this.name());
    }
}

public class EnumExample {
    public static void main(String[] args) {
        Color color = Color.RED;
        color.printColor();
    }
}

Keyword Usage Notes

  1. Case Sensitive: Java keywords are all lowercase. Public is not a keyword, but public is.

  2. Cannot Be Used As Identifiers: Keywords cannot be used as variable names, method names, class names, etc.

java
// Wrong examples
int class = 10;    // Error: class is a keyword
void if() {}       // Error: if is a keyword

// Correct examples
int className = 10;  // Correct
void ifCondition() {} // Correct
  1. Context Sensitive: Some words are only keywords in specific contexts, such as var (Java 10+).

  2. Version Differences: Different Java versions may introduce new keywords, such as:

    • Java 1.2: strictfp
    • Java 1.4: assert
    • Java 5: enum
    • Java 10: var (contextual keyword)

Best Practices

  1. Memorize Common Keywords: Focus on mastering commonly used keywords for access control, program control, and exception handling.

  2. Understand Keyword Meanings: Not only know the syntax, but also understand the purpose and use cases of each keyword.

  3. Avoid Naming Conflicts: Avoid using keywords or names similar to keywords when choosing variable names.

  4. Use Modifiers Appropriately: Choose appropriate access modifiers and other modifiers based on actual needs.

  5. Exception Handling: Properly use try-catch-finally and throws keywords to handle exceptions.

By mastering these Java keywords, you will be able to better understand and write Java code, building well-structured and fully functional Java applications.

Content is for learning and research only.