Keywords in Java
Keywords in Java
Definition:
The abstract keyword is a non-access modifier used to declare:
Abstract class – cannot be instantiated directly.
Abstract method – a method without a body that must be implemented by
subclasses.
Syntax:
Abstract Class:
Abstract Method:
Example:
void info() {
System.out.println("This is a shape");
}
}
Keyword: assert
Definition:
The assert keyword is used for debugging in Java.
It tests an expression and throws an AssertionError if the expression is false.
Assertions are typically used during development/testing, not in production.
Syntax:
Basic Syntax:
assert condition;
Example:
class TestAssert {
public static void main(String[] args) {
int age = 15;
System.out.println("Age is valid");
}
}
How to Run:
Assertions are disabled by default.
To enable them, run with:
Keyword: boolean
Definition:
The boolean keyword is used to declare a variable that can store only two
values: true or false .
It is typically used for conditions, flags, and logical operations.
Syntax:
class TestBoolean {
public static void main(String[] args) {
boolean isJavaFun = true;
boolean isFishTasty = false;
if (isJavaFun) {
System.out.println("Yes, Java is fun!");
}
}
}
Output:
Keyword: break
Definition:
The break keyword is used to terminate a loop or a switch statement
immediately.
When encountered, the control jumps out of the loop or switch block.
Syntax:
Inside Loop:
break;
Inside Switch:
case value:
// statements
break;
class TestBreakLoop {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break; // exit the loop when i is 3
}
System.out.println(i);
}
}
}
Output:
1
2
class TestBreakSwitch {
public static void main(String[] args) {
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Other Day");
}
}
}
Output:
Tuesday
Keyword: byte
Definition:
The byte keyword is used to declare a variable that can store 8-bit signed
integer values.
Its value range is -128 to 127.
It is often used when memory saving is important or when working with raw binary
data.
Syntax:
Example:
class TestByte {
public static void main(String[] args) {
byte num = 100; // valid (within range)
System.out.println(num);
Output:
100
Sum: 30
Keyword: case
Definition:
The case keyword is used inside a switch statement to define a block of code
that runs when the switch expression matches the case value.
Each case ends with a break (optional but recommended).
Syntax:
switch (expression) {
case value1:
// code block
break;
case value2:
// code block
break;
default:
// code block
}
Example:
class TestCase {
public static void main(String[] args) {
int day = 3;
switch (day) {
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");
}
}
}
Output:
Wednesday
Keyword: catch
Definition:
The catch keyword is used to handle exceptions in Java.
It works with try and finally .
When an exception occurs in the try block, the corresponding catch block is
executed.
Syntax:
try {
// code that may throw an exception
} catch (ExceptionType e) {
// handling code
}
Example:
class TestCatch {
public static void main(String[] args) {
try {
int result = 10 / 0; // will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
System.out.println("Program continues...");
}
}
Output:
Error: / by zero
Program continues...
Keyword: char
Definition:
The char keyword is used to declare a variable that stores a single 16-bit
Unicode character.
It can store any letter, digit, or symbol in single quotes ( 'A' , '9' , '#' ).
Syntax:
Example:
class TestChar {
public static void main(String[] args) {
char grade = 'A';
char symbol = '#';
char digit = '7';
Output:
Grade: A
Symbol: #
Digit: 7
Unicode Char: A
Keyword: class
Definition:
The class keyword is used to declare a class in Java.
A class is a blueprint for creating objects, containing fields (variables) and
methods (functions).
Syntax:
class ClassName {
// fields
dataType variableName;
// methods
returnType methodName() {
// code
}
}
Example:
class Car {
String brand; // field
int year; // field
Output:
Toyota - 2023
Keyword: const
Definition:
const is a reserved keyword in Java, but it is not used in the language.
It was reserved for future use to define constants, similar to final .
Instead of const , Java uses the final keyword to declare constants.
Syntax:
There is no valid syntax for const in Java, because it is not implemented.
class TestConst {
public static void main(String[] args) {
final int MAX = 100; // constant
System.out.println("Max value: " + MAX);
}
}
Output:
Keyword: continue
Definition:
The continue keyword is used inside loops to skip the current iteration and move
to the next iteration.
Unlike break (which terminates the loop), continue does not end the loop, it just
skips to the next cycle.
Syntax:
continue;
Example:
class TestContinue {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip when i = 3
}
System.out.println(i);
}
}
}
Output:
1
2
4
5
Keyword: default
Definition:
In a switch statement, default is used to define the block of code that executes
if no case matches.
In interfaces, default is used to define a method with a body (default method)
from Java 8 onward.
Syntax (Switch):
switch (expression) {
case value1:
// code
break;
default:
// code if no case matches
}
interface MyInterface {
default void display() {
System.out.println("Default method in interface");
}
}
class TestDefaultSwitch {
public static void main(String[] args) {
int day = 5;
switch (day) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
default: System.out.println("Other Day");
}
}
}
Output:
Other Day
interface Vehicle {
default void horn() {
System.out.println("Default horn sound");
}
}
Keyword: do
Definition:
The do keyword is used to create a do-while loop.
In a do-while loop, the body is executed at least once, and then the condition is
checked.
Syntax:
do {
// code block
} while (condition);
Example:
class TestDoWhile {
public static void main(String[] args) {
int i = 1;
do {
System.out.println("Value of i: " + i);
i++;
} while (i <= 5);
}
}
Output:
Value of i: 1
Value of i: 2
Value of i: 3
Value of i: 4
Value of i: 5
Keyword: double
Definition:
The double keyword is used to declare a variable that stores 64-bit floating-
point numbers.
It is more precise than float and is the default type for decimal values in Java.
Syntax:
Example:
class TestDouble {
public static void main(String[] args) {
double price = 99.99;
double pi = 3.14159;
Output:
Price: 99.99
Value of Pi: 3.14159
Sum: 103.13159
Keyword: else
Definition:
The else keyword is used with an if statement to define a block of code that
executes when the if condition is false.
Syntax:
if (condition) {
// code if condition is true
} else {
// code if condition is false
}
Example:
class TestElse {
public static void main(String[] args) {
int age = 16;
if (age >= 18) {
System.out.println("Eligible to vote");
} else {
System.out.println("Not eligible to vote");
}
}
}
Output:
Keyword: enum
Definition:
The enum keyword is used to define a set of named constants in Java.
An enum is a special type of class that can have fields, methods, and
constructors.
Enums are type-safe and improve code readability compared to using integer
constants.
Syntax:
enum EnumName {
CONSTANT1, CONSTANT2, CONSTANT3;
}
Example:
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
class TestEnum {
public static void main(String[] args) {
Day today = Day.WEDNESDAY;
switch (today) {
case MONDAY:
System.out.println("Start of the week");
break;
case WEDNESDAY:
System.out.println("Midweek");
break;
default:
System.out.println("Other day");
}
}
}
Output:
Midweek
Keyword: extends
Definition:
The extends keyword is used in Java for class inheritance.
It allows a child class (subclass) to inherit fields and methods from a parent class
(superclass).
It is also used in interfaces, where one interface can extend another.
Syntax:
For Classes:
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
Output:
interface A {
void methodA();
}
interface B extends A {
void methodB();
}
Keyword: false
Definition:
The false keyword is a boolean literal in Java.
It represents the logical value false and can only be assigned to variables of type
boolean .
Syntax:
Example:
class TestFalse {
public static void main(String[] args) {
boolean isJavaHard = false;
if (isJavaHard) {
System.out.println("Java is difficult");
} else {
System.out.println("Java is easy");
}
}
}
Output:
Java is easy
Keyword: final
Definition:
The final keyword is used to restrict changes in Java.
It can be applied to:
1. Variables – Makes the variable a constant (cannot be reassigned).
2. Methods – Prevents the method from being overridden.
3. Classes – Prevents the class from being inherited.
Syntax:
For Variables (Constant):
For Methods:
For Classes:
Examples:
1. Final Variable
class TestFinalVar {
public static void main(String[] args) {
final int MAX = 100;
System.out.println(MAX);
// MAX = 200; // ERROR: cannot assign a value to final variable
}
}
2. Final Method
class Parent {
final void display() {
System.out.println("This method cannot be overridden");
}
}
3. Final Class
class Car extends Vehicle { } // ERROR: Cannot inherit from final class
Keyword: finally
Definition:
The finally block in Java is always executed after a try block, whether an
exception occurs or not.
It is mainly used to close resources like files, database connections, etc.
Syntax:
try {
// code that may throw exception
} catch (ExceptionType e) {
// handling code
} finally {
// code that will always execute
}
Example:
class TestFinally {
public static void main(String[] args) {
try {
int result = 10 / 2;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("This block always executes");
}
}
}
Output:
Result: 5
This block always executes
Keyword: float
Definition:
The float keyword is used to declare a variable that stores 32-bit floating-point
numbers (decimal values).
It is less precise than double and requires the f or F suffix for literal values.
Syntax:
class TestFloat {
public static void main(String[] args) {
float price = 99.99f; // 'f' is required for float literal
float pi = 3.14F;
Output:
Price: 99.99
Pi Value: 3.14
Total: 103.13
Keyword: for
Definition:
The for keyword is used to create a for loop.
It is used when the number of iterations is known in advance.
Java also supports the enhanced for loop (for-each loop) to iterate over arrays or
collections.
Syntax:
Normal For Loop:
class TestFor {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
}
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
class TestForEach {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40};
Output:
10
20
30
40
Keyword: goto
Definition:
The goto keyword is reserved in Java but not implemented.
It was intended for jump statements (like in C/C++), but Java does not support
goto to avoid unstructured code.
Instead, Java uses break with labels or continue with labels for controlled jumps
inside loops.
Syntax:
There is no valid syntax for goto in Java because it is not used.
class TestGotoAlternative {
public static void main(String[] args) {
outer:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
break outer; // exits both loops
}
System.out.println(i + " " + j);
}
}
}
}
Output:
1 1
1 2
1 3
2 1
Keyword: if
Definition:
The if keyword is used to execute a block of code only when a given condition
is true.
It can be combined with else and else if to handle multiple conditions.
Syntax:
if (condition) {
// code if condition is true
}
class TestIf {
public static void main(String[] args) {
int age = 20;
Eligible to vote
Example 2 – if-else:
class TestIfElse {
public static void main(String[] args) {
int marks = 35;
Output:
Fail
class TestIfElseIf {
public static void main(String[] args) {
int marks = 85;
Output:
Grade A
Keyword: implements
Definition:
The implements keyword is used by a class to inherit (implement) an interface in
Java.
A class that uses implements must provide implementations for all abstract
methods of the interface.
A class can implement multiple interfaces (supports multiple inheritance of type).
Syntax:
Example:
interface Animal {
void sound(); // abstract method
}
interface Pet {
void play();
}
Output:
Dog barks
Dog plays with ball
Keyword: import
Definition:
The import keyword is used to import classes or entire packages into a Java
program.
It allows you to use classes from other packages without writing their full
package names.
Syntax:
Example:
Keyword: instanceof
Definition:
The instanceof keyword is used to test whether an object is an instance of a
particular class or subclass, or implements an interface.
It returns a boolean value ( true or false ).
Syntax:
Example:
class Animal {}
class Dog extends Animal {}
Output:
true
true
true
Keyword: int
Definition:
The int keyword is used to declare a variable of integer type in Java.
It is a 32-bit signed integer that can store values from -2,147,483,648 to
2,147,483,647.
Syntax:
Example:
class TestInt {
public static void main(String[] args) {
int age = 20; // variable declaration
int sum = age + 5; // arithmetic operation
System.out.println(sum); // Output: 25
}
}
Keyword: interface
Definition:
The interface keyword is used to define an interface in Java.
An interface is a collection of abstract methods (and static/final variables).
From Java 8, interfaces can also have default and static methods.
Classes use the implements keyword to provide implementation for an interface.
Syntax:
interface InterfaceName {
// constant variables
// abstract methods (no body)
returnType methodName();
}
Example:
interface Animal {
void sound(); // abstract method
}
Output:
Dog barks
Keyword: long
Definition:
The long keyword is used to declare a variable that stores a 64-bit signed
integer.
It can store values in the range -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807.
For literals, use L or l suffix to specify a long value.
Syntax:
Example:
class TestLong {
public static void main(String[] args) {
long population = 1380004385L; // 'L' is required for large values
long distance = 9876543210L;
Population: 1380004385
Distance: 9876543210
Keyword: native
Definition:
The native keyword is used to declare a method that is implemented in native
code (C/C++) using JNI (Java Native Interface).
Such methods have no body in Java; they are linked to external libraries.
Syntax:
Example:
class TestNative {
// Declaration of native method
public native void printMessage();
static {
System.loadLibrary("MyNativeLib"); // Load native library
}
Keyword: null
Definition:
The null keyword is a literal in Java that represents the absence of a value or no
reference.
It can only be assigned to reference types (objects, arrays, strings), not to
primitive types.
Syntax:
Example:
class TestNull {
public static void main(String[] args) {
String name = null; // no reference assigned
System.out.println(name); // Output: null
if (name == null) {
System.out.println("Variable is null");
}
}
}
Output:
null
Variable is null
Key Points:
You cannot call methods on a null reference (will cause NullPointerException ).
null is not equal to 0, and it is not a keyword for primitive types.
Keyword: new
Definition:
The new keyword is used to create new objects, allocate memory for arrays, or
invoke constructors in Java.
It dynamically allocates memory on the heap and returns a reference to the object.
Syntax:
class Car {
void drive() {
System.out.println("Car is running");
}
}
Output:
Car is running
class TestNewArray {
public static void main(String[] args) {
int[] numbers = new int[3]; // memory allocation for array
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
Output:
10
20
30
Keyword: package
Definition:
The package keyword is used to define a group of related classes, interfaces,
and sub-packages.
It is written at the top of a Java file to specify the package name.
Helps in organizing code and avoiding class name conflicts.
Syntax:
package packageName;
Example:
File: mypack/Message.java
package mypack;
File: TestPackage.java
import mypack.Message;
Steps to Run:
javac -d . Message.java
javac TestPackage.java
java TestPackage
Output:
Keyword: private
Definition:
The private keyword is an access modifier that makes a variable, method, or
constructor accessible only within the same class.
It provides the highest level of encapsulation in Java.
Syntax:
Example:
class BankAccount {
private double balance; // private variable
Output:
Balance: 5000.0
Keyword: protected
Definition:
The protected keyword is an access modifier in Java.
A protected member is accessible:
1. Within the same class
2. Within the same package
3. By subclasses (even in different packages)
Syntax:
Example:
class Animal {
protected String name = "Generic Animal";
protected void sound() {
System.out.println("Animal makes a sound");
}
}
Output:
Keyword: public
Definition:
The public keyword is an access modifier that makes a class, method,
constructor, or variable accessible from anywhere in the program.
When something is declared as public , it has the widest scope of visibility.
Syntax:
For Class:
public class ClassName { . }
For Method:
For Variable:
Example:
// File: MyClass.java
public class MyClass {
public int number = 10; // public variable
// File: TestPublic.java
public class TestPublic {
public static void main(String[] args) {
MyClass obj = new MyClass();
System.out.println(obj.number); // Accessing public variable
obj.display(); // Calling public method
}
}
Output:
10
Hello from public method!
Keyword: return
Syntax:
class Calculator {
public int add(int a, int b) {
return a + b; // returns int value
}
}
Output:
Sum: 8
class TestReturnVoid {
public void display(int x) {
if (x < 0) {
System.out.println("Negative value");
return; // exits the method
}
System.out.println("Value: " + x);
}
Output:
Negative value
Value: 10
Keyword: short
Definition:
The short keyword is used to declare a 16-bit signed integer variable.
It is smaller than int and stores values in the range -32,768 to 32,767.
It is generally used when memory saving is important.
Syntax:
Example:
class TestShort {
public static void main(String[] args) {
short num1 = 1000;
short num2 = 2000;
Output:
Sum: 3000
Keyword: static
Definition:
The static keyword is used for members (variables, methods, blocks, or nested
classes) that belong to the class rather than an object.
It allows access without creating an object.
Static members share the same memory for all objects of the class.
Syntax:
class Counter {
static int count = 0; // shared variable
Output:
Count: 2
class TestStaticBlock {
static {
System.out.println("Static block executed before main");
}
Output:
Keyword: strictfp
Definition:
The strictfp keyword is used to ensure consistent floating-point calculations
across all platforms.
When a class or method is declared strictfp , all floating-point operations inside
follow IEEE 754 standards.
Syntax:
Example:
Result: 16.666...
Definition:
The super keyword refers to the immediate parent class of the current object.
It is used to:
1. Access parent class variables (if hidden by child class).
2. Call parent class methods (if overridden).
3. Call parent class constructor (must be the first statement in the constructor).
Syntax:
super.variableName;
super.methodName();
super(); // calls parent class constructor
Example:
class Animal {
String name = "Animal";
Animal() {
System.out.println("Animal constructor");
}
void sound() {
System.out.println("Animal makes sound");
}
}
Dog() {
super(); // calls Animal constructor
System.out.println("Dog constructor");
}
void display() {
System.out.println("Child name: " + name);
System.out.println("Parent name: " + super.name); // access parent
variable
}
void sound() {
super.sound(); // call parent method
System.out.println("Dog barks");
}
}
Output:
Animal constructor
Dog constructor
Child name: Dog
Parent name: Animal
Animal makes sound
Dog barks
Keyword: switch
Definition:
The switch keyword is used to execute one block of code from multiple options
based on the value of an expression.
It is an alternative to multiple if-else statements when comparing the same
variable.
From Java 7, switch also supports String, and from Java 14+, switch expressions
were added.
Syntax:
switch (expression) {
case value1:
// code block
break;
case value2:
// code block
break;
default:
// code block
}
Example:
class TestSwitch {
public static void main(String[] args) {
int day = 3;
switch (day) {
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("Invalid day");
}
}
}
Output:
Wednesday
Keyword: synchronized
Definition:
The synchronized keyword is used to control access to methods or blocks by
multiple threads.
It prevents race conditions by allowing only one thread at a time to execute the
synchronized code.
Syntax:
Synchronized Method:
Synchronized Block:
synchronized (object) {
// code
}
Example:
class Counter {
private int count = 0;
public synchronized void increment() { // synchronized method
count++;
}
t1.start();
t2.start();
t1.join();
t2.join();
Output:
Without synchronized , the output might be less than 2000 due to race conditions.
Keyword: this
Definition:
The this keyword is a reference to the current object in Java.
It is used to:
1. Differentiate instance variables from parameters (when they have the same
name).
2. Call other constructors in the same class ( this() ).
3. Pass the current object as a parameter.
Syntax:
this.variableName;
this.methodName();
this(); // calls another constructor in the same class
class Student {
String name;
Student(String name) {
this.name = name; // 'this' refers to instance variable
}
void display() {
System.out.println("Name: " + this.name);
}
}
Output:
Name: Amit
Example 2 – Calling Another Constructor:
class Demo {
Demo() {
this(10); // calls parameterized constructor
System.out.println("Default constructor");
}
Demo(int x) {
System.out.println("Parameterized constructor: " + x);
}
}
Output:
Parameterized constructor: 10
Default constructor
Keyword: throw
Definition:
The throw keyword is used to explicitly throw an exception in Java.
It transfers control to the nearest appropriate catch block that handles the thrown
exception.
Used to throw both checked and unchecked exceptions.
Syntax:
class TestThrow {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Not eligible to vote");
} else {
System.out.println("Eligible to vote");
}
}
Output:
Keyword: throws
Definition:
The throws keyword is used in a method declaration to specify that the method
may throw one or more exceptions.
It informs the caller of the method that they need to handle or declare the
exceptions.
Used mainly with checked exceptions.
Syntax:
returnType methodName() throws ExceptionType1, ExceptionType2 {
// method code
}
Example:
import java.io.*;
class TestThrows {
static void readFile() throws IOException {
FileReader fr = new FileReader("test.txt");
fr.close();
}
Keyword: transient
Definition:
The transient keyword is used to mark a variable that should not be serialized
when an object is converted into a byte stream (during serialization).
The value of a transient variable is not saved or restored during the serialization
process.
Syntax:
transient dataType variableName;
Example:
import java.io.*;
try {
// Serialize object
FileOutputStream fileOut = new FileOutputStream("user.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(user);
out.close();
fileOut.close();
// Deserialize object
FileInputStream fileIn = new FileInputStream("user.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
User deserializedUser = (User) in.readObject();
in.close();
fileIn.close();
Output:
Username: Amit
Password: null
Keyword: true
Definition:
The true keyword is a boolean literal in Java representing the logical value true.
It can only be assigned to variables of type boolean .
Syntax:
Example:
class TestTrue {
public static void main(String[] args) {
boolean isJavaFun = true;
if (isJavaFun) {
System.out.println("Java is fun!");
} else {
System.out.println("Java is not fun!");
}
}
}
Output:
Java is fun!
Keyword: try
Definition:
The try keyword is used to define a block of code that may throw exceptions.
It must be followed by at least one catch block or a finally block.
The try block contains code where exceptions are monitored.
Syntax:
try {
// code that may throw exception
} catch (ExceptionType e) {
// exception handling code
} finally {
// optional block, executes always
}
Example:
class TestTry {
public static void main(String[] args) {
try {
int division = 10 / 0; // throws ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
} finally {
System.out.println("This block always executes");
}
}
}
Output:
Definition:
The void keyword is used to specify that a method does not return any value.
Methods declared with void perform actions but do not send any data back to
the caller.
Syntax:
void methodName(parameters) {
// method body
}
Example:
class TestVoid {
void displayMessage() {
System.out.println("This method returns nothing.");
}
Output:
Keyword: volatile
Group: Non-Access Modifier (Concurrency Control)
Definition:
The volatile keyword is used to declare a variable whose value may be
modified by multiple threads concurrently.
It ensures visibility of changes to variables across threads, preventing threads
from caching values locally.
Access to a volatile variable is always read from and written to the main
memory.
Syntax:
Example:
class SharedData {
volatile int counter = 0;
t1.start();
t2.start();
t1.join();
t2.join();
Note:
Keyword: while
Definition:
The while keyword is used to create a while loop, which repeatedly executes a
block of code as long as the specified condition is true.
The condition is evaluated before each iteration, so if the condition is false initially,
the loop body may not execute at all.
Syntax:
while (condition) {
// code block to execute
}
Example:
class TestWhile {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println("Count: " + i);
i++;
}
}
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Keyword: _ (Underscore)
Definition:
The single underscore ( _ ) used to be allowed as an identifier in earlier versions of
Java.
Since Java 9, using _ alone as an identifier is not allowed and results in a
compile-time error.
It is reserved for future use and cannot be used as a variable name, method name,
or identifier.
Example:
Important:
You cannot declare variables, methods, or classes with the name _ in Java 9+.
Using _ alone as an identifier will cause a compiler error like:
"underscore is a keyword, and may not be used as an identifier"
Contextual Keywords~
Keyword: exports
Definition:
The exports keyword is used in the module system introduced in Java 9.
It declares which packages of a module are accessible to other modules.
Only the packages explicitly exported are accessible outside the module.
Syntax:
exports package.name;
Example:
module-info.java (in module com.example.mymodule )
module com.example.mymodule {
exports com.example.mymodule.api;
}
This means the package com.example.mymodule.api is accessible to other
modules.
Packages not exported remain encapsulated within the module.
Usage Context:
Used only in module-info.java files to define module boundaries.
Helps with strong encapsulation and modular programming in Java.
Keyword: module
Definition:
The module keyword is used to define a Java module in the module system
introduced in Java 9.
A module groups related packages and controls which packages are accessible to
other modules.
Modules enhance strong encapsulation and better dependency management.
Syntax:
module moduleName {
// directives like exports, requires, uses, provides
}
Example:
module-info.java file:
module com.example.myapp {
requires java.base;
exports com.example.myapp.api;
}
Usage Context:
Modules are declared in a file named module-info.java at the root of the module
source directory.
Supports better modular design by clearly specifying dependencies and API
exposure.
Keyword: non-sealed
Definition:
The non-sealed keyword is used to allow a class to extend a sealed class but be
itself non-sealed, meaning it can be further extended by other classes.
It provides flexibility in the sealed class hierarchy by opening up the subclass for
further extension.
Context:
Used with sealed classes, which restrict which classes can extend them.
A sealed class explicitly permits certain subclasses using the permits keyword.
These subclasses can be declared as final , sealed , or non-sealed .
Syntax:
public non-sealed class Subclass extends SealedClass {
// This class can be extended further
}
Example:
Summary:
non-sealed lets subclasses of a sealed class be open for extension, unlike final
or sealed which restrict it.
Helps maintain controlled yet flexible inheritance hierarchies.
Keyword: open
Definition:
The open keyword is used in the module system to declare that a module or a
package is open for deep reflection by other modules at runtime.
This allows frameworks and libraries (like reflection-based tools) to access non-
public members of classes inside the module/package.
There are two common uses:
open module — the entire module is open for reflection.
open package — a specific package is open for reflection.
Syntax:
or
Example:
module-info.java:
This declares the module com.example.myapp as open, so all its packages are
open for reflection.
Usage Context:
Primarily used to support frameworks that rely on reflection (like Spring,
Hibernate).
Without open , deep reflection is restricted in the module system.
Keyword: opens
Syntax:
opens package.name;
opens package.name to moduleName1, moduleName2;
Example:
module-info.java
module com.example.myapp {
opens com.example.myapp.internal to javafx.fxml;
}
Usage Context:
Used to grant runtime-only access for reflection, important for frameworks like
serialization, dependency injection, or UI frameworks.
Helps maintain encapsulation by not exporting the package for normal compile-
time usage.
Keyword: permits
Syntax:
Example:
Here, only Car and Bike are permitted to extend Vehicle . No other class can
extend it.
Summary:
permits defines the set of allowed subclasses in sealed class hierarchies.
Enforces controlled inheritance and better encapsulation.
Keyword: provides
Syntax:
Example:
module-info.java
module com.example.myapp {
provides com.example.service.MessageService with
com.example.service.impl.MessageServiceImpl;
}
Usage Context:
Used with the Java Platform Module System (JPMS) for dynamic service
discovery and loading.
Supports loosely coupled, pluggable designs.
Keyword: record
Definition:
The record keyword is used to declare a special kind of class called a "record".
Records are immutable data carriers designed to hold fixed sets of data with less
boilerplate code than normal classes.
Records automatically provide implementations of methods like equals() ,
hashCode() , and toString() .
Syntax:
Example:
Output:
X: 10
Y: 20
Point[x=10, y=20]
Summary:
Records simplify creating classes for immutable data.
They reduce boilerplate and promote clean, concise code for value-based classes.
Keyword: requires
Definition:
The requires keyword is used in a module declaration to specify module
dependencies.
It indicates that the current module depends on another module, allowing access
to its exported packages.
Syntax:
module moduleName {
requires other.module.name;
}
Example:
module-info.java
module com.example.myapp {
requires java.sql;
}
Summary:
requires is used to declare dependencies between modules in Java’s module
system.
Helps enforce modular encapsulation and clear dependency management.
Keyword: sealed
Definition:
The sealed keyword is used to restrict which classes or interfaces may extend
or implement a given class or interface.
A sealed class declares a fixed set of permitted subclasses using the permits
keyword.
It provides controlled inheritance, improving encapsulation and security.
Syntax:
Example:
Summary:
sealed classes allow strict control over subclassing.
Only classes listed in permits can extend the sealed class.
Keyword: to
Group: Module System Directive Keyword (Java 9 and later)
Definition:
The to keyword is used in module declarations with exports or opens directives
to limit which specific modules can access the exported or opened package.
It restricts the visibility of the package to only the named modules.
Syntax:
Example:
module-info.java
module com.example.myapp {
exports com.example.myapp.api to com.example.client,
com.example.tools;
opens com.example.myapp.internal to com.example.framework;
}
Usage Context:
Useful for fine-grained control over module dependencies and encapsulation in
the Java module system.
Keyword: transitive
Group: Module System Modifier (Java 9 and later)
Definition:
The transitive keyword is used with the requires directive in a module
declaration to specify that any module depending on this module also implicitly
depends on the required module.
It makes the dependency transitive, so dependent modules don’t need to declare
the transitive dependency explicitly.
Syntax:
Example:
module-info.java
module com.example.app {
requires transitive com.example.utils;
}
Usage Context:
Useful for sharing common dependencies across modules without requiring every
module to declare them.
Keyword: uses
Syntax:
uses ServiceInterface;
Example:
module-info.java
module com.example.myapp {
uses com.example.service.MessageService;
}
Usage Context:
Used in the Java Platform Module System for service provider lookup and
dynamic loading.
Works together with provides keyword, which declares implementations.
Keyword: var
Syntax:
Example:
class TestVar {
public static void main(String[] args) {
var message = "Hello, World!"; // inferred as String
var number = 100; // inferred as int
System.out.println(message);
System.out.println(number);
}
}
Output:
Hello, World!
100
Important Notes:
var is not a keyword but a reserved type name for local variable inference.
Variable must be initialized at declaration for compiler to infer type.
Cannot be used for uninitialized variables or method parameters.
Keyword: with
Definition:
The with keyword is used in a module declaration to associate a service
implementation class with a service interface in the provides directive.
It specifies which class provides the implementation of the declared service.
Syntax:
Example:
module-info.java
module com.example.myapp {
provides com.example.service.MessageService with
com.example.service.impl.MessageServiceImpl;
}
Usage Context:
Used as part of Java’s Service Loader mechanism for dynamic service discovery
and loading.
Helps build modular, pluggable applications.
Keyword: yield
Group: Flow Control Keyword (Java 13 and later)
Definition:
The yield keyword is used inside a switch expression to return a value from a
case block.
It allows multi-line case blocks to compute a value and return it to the switch
expression.
It acts similar to return , but is specific to switch expressions.
Syntax:
switch (expression) {
case value1 -> result1;
case value2 -> {
// multiple statements
yield result2;
}
default -> result3;
}
Example:
System.out.println(result);
}
}
Usage Context:
Only valid inside switch expressions (introduced as a preview feature in Java 13,
finalized in Java 14).
Used when case block needs multiple statements before returning a value.
Replaces the older break + assignment approach in classic switch-case
statements.