Java Keywords Explained: Reserved Words & Their Usage

What are Java Keywords?

Java keywords are words only used in the Java computer language and have specific meanings. Think of them like traffic signs—they tell the Java compiler exactly what to do. You cannot use these words as names for your variables, methods, or classes because Java has already claimed them for specific purposes.

Complete List of Java Reserved Words

Java has 67 Java keywords (as per Java SE 17).

Access Modifiers

Public – Allows a class, method, or variable to be accessed from anywhere in the program.

Example: If a method is public, it can be called from any other class.

private– restricts access to only within the same class. It is Good for encapsulation — hiding implementation details.

protected– allows access in the same package + child classes, even in different packages.

Class/Method Modifiers

abstract – An abstract modifier is used when a class or method is declared but not fully implemented. Abstract classes can’t be instantiated; abstract methods must be overridden.

static– belongs to the class, not to an object. Static variables share one copy across objects; static methods can be called without creating objects.

final– value/method/class cannot be changed further.

Final variable = constant.
Final method = can’t be overridden.
Final class = can’t be inherited.

synchronized– used to make code thread-safe. At any given moment, only one thread can access the resource.

native– declares a method implemented in another language (like C/C++). It is used in Java Native Interface (JNI).

strictfp – The strictfp keyword ensures that floating-point calculations remain consistent across all machines and platforms.

Data Types

boolean– true/false values.

byte– 8-bit integer (-128 to 127). This format is beneficial for optimizing memory usage.

char—A char represents a single Unicode character, consisting of two bytes.

short– 16-bit integer, smaller range than int.

int– common 32-bit integer.

long– 64-bit integer (huge numbers).

float– 32-bit decimal numbers (single precision).

double– 64-bit decimal numbers (double precision, more accurate).

void– return type of a method when it does not return anything.

Control Flow

if– executes a block when a condition is true.

else– runs when “if” condition is false.

switch– used to choose from multiple possible options.

case– branch inside switch.

default– fallback option in switch.

for– loop with initialization, condition, increment parts.

while– loop that runs while a condition is true.

do– do-while loop (executes at least once before checking condition).

break– immediately exit from loop/switch.

continue– skip the current loop iteration and move to next.

return– exit a method and send a value back.

Object-Oriented

class– defines a blueprint/template for objects.

interface– collection of methods to be implemented by class (defines a contract).

extends– used when a class inherits another class.

implements– used when a class uses an interface.

new– creates new objects in memory.

this– keyword to point to the current object itself.

super– refers to parent class (used to access parent methods/constructors).

instanceof– checks whether an object belongs to a specific class.

Exception Handling

try– block of code where risky code is written (may throw exception).

catch– block to handle exceptions from try.

finally– block that always executes after try/catch (for cleanup).

throw– used to explicitly throw an exception.

throws– used in the method signature to declare what exceptions might be thrown.

Package/Import

package– groups related classes/interfaces into a namespace (like folders).

import– brings classes from other packages for use

Concurrency

synchronized– (already explained earlier) ensures thread safety.

volatile– tells JVM a variable’s value will change across threads, so always read latest value from memory.

transient– prevents a variable from being serialized (not saved during object serialization).

Unused (reserved for future use)

goto– reserved but not used in Java (to discourage spaghetti code).

const– reserved but not used in Java (instead, we use final).

Others

assert  assert keyword is used for debugging by checking conditions, primarily during testing.

enum– defines a set of named constants (e.g., DAYS {MONDAY, TUESDAY…}).

Rules for Using Java Keywords

Never use keywords as identifiers – You can’t name a variable int or class
Keywords are case-sensitive – Public is different from public (only lowercase public is the keyword)
Keywords cannot be modified – Their meanings are fixed by Java
Use keywords exactly as specified – No variations allowed

Important Java Keywords Explained

static:

It belongs to the class, not to any specific object.

java
class Counter {
	static int count = 0;  // Shared by all objects
	static void printCount() {  // Can be called without creating object
    	System.out.println(count);
	}
}

In Java, the keyword “static” means that a variable or method belongs to the class rather than any object created from it. In the above example, the Counter class has a static variable count and a static method printCount().

The variable count is shared by all instances of the class, meaning every object of Counter accesses the same count value rather than each having its separate copy. This is useful when you want to keep track of something familiar across all objects, such as counting how many have been created.

The static method printCount() can be called directly using the class name without creating an instance of Counter. This method prints the current value of the shared count variable. Because the variable and method are static, they exist at the class level.

final:

Cannot be changed once set

java
class Person {
	String name;
	void setName(String name) {
    	this.name = name;  // this.name refers to instance variable
	}
}

In this Java example, the Person class has an instance variable name that stores the name of a person. The method setName takes a parameter called name and assigns it to the instance variable.

The keyword this is used to distinguish between the instance variable name and the method parameter name, which have the same name. When you write this.name = name;, the this.name refers to the instance variable belonging to the current object, while the plain name refers to the method parameter passed in.

super:

Refers to the parent class

java
class Animal {
	void sound() { System.out.println("Some sound"); }
}
class Dog extends Animal {
	void sound() {
    	super.sound();  // Calls parent's sound method
    	System.out.println("Woof!");
	}
}

In this example, the Animal class has a method sound() that prints a generic message, “Some sound”. The Dog class extends Animal, meaning it inherits the properties and methods of Animal.

Inside the Dog class, the sound() method is overridden to provide a more specific behavior. Within this overridden method, the keyword super is used to call the sound() method of the parent Animal class first, printing “Some sound.” Then, it prints “Woof!” to represent the dog’s specific sound.

Exception Handling Java Keywords

try-catch-finally:

Handle errors gracefully

java
try {
	int result = 10 / 0;  // Might cause error
} catch (ArithmeticException e) {
	System.out.println("Cannot divide by zero!");
} finally {
	System.out.println("This always runs");
}

In this Java code, the try block contains a statement that attempts to divide the number 10 by zero, which will cause an arithmetic error called ArithmeticException. When this exception occurs, the program jumps to the catch block, which catches the specific ArithmeticException and executes the code inside it, printing the message “Cannot divide by zero!” to inform the user about the error.

Regardless of whether an exception occurred or not, the finally block always executes. In this case, it prints “This always runs.” The finally block is typically used for cleanup actions or code that must run regardless of what happens within the try-catch blocks, ensuring important tasks are completed even in error situations.

throws:

Declares that a method might throw an exception

java
void readFile() throws IOException {
	// Method that might throw IOException
}

In this Java example, the method readFile() is declared with the keyword throws IOException, which means that the method might generate an IOException during its execution. This declaration informs anyone who calls readFile() that they need to be prepared to handle this checked exception, either by catching it with a try-catch block or by declaring it further up the call chain with their throws clause.

The IOException typically occurs when there is a problem with input/output operations, such as reading a file that does not exist or experiencing a failure in accessing the file system.

Using throws allows the method to delegate exception handling responsibility to its caller, promoting safer and more robust error handling in Java programs.

Concurrency Keywords

synchronized:

Only one thread can access at a time

java
synchronized void withdraw(int amount) {
	// Only one thread can execute this method at a time
}

In this Java example, the method withdrawal (int amount) is marked with the keyword synchronized, which means that only one thread can execute this method at a time on the same object.

Java guarantees that all subsequent threads attempting to execute the withdraw method on the same object must wait until the first thread completes its execution by synchronizing it.

volatile:

Variable value is always read from main memory

java
volatile boolean flag = true;  // Value always fresh from memory

When a variable is declared as volatile, it ensures that every read of that variable is done directly from the main memory and not from a thread’s local cache. This guarantees that all threads see the most up-to-date value of the variable immediately after any change is made.

transient:

Skip this field during serialization

java
class User {
	String name;
	transient String password;  // Won't be saved when object is serialized
}

In this Java example, the User class contains two instance variables: name and password. The keyword “transient” next to the password variable signifies that it won’t be included in the serialization process.

Serialization is the process of turning an item into a stream of bytes so that it may be saved to a file or sent over a network. By marking the password as temporary, Java makes sure that this private information won’t be saved or sent when the User object is serialized.

This technique is commonly used to protect confidential data, such as passwords or security tokens, from being inadvertently exposed or stored in an insecure way, while other non-sensitive fields like name are still serialized normally.

Scroll to Top
Verified by MonsterInsights