0% found this document useful (0 votes)
6 views83 pages

Keywords in Java

Uploaded by

adefault720
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views83 pages

Keywords in Java

Uploaded by

adefault720
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

Keywords in Java

Each Keyword at a time!


Keyword: abstract

Group: Non-Access Modifier (used for classes and methods)

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 class ClassName {


abstract void methodName(); // abstract method
void normalMethod() { } // normal method
}

Abstract Method:

abstract returnType methodName(parameters);

Example:

abstract class Shape {


abstract void draw(); // abstract method

void info() {
System.out.println("This is a shape");
}
}

class Circle extends Shape {


void draw() {
System.out.println("Drawing Circle");
}
}

public class TestAbstract {


public static void main(String[] args) {
Shape s = new Circle(); // allowed via upcasting
s.draw(); // Output: Drawing Circle
s.info(); // Output: This is a shape
}
}

Keyword: assert

Group: Exception Handling / Debugging Keyword

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;

With Error Message:

assert condition : "Error Message";

Example:
class TestAssert {
public static void main(String[] args) {
int age = 15;

assert age >= 18 : "Age must be 18 or above"; // will throw


AssertionError

System.out.println("Age is valid");
}
}

How to Run:
Assertions are disabled by default.
To enable them, run with:

java -ea TestAssert

Output (if enabled):

Exception in thread "main" java.lang.AssertionError: Age must be 18 or


above

Keyword: boolean

Group: Primitive Data Type Keyword

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:

boolean variableName = true; // or false


Example:

class TestBoolean {
public static void main(String[] args) {
boolean isJavaFun = true;
boolean isFishTasty = false;

System.out.println("Is Java Fun? " + isJavaFun);


System.out.println("Is Fish Tasty? " + isFishTasty);

if (isJavaFun) {
System.out.println("Yes, Java is fun!");
}
}
}

Output:

Is Java Fun? true


Is Fish Tasty? false
Yes, Java is fun!

Keyword: break

Group: Control Flow Statement

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;

Example 1: Using break in a loop

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

Example 2: Using break in switch

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

Group: Primitive Data Type Keyword

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:

byte variableName = value;

Example:

class TestByte {
public static void main(String[] args) {
byte num = 100; // valid (within range)
System.out.println(num);

byte small = 10;


byte big = 20;
int sum = small + big; // result is promoted to int
System.out.println("Sum: " + sum);
}
}

Output:

100
Sum: 30

Keyword: case

Group: Control Flow Statement (used with switch)

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

Group: Exception Handling Keyword

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

Group: Primitive Data Type Keyword

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:

char variableName = 'A';

Example:
class TestChar {
public static void main(String[] args) {
char grade = 'A';
char symbol = '#';
char digit = '7';

System.out.println("Grade: " + grade);


System.out.println("Symbol: " + symbol);
System.out.println("Digit: " + digit);

// You can also assign Unicode value


char unicodeChar = '\u0041'; // Unicode for 'A'
System.out.println("Unicode Char: " + unicodeChar);
}
}

Output:

Grade: A
Symbol: #
Digit: 7
Unicode Char: A

Keyword: class

Group: Class Definition Keyword

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

void display() { // method


System.out.println(brand + " - " + year);
}
}

public class TestClass {


public static void main(String[] args) {
Car myCar = new Car(); // creating object
myCar.brand = "Toyota";
myCar.year = 2023;

myCar.display(); // Output: Toyota - 2023


}
}

Output:

Toyota - 2023

Keyword: const

Group: Reserved Keyword (Not Used)

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.

Instead, constants are declared like this:

final dataType VARIABLE_NAME = value;

Example (using final instead of const):

class TestConst {
public static void main(String[] args) {
final int MAX = 100; // constant
System.out.println("Max value: " + MAX);
}
}

Output:

Max value: 100

Keyword: continue

Group: Control Flow Statement

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

Group: Control Flow Statement (used in switch) / Interface


Modifier (default methods)

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
}

Syntax (Interface Default Method):

interface MyInterface {
default void display() {
System.out.println("Default method in interface");
}
}

Example 1 – Using default in switch:

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

Example 2 – Using default in interface:

interface Vehicle {
default void horn() {
System.out.println("Default horn sound");
}
}

class Car implements Vehicle { }

public class TestDefaultInterface {


public static void main(String[] args) {
Car c = new Car();
c.horn(); // Output: Default horn sound
}
}

Keyword: do

Group: Control Flow Statement (Loop)

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

Group: Primitive Data Type Keyword

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:

double variableName = value;

Example:

class TestDouble {
public static void main(String[] args) {
double price = 99.99;
double pi = 3.14159;

System.out.println("Price: " + price);


System.out.println("Value of Pi: " + pi);

double sum = price + pi;


System.out.println("Sum: " + sum);
}
}

Output:

Price: 99.99
Value of Pi: 3.14159
Sum: 103.13159

Keyword: else

Group: Control Flow Statement (Conditional)

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:

Not eligible to vote

Keyword: enum

Group: Special Class Type (Enum Type)

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

Group: Inheritance Keyword

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 ChildClass extends ParentClass {


// additional fields and methods
}
For Interfaces:

interface InterfaceB extends InterfaceA {


// additional methods
}

Example – Class Inheritance:

class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


void bark() {
System.out.println("Dog barks");
}
}

public class TestExtends {


public static void main(String[] args) {
Dog d = new Dog();
d.sound(); // inherited method
d.bark(); // child method
}
}

Output:

Animal makes a sound


Dog barks

Example – Interface Inheritance:

interface A {
void methodA();
}

interface B extends A {
void methodB();
}

Keyword: false

Group: Boolean Literal

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:

boolean variableName = false;

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

Group: Non-Access Modifier

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):

final dataType variableName = value;

For Methods:

final returnType methodName() { . }

For Classes:

final class ClassName { . }

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");
}
}

class Child extends Parent {


// void display() {} // ERROR: Cannot override final method
}

3. Final Class

final class Vehicle { }

class Car extends Vehicle { } // ERROR: Cannot inherit from final class

Keyword: finally

Group: Exception Handling Keyword

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

Group: Primitive Data Type Keyword

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:

float variableName = value;


Example:

class TestFloat {
public static void main(String[] args) {
float price = 99.99f; // 'f' is required for float literal
float pi = 3.14F;

System.out.println("Price: " + price);


System.out.println("Pi Value: " + pi);

float total = price + pi;


System.out.println("Total: " + total);
}
}

Output:

Price: 99.99
Pi Value: 3.14
Total: 103.13

Keyword: for

Group: Control Flow Statement (Loop)

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:

for (initialization; condition; update) {


// code block
}

Enhanced For Loop:

for (dataType variable : array) {


// code block
}

Example 1 – 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

Example 2 – Enhanced for loop:

class TestForEach {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40};

for (int num : numbers) {


System.out.println(num);
}
}
}

Output:
10
20
30
40

Keyword: goto

Group: Reserved Keyword (Not Used)

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.

Alternative Example (Using Labeled break):

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

Group: Control Flow Statement (Conditional)

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
}

Example 1 – Simple if:

class TestIf {
public static void main(String[] args) {
int age = 20;

if (age >= 18) {


System.out.println("Eligible to vote");
}
}
}
Output:

Eligible to vote

Example 2 – if-else:

class TestIfElse {
public static void main(String[] args) {
int marks = 35;

if (marks >= 40) {


System.out.println("Pass");
} else {
System.out.println("Fail");
}
}
}

Output:

Fail

Example 3 – if-else if ladder:

class TestIfElseIf {
public static void main(String[] args) {
int marks = 85;

if (marks >= 90) {


System.out.println("Grade A+");
} else if (marks >= 75) {
System.out.println("Grade A");
} else {
System.out.println("Grade B");
}
}
}

Output:
Grade A

Keyword: implements

Group: Inheritance / Interface Implementation Keyword

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:

class ClassName implements InterfaceName1, InterfaceName2 {


// must implement all abstract methods
}

Example:

interface Animal {
void sound(); // abstract method
}

interface Pet {
void play();
}

class Dog implements Animal, Pet {


public void sound() {
System.out.println("Dog barks");
}
public void play() {
System.out.println("Dog plays with ball");
}
}

public class TestImplements {


public static void main(String[] args) {
Dog d = new Dog();
d.sound(); // Output: Dog barks
d.play(); // Output: Dog plays with ball
}
}

Output:

Dog barks
Dog plays with ball

Keyword: import

Group: Package Management Keyword

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:

import packageName.ClassName; // import specific class


import packageName.*; // import all classes from package

Example:

import java.util.Scanner; // importing Scanner class


class TestImport {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // using imported class
System.out.print("Enter name: ");
String name = sc.nextLine();
System.out.println("Hello " + name);
}
}

Output (if input is Amit):

Enter name: Amit


Hello Amit

Keyword: instanceof

Group: Type Comparison Operator (Keyword)

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:

object instanceof ClassName

Example:

class Animal {}
class Dog extends Animal {}

public class TestInstanceof {


public static void main(String[] args) {
Dog d = new Dog();
System.out.println(d instanceof Dog); // true
System.out.println(d instanceof Animal); // true
System.out.println(d instanceof Object); // true
}
}

Output:

true
true
true

Keyword: int

Group: Primitive Data Type Keyword

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:

int variableName = value;

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

Group: Type Definition Keyword

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
}

class Dog implements Animal {


public void sound() {
System.out.println("Dog barks");
}
}

public class TestInterface {


public static void main(String[] args) {
Dog d = new Dog();
d.sound(); // Output: Dog barks
}
}

Output:

Dog barks

Keyword: long

Group: Primitive Data Type Keyword

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:

long variableName = value;

Example:

class TestLong {
public static void main(String[] args) {
long population = 1380004385L; // 'L' is required for large values
long distance = 9876543210L;

System.out.println("Population: " + population);


System.out.println("Distance: " + distance);
}
}
Output:

Population: 1380004385
Distance: 9876543210

Keyword: native

Group: Non-Access Modifier

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:

native returnType methodName(parameters);

Must be used inside a class.


A native method is usually static or final .

Example:

class TestNative {
// Declaration of native method
public native void printMessage();

static {
System.loadLibrary("MyNativeLib"); // Load native library
}

public static void main(String[] args) {


new TestNative().printMessage(); // Calls C/C++ implementation
}
}

The actual implementation will be in C/C++ and compiled as a native library.

Keyword: null

Group: Literal (Null Literal)

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:

ClassName obj = null;

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

Group: Object Creation Keyword (Operator)

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:

ClassName obj = new ClassName(); // Create object


dataType[] arr = new dataType[size]; // Create array

Example 1 – Creating an object:

class Car {
void drive() {
System.out.println("Car is running");
}
}

public class TestNew {


public static void main(String[] args) {
Car c = new Car(); // object creation
c.drive();
}
}

Output:

Car is running

Example 2 – Creating an array:

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;

for (int num : numbers) {


System.out.println(num);
}
}
}

Output:

10
20
30

Keyword: package

Group: Package Management Keyword

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;

public class Message {


public void display() {
System.out.println("Hello from mypack!");
}
}

File: TestPackage.java

import mypack.Message;

public class TestPackage {


public static void main(String[] args) {
Message msg = new Message();
msg.display();
}
}

Steps to Run:

1. Compile with package directory:

javac -d . Message.java

2. Compile and run TestPackage.java :

javac TestPackage.java
java TestPackage

Output:

Hello from mypack!

Keyword: private

Group: Access Modifier

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:

private dataType variableName;


private returnType methodName() { . }

Example:

class BankAccount {
private double balance; // private variable

// public method to access private variable


public void deposit(double amount) {
balance += amount;
}

public double getBalance() {


return balance;
}
}
public class TestPrivate {
public static void main(String[] args) {
BankAccount acc = new BankAccount();
acc.deposit(5000);
System.out.println("Balance: " + acc.getBalance());
// acc.balance = 10000; // ERROR: balance has private access
}
}

Output:

Balance: 5000.0

Keyword: protected

Group: Access Modifier

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:

protected dataType variableName;


protected returnType methodName() { . }

Example:

class Animal {
protected String name = "Generic Animal";
protected void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


public void display() {
System.out.println("Name: " + name); // Accessible due to
protected
sound(); // Accessible
}
}

public class TestProtected {


public static void main(String[] args) {
Dog d = new Dog();
d.display();
}
}

Output:

Name: Generic Animal


Animal makes a sound

Keyword: public

Group: Access Modifier

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:

public returnType methodName(parameters) { . }

For Variable:

public dataType variableName;

Example:

// File: MyClass.java
public class MyClass {
public int number = 10; // public variable

public void display() { // public method


System.out.println("Hello from public method!");
}
}

// 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

Group: Control Flow Statement (Method Control)


Definition:
The return keyword is used to exit from a method and optionally return a value
to the caller.
If the method has a return type other than void , return must return a value of
that type.

Syntax:

return; // used in void methods


return value; // used in methods with a return type

Example 1 – Returning a value:

class Calculator {
public int add(int a, int b) {
return a + b; // returns int value
}
}

public class TestReturn {


public static void main(String[] args) {
Calculator c = new Calculator();
int result = c.add(5, 3);
System.out.println("Sum: " + result);
}
}

Output:

Sum: 8

Example 2 – Using return in a void method:

class TestReturnVoid {
public void display(int x) {
if (x < 0) {
System.out.println("Negative value");
return; // exits the method
}
System.out.println("Value: " + x);
}

public static void main(String[] args) {


TestReturnVoid obj = new TestReturnVoid();
obj.display(-5); // exits early
obj.display(10); // prints value
}
}

Output:

Negative value
Value: 10

Keyword: short

Group: Primitive Data Type Keyword

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:

short variableName = value;

Example:

class TestShort {
public static void main(String[] args) {
short num1 = 1000;
short num2 = 2000;

short sum = (short)(num1 + num2); // explicit casting required


System.out.println("Sum: " + sum);
}
}

Output:

Sum: 3000

Keyword: static

Group: Non-Access Modifier

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:

static dataType variableName;


static returnType methodName() { . }
static { . } // static block

Example 1 – Static Variable and Method:

class Counter {
static int count = 0; // shared variable

static void increment() {


count++;
}
}

public class TestStatic {


public static void main(String[] args) {
Counter.increment(); // calling without object
Counter.increment();
System.out.println("Count: " + Counter.count);
}
}

Output:

Count: 2

Example 2 – Static Block:

class TestStaticBlock {
static {
System.out.println("Static block executed before main");
}

public static void main(String[] args) {


System.out.println("Main method executed");
}
}

Output:

Static block executed before main


Main method executed

Keyword: strictfp

Group: Non-Access Modifier (Floating-Point Precision


Control)

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.

Where It Can Be Used:


With classes
With methods
With interfaces

Syntax:

strictfp class ClassName { . }

strictfp returnType methodName() { . }

Example:

strictfp class TestStrictfp {


public static void main(String[] args) {
double num1 = 10e+10;
double num2 = 6e+08;
double result = num1 / num2;

System.out.println("Result: " + result);


}
}

Output (consistent on all platforms):

Result: 16.666...

If strictfp is not used, floating-point operations may vary across hardware/OS.


Keyword: super

Group: Inheritance Keyword

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");
}
}

class Dog extends Animal {


String name = "Dog";

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");
}
}

public class TestSuper {


public static void main(String[] args) {
Dog d = new Dog();
d.display();
d.sound();
}
}

Output:

Animal constructor
Dog constructor
Child name: Dog
Parent name: Animal
Animal makes sound
Dog barks

Keyword: switch

Group: Control Flow Statement (Conditional)

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

Group: Multithreading Keyword

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.

Where It Can Be Used:


1. Synchronized Method
2. Synchronized Block

Syntax:
Synchronized Method:

public synchronized void methodName() {


// code
}

Synchronized Block:

synchronized (object) {
// code
}

Example:

class Counter {
private int count = 0;
public synchronized void increment() { // synchronized method
count++;
}

public int getCount() {


return count;
}
}

public class TestSynchronized {


public static void main(String[] args) throws InterruptedException {
Counter c = new Counter();

Thread t1 = new Thread(() -> {


for (int i = 0; i < 1000; i++) c.increment();
});

Thread t2 = new Thread(() -> {


for (int i = 0; i < 1000; i++) c.increment();
});

t1.start();
t2.start();

t1.join();
t2.join();

System.out.println("Final Count: " + c.getCount());


}
}

Output:

Final Count: 2000

Without synchronized , the output might be less than 2000 due to race conditions.

Keyword: this

Group: Reference Keyword

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

Example 1 – Resolving Variable Name Conflict:

class Student {
String name;

Student(String name) {
this.name = name; // 'this' refers to instance variable
}

void display() {
System.out.println("Name: " + this.name);
}
}

public class TestThis {


public static void main(String[] args) {
Student s = new Student("Amit");
s.display();
}
}

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);
}
}

public class TestThisConstructor {


public static void main(String[] args) {
new Demo();
}
}

Output:

Parameterized constructor: 10
Default constructor

Keyword: throw

Group: Exception Handling Keyword

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:

throw new ExceptionType("Error message");


Example:

class TestThrow {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Not eligible to vote");
} else {
System.out.println("Eligible to vote");
}
}

public static void main(String[] args) {


try {
checkAge(15);
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}

Output:

Exception caught: Not eligible to vote

Keyword: throws

Group: Exception Handling Keyword

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();
}

public static void main(String[] args) {


try {
readFile();
} catch (IOException e) {
System.out.println("Exception handled: " + e.getMessage());
}
}
}

Keyword: transient

Group: Non-Access Modifier (Serialization Control)

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.*;

class User implements Serializable {


String username;
transient String password; // will not be serialized

User(String username, String password) {


this.username = username;
this.password = password;
}
}

public class TestTransient {


public static void main(String[] args) {
User user = new User("Amit", "mypassword");

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();

System.out.println("Username: " + deserializedUser.username);


System.out.println("Password: " + deserializedUser.password);
// null
} catch (Exception e) {
e.printStackTrace();
}
}
}

Output:
Username: Amit
Password: null

Keyword: true

Group: Boolean Literal

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:

boolean flag = true;

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

Group: Exception Handling Keyword

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:

Cannot divide by zero


This block always executes
Keyword: void

Group: Method Return Type Keyword

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.");
}

public static void main(String[] args) {


TestVoid obj = new TestVoid();
obj.displayMessage();
}
}

Output:

This method returns nothing.

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:

volatile dataType variableName;

Example:

class SharedData {
volatile int counter = 0;

public void increment() {


counter++;
}
}

public class TestVolatile {


public static void main(String[] args) throws InterruptedException {
SharedData data = new SharedData();

Thread t1 = new Thread(() -> {


for (int i = 0; i < 1000; i++) {
data.increment();
}
});

Thread t2 = new Thread(() -> {


for (int i = 0; i < 1000; i++) {
data.increment();
}
});

t1.start();
t2.start();

t1.join();
t2.join();

System.out.println("Counter: " + data.counter);


}
}

Note:

volatile does not guarantee atomicity of operations (like increment). Use


synchronization for atomicity.

Keyword: while

Group: Control Flow Statement (Loop)

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)

Group: Reserved Keyword (Disallowed Identifier)

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:

// Java 8: allowed (not recommended)


// int _ = 10;
// Java 9 and later:
// int _ = 10; // Compilation error: as of release 9, '_' is a keyword

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

Group: Module System Keyword (Java 9 and later)

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

Group: Module System Keyword (Java 9 and later)

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;
}

This defines a module named com.example.myapp that requires the java.base


module (implicitly required in all modules) and exports the package
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

Group: Sealed Classes Modifier (Java 17 and later)

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:

public sealed class Vehicle permits Car, Bike {}

public final class Car extends Vehicle {


// No further subclassing allowed
}

public non-sealed class Bike extends Vehicle {


// Bike can be subclassed further
}

public class MountainBike extends Bike {


// Allowed because Bike is non-sealed
}

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

Group: Module System Modifier (Java 9 and later)

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:

open module moduleName {


// directives
}

or

open package packageName;

Example:
module-info.java:

open module com.example.myapp {


exports com.example.myapp.api;
}

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

Group: Module System Keyword (Java 9 and later)


Definition:
The opens keyword is used in the module system to open a specific package for
deep reflection at runtime without exporting it for compile-time access.
This allows reflection-based frameworks to access non-public members (fields,
methods) of classes in the specified package.
Unlike exports , which allows compile-time access, opens is for runtime
reflection only.

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;
}

This opens the package com.example.myapp.internal only to the javafx.fxml


module for deep reflection.

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

Group: Sealed Classes Keyword (Java 17 and later)


Definition:
The permits keyword is used in a sealed class or interface declaration to specify
the allowed subclasses or implementations.
It restricts which classes or interfaces can extend or implement the sealed
class/interface.

Syntax:

public sealed class ClassName permits Subclass1, Subclass2, Subclass3 {


// class body
}

Example:

public sealed class Vehicle permits Car, Bike {}

public final class Car extends Vehicle {}

public non-sealed class Bike extends Vehicle {}

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

Group: Module System Keyword (Java 9 and later)


Definition:
The provides keyword is used in the module system to declare that a module
provides an implementation of a service interface.
It is part of the Service Loader mechanism for service-provider loading.

Syntax:

provides ServiceInterface with ServiceImplementation;

Example:
module-info.java

module com.example.myapp {
provides com.example.service.MessageService with
com.example.service.impl.MessageServiceImpl;
}

This means the module provides an implementation MessageServiceImpl for the


service interface MessageService .

Usage Context:
Used with the Java Platform Module System (JPMS) for dynamic service
discovery and loading.
Supports loosely coupled, pluggable designs.

Keyword: record

Group: Class Declaration Modifier (Java 14 and later)

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:

public record RecordName(dataType field1, dataType field2, .) {


// optional additional methods or constructors
}

Example:

public record Point(int x, int y) {}

public class TestRecord {


public static void main(String[] args) {
Point p = new Point(10, 20);
System.out.println("X: " + p.x());
System.out.println("Y: " + p.y());
System.out.println(p); // prints Point[x=10, y=20]
}
}

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

Group: Module System Keyword (Java 9 and later)

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;
}

This means the module com.example.myapp depends on the java.sql module


and can use its public APIs.

Summary:
requires is used to declare dependencies between modules in Java’s module
system.
Helps enforce modular encapsulation and clear dependency management.
Keyword: sealed

Group: Class Modifier (Java 17 and later)

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:

public sealed class ClassName permits Subclass1, Subclass2 {


// class body
}

Example:

public sealed class Vehicle permits Car, Bike {}

public final class Car extends Vehicle {}

public non-sealed class Bike extends Vehicle {}

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:

exports package.name to moduleName1, moduleName2;


opens package.name to moduleName1, moduleName2;

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;
}

Here, the package com.example.myapp.api is exported only to the modules


com.example.client and com.example.tools .
The package com.example.myapp.internal is opened for reflection only 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:

requires transitive moduleName;

Example:
module-info.java

module com.example.app {
requires transitive com.example.utils;
}

If another module requires com.example.app , it automatically also requires


com.example.utils because of transitive .

Usage Context:
Useful for sharing common dependencies across modules without requiring every
module to declare them.

Keyword: uses

Group: Module System Keyword (Java 9 and later)


Definition:
The uses keyword is used in a module declaration to specify that the module
depends on a service interface.
It indicates that the module intends to consume implementations of the specified
service interface at runtime.

Syntax:

uses ServiceInterface;

Example:
module-info.java

module com.example.myapp {
uses com.example.service.MessageService;
}

This declares that com.example.myapp uses the service interface MessageService ,


and at runtime, implementations of MessageService may be loaded.

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

Group: Local Variable Type Inference (Java 10 and later)


Definition:
The var keyword enables local variable type inference in Java.
When declaring a local variable, the compiler infers the variable’s type from the
initializer expression, so you don't have to explicitly write the type.
Only works for local variables inside methods, constructors, or initializer blocks—
not for fields, method parameters, or return types.

Syntax:

var variableName = value; // compiler infers type from 'value'

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

Group: Module System Directive (Java 9 and later)

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:

provides ServiceInterface with ServiceImplementationClass;

Example:
module-info.java

module com.example.myapp {
provides com.example.service.MessageService with
com.example.service.impl.MessageServiceImpl;
}

This declares that the module provides an implementation MessageServiceImpl


for the service interface MessageService .

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:

public class YieldExample {


public static void main(String[] args) {
int num = 2;

String result = switch (num) {


case 1 -> "One";
case 2 -> {
System.out.println("Inside case 2");
yield "Two"; // returns "Two" for this case
}
default -> "Other";
};

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.

You might also like