1. What Are SealedClasses?
o SealedInterfaces
2. Pattern Matchingfor instanceof
3. WhatAre Records?
4. WhatIs Strong Encapsulation?
5. NewGarbage Collectors
o HowIt Works
Divides memory into twogenerations:
Java 21 IMprovements
Other Collectors(Still Available)
6. VectorAPI
o What is Vector API?
Purpose
Key Components
How It Works
7. TextBlocks
1. What Are Sealed Classes?
restrict which classes or interfaces can extend or implement a
given class or interface.
🧩 Syntax
public sealed class Shape permits Circle, Square, Triangle {
// class body}
sealed: Declares the class as sealed.
permits: Lists the classes allowed to extend this sealed
class.
Each permitted subclass must be declared as either:
sealed
non-sealed
final
Sealed Interfaces:
You can also seal interfaces to restrict which classes implement
them
public sealed interface Vehicle permits Car, Bike {}
Subclass Options
Modifier Meaning
final Cannot be extended further.
Can be extended, but must declare its own
sealed
permits clause.
non- Removes sealing — allows unrestricted
sealed extension.
🧠 Why Use Sealed Classes?
✅ Exhaustive pattern matching: Useful with switch or
instanceof checks.
✅ Better control: Prevents unwanted subclassing.
✅ Improved readability: Makes hierarchies explicit.
✅ Safer refactoring: You know all subclasses at compile time.
Real-World Backend Use Case: Error Handling
public sealed class ServiceError permits TimeoutError,
ValidationError, DatabaseError {
public abstract String getMessage();
public final class TimeoutError extends ServiceError {
public String getMessage() {
return "Request timed out.";
}
public final class ValidationError extends ServiceError {
public String getMessage() {
return "Invalid input.";
public final class DatabaseError extends ServiceError {
public String getMessage() {
return "Database connection failed.";
This lets you handle errors like:
public void handleError(ServiceError error) {
switch (error) {
case TimeoutError t -> log([Link]());
case ValidationError v -> notifyUser([Link]());
case DatabaseError d -> alertOps([Link]());
2. Pattern Matching for instanceof
🔍 Traditional instanceof (Before Java 16)
if (obj instanceof String) {
String s = (String) obj; // explicit cast
[Link]([Link]());
}
We had to check the type and then cast it manually.
🚀 Pattern Matching instanceof (Java 16+)
if (obj instanceof String s) {
[Link]([Link]()); // no cast needed
}
The variable s is automatically cast to String if the check
passes.
Scope of s is limited to the if block.
3. What Are Records?
Definition
o Records are a special kind of class in Java.
o Their purpose is to simplify the creation of data-holding objects.
Purpose
o Designed to reduce boilerplate code for classes that primarily
store data.
o Automatically generate methods like equals(),
hashCode(), and toString().
🚫 Limitations
Records cannot extend other classes (they implicitly
extend [Link]).
Fields are final and cannot be changed after
construction.
Not suitable for mutable or behavior-heavy classes.
🛠 Use Cases
DTOs (Data Transfer Objects)
Configuration objects
Lightweight domain models
Return types for service methods
example of a record in Java that models a Person:
public record Person(String name, int age) {}
🔍 What This Does
This single line of code automatically gives you:
A final class named Person
Two private final fields: name and age
A constructor: Person(String name, int age)
Getter methods: name() and age()
equals(), hashCode(), and toString() methods
🧪 Example Usage
public class Main {
public static void main(String[] args) {
Person p = new Person("Aarav", 30);
[Link]([Link]()); // Output: Aarav
[Link]([Link]()); // Output: 30
[Link](p); // Output: Person[name=Aarav,
age=30]
}
}
4. What Is Strong Encapsulation?
Strong encapsulation refers to the default restriction of access to
internal APIs and non-exported packages in Java modules.
exported or opened packages are accessible outside a module.
🧱 Why It Was Introduced
Before Java 9, developers developed on internal JDK classes (like
[Link]) that were never meant for public use.
Security risks due to access to privileged operations.
Maintenance issues when internal APIs changed or were removed.
Compatibility problems during JDK upgrades.
Strong encapsulation aims to:
Improve security and maintainability of the JDK.
Encourage use of standard APIs.
Prevent accidental dependencies on unstable internal code.
📦 How It Works
Java modules define boundaries using [Link].
Exported packages: Accessible to other modules.
Unexported packages: Hidden from other modules.
Opened packages: Accessible via reflection (if explicitly opened).
Internal APIs: Not exported or opened, hence inaccessible.
Even reflection-based access is blocked unless the package is explicitly
opened.
⚙️Example
Suppose you have a module:
module [Link] {
exports [Link];
[Link] is accessible to other modules.
Any other package (e.g., [Link]) is strongly
encapsulated.
Exceptions and Migration
Some internal APIs like [Link] are still accessible via the
[Link] module for compatibility reasons.
To ease migration:
Java 9 introduced the --illegal-access option:
o permit: Allows access to JDK 8 internal packages.
o warn: Logs warnings.
o deny: Blocks access completely.
This option was removed in Java 17, enforcing strong encapsulation fully.
✅ Benefits
Robustness: Prevents fragile dependencies.
Security: Limits access to sensitive operations.
Cleaner architecture: Encourages modular design.
Future-proofing: Easier upgrades across Java versions.
5. New Garbage Collectors
Generational ZGC (Z Garbage Collector)
A low-latency, scalable garbage collector.
Introduced in Java 11 (non-generational), enhanced in Java 21
with generational support.
🧠 How It Works
Divides memory into two generations:
o Young Generation: Where new objects are created.
o Old Generation: long-lived objects are moved after surviving
several collections.
Collects young objects more frequently, reducing overhead and
improving performance.
🎯 Benefits
Faster GC cycles for short-lived objects.
Lower pause times even with large heaps.
Better performance for typical Java workloads.
⚙️How to Enable
Use JVM options:
java -XX:+UseZGC -XX:+UseGenerationalZGC -Xmx2G MyApp
📊 Monitoring Tools
Use JVisualVM or Java Mission Control (JMC).
Enable GC logging:
-Xlog:gc
2. 🌀 Shenandoah GC (Improved)
Java 21 Improvements
Enhanced support for large heaps and high-concurrency
applications.
Better integration with virtual threads.
Other Collectors (Still Available)
Collector Description Use Case
Region-based, balances pause Default in many Java
G1 GC
and throughput versions
Parallel GC High throughput, longer pauses Batch processing
Serial GC Simple, single-threaded Small applications
ZGC (non- Large heaps, real-time
Unified heap, low latency
generational) systems
📌 Summary
Java 21’s highlight is the Generational ZGC, combining low
latency with smart memory management.
Shenandoah GC also sees performance boosts.
These collectors help Java apps run faster, smoother, and more
efficiently—especially in cloud, big data, and real-time
environments.
Context-Specific Deserialization Filters
🔐 What Is Deserialization?
Deserialization is the process of converting binary data back into Java
objects.
If not handled carefully, it can be load malicious or unexpected
classes, leading to security risks.
🧠 What Are Context-Specific Deserialization Filters?
define which classes are allowed or denied during deserialization,
based on the context in which deserialization occurs.
✅ Key Features:
Fine-grained control over deserialization.
Filters can be applied per stream, not just globally.
Helps prevent unauthorized class loading.
Supports custom logic using predicates or patterns.
How to Use Them
You can set a filter on an ObjectInputStream like this:
🔍 Explanation:
[Link]() gives the class being deserialized.
You check if it belongs to a safe package.
You allow or reject based on your rules.
📦 Use Cases
Web applications: Prevent attackers from sending harmful
serialized data.
Microservices: Ensure only expected classes are deserialized
across services.
Third-party data: Safely handle data from external sources.
6. Vector API
📌 What is Vector API?
A Java API for performing vectorized computations using SIMD
(Single Instruction, Multiple Data).
Introduced as an incubator module in JDK 16 ([Link]).
Purpose
To accelerate performance of numerical and data-parallel
operations.
Enables Java programs to use CPU vector instructions efficiently.
🧩 Key Components
Component Description
Defines shape and size of
VectorSpecies<T>
vectors
FloatVector, IntVector,
Type-specific vector classes
etc.
Enables conditional lane
VectorMask
operations
VectorShuffle Rearranges vector lanes
How It Works
1. Choose a VectorSpecies (e.g., IntVector.SPECIES_256).
2. Load data into a vector using fromArray.
3. Perform operations like add, mul, etc.
4. Store results back to an array.
Benefits
High performance: Leverages SIMD for parallel processing.
Platform independence: Abstracts hardware-specific instructions.
Safer than native code: No need for JNI or unsafe memory access.
Use Cases
Image processing
Signal processing
Machine learning inference
Financial modelling
🚧 Limitations
Still in incubator stage (subject to change).
Requires modern CPUs with SIMD support.
Adds complexity—best for performance-critical code.
Setting Up
Requirements
JDK 17 installed.
Enable incubator modules when compiling and running:
javac --add-modules [Link] [Link]
java --add-modules [Link] YourClass
4. Step-by-Step Example: Adding Two Arrays
Step 1: Import the API
import [Link].*;
Step 2: Define Species
VectorSpecies<Float> SPECIES = FloatVector.SPECIES_256;
Step 3: Create Arrays
float[] a = new float[8];
float[] b = new float[8];
float[] result = new float[8];
Step 4: Fill Arrays
[Link](a, i -> (float) [Link]());
[Link](b, i -> (float) [Link]());
Step 5: Vector Addition
for (int i = 0; i < [Link]; i += [Link]()) {
FloatVector va = [Link](SPECIES, a, i);
FloatVector vb = [Link](SPECIES, b, i);
FloatVector vc = [Link](vb);
[Link](result, i);
7. Text Blocks
📌 Text Blocks in Java 17 — Key Points
1. Syntax: Use triple double quotes """ to define a text block.
2. String text = """
3. Line 1
4. Line 2
5. Line 3
6. """;
7. Purpose: Simplifies multi-line string creation and improves
readability.
8. Whitespace Handling: Java automatically removes common
leading whitespace.
9. Escape Sequences: Supports standard escapes like \n, \t, \".
10. String Type: Text blocks are still regular String objects.
11. Formatting: Use .formatted() to inject values.
12. String name = "Alice";
13. String greeting = """
14. Hello, %s!
15. """.formatted(name);
16. Use Cases: Ideal for HTML, SQL, JSON, XML, and other
structured text.