Modern Java Features (Java 11 to Recent)
20 min read
Modern Java Features (Java 11 to Recent)
Welcome, intrepid coder, to the cutting edge of Java! π You've mastered the fundamentals, and now it's time to add some powerful, modern tools to your arsenal. These features, introduced from Java 11 onwards, are designed to make your code more concise, readable, and robust. Think of it as upgrading from a trusty flip phone to the latest smartphone β everything you could do before is still there, but now you have a host of new capabilities that will make your life much easier.
We'll be exploring some of the most impactful changes that you'll frequently encounter in modern Java development. Let's dive in!
The 'var' Keyword: Local Variable Type Inference
The Old Way: Explicitly Stating Types
Before Java 10, every time you declared a local variable, you had to explicitly state its type. This could sometimes lead to a bit of verbosity, especially with complex types.
Imagine you're ordering a coffee. You walk up to the counter and say, "I would like a medium, two-shot, non-fat, extra-hot latte." The barista knows exactly what you want. In pre-Java 10, your code did something similar:
// Pre-Java 10
String message = "Hello, Modern Java!";
ArrayList<String> userNames = new ArrayList<String>();Notice how ArrayList<String> is mentioned on both the left and right sides of the declaration. A bit redundant, wouldn't you say? Itβs like telling the barista the full, detailed name of your coffee and then handing them a cup with the same name written on it. They get it, you get it, but couldn't it be simpler?
The Problem: Redundancy and Verbosity
The main issue with the old way was the boilerplate code. While being explicit is often good, in many cases, the type of the variable is obvious from the right-hand side of the assignment. This extra typing can make code longer and sometimes harder to read, especially with nested generic types.
For instance:
Map<String, List<Map<String, Integer>>> veryComplexMap = new HashMap<String, List<Map<String, Integer>>>();That's a mouthful! All that type information can sometimes obscure the more important part: the variable's name and its purpose.
The Solution: var to the Rescue! π¦ΈββοΈ
Introduced in Java 10, the var keyword allows for local variable type inference. This means you can declare a local variable with var, and the Java compiler will figure out the type for you based on the value you assign to it.
Think of it as simply telling the barista, "Give me the usual." They know what you mean from your past orders (the context). Similarly, the Java compiler looks at the right side of the assignment (the context) and infers the type.
// With 'var'
var message = "Hello, Modern Java!";
var userNames = new ArrayList<String>();
var veryComplexMap = new HashMap<String, List<Map<String, Integer>>>();See how much cleaner that is? The code is less cluttered, and the focus is now on the variable names, which, if well-named, tell you more about the business logic.
Under the Hood: Is Java Becoming Dynamically Typed?
A common misconception is that var makes Java a dynamically typed language like Python or JavaScript. This is not the case! Java is still a statically typed language. The type of a variable declared with var is determined at compile-time, not at runtime. Once the compiler infers the type, that variable is locked into that type for its entire scope.
So, this is perfectly fine:
var greeting = "Hello"; // Compiler infers StringBut this will result in a compilation error:
var greeting = "Hello";
greeting = 123; // Error: Type mismatch: cannot convert from int to StringThe compiler essentially replaces var with the explicit type behind the scenes. It's a convenient shorthand for you, the developer, without changing the fundamental nature of Java's type system.
Where Can You Use var? π€
The var keyword is specifically for local variables. This includes variables declared inside:
- Methods
- Constructors
- Initialization blocks
forloops
// Inside a method
public void someMethod() {
var count = 10;
}
// In a for loop
var names = List.of("Alice", "Bob");
for (var name : names) {
System.out.println(name);
}Where You Can't Use var π«
There are some important limitations to where var can be applied. You cannot use var for:
- Instance or static variables (fields): These are part of a class's contract, and their types need to be explicitly declared.
- Method parameters: The types of parameters are part of a method's signature.
- Method return types: The return type is also a key part of the method's contract.
- Variables without an initializer: You must declare and initialize a
varvariable in the same statement, otherwise, the compiler has nothing to infer the type from. - Variables initialized to
null: The compiler can't infer a specific type fromnull. - Lambda expressions without an explicit target type: The type needs to be clear from the context.
Best Practices and When to Be Cautious
While var is a great tool for reducing verbosity, it should be used judiciously to maintain code readability.
π When to Use var:
- When the type is obvious from the initializer: This is the most common and beneficial use case.java
var user = new User("JohnDoe"); // Clearly a User var names = new ArrayList<String>(); // Clearly an ArrayList of Strings - To reduce boilerplate with complex generic types: This is where
vartruly shines and improves readability.java// Instead of: Map<String, List<String>> userGroups = new HashMap<>(); // You can write: var userGroups = new HashMap<String, List<String>>();
π€ When to Think Twice About Using var:
When the initializer doesn't provide clear type information:
javavar result = getSomeData(); // What type is 'result'? A String? A List? An object?In such cases, it's often better to stick with an explicit type declaration to help other developers (and your future self!) understand the code at a glance.
When dealing with primitive types: While you can use
varfor primitives, it doesn't save much typing and can sometimes make the code less clear.java// This is fine, but is it more readable? var count = 10; // int var price = 29.99; // double // Explicit types are just as clear and short int count = 10; double price = 29.99;Chained method calls: When a variable is initialized from a long chain of method calls, the resulting type might not be immediately obvious.
javavar value = someObject.doSomething().andThenThis().getTheResult(); // What's the type of 'value'?
Key Takeaway: The goal of var is to improve code readability by removing redundant information. If using var makes the code less readable, then it's better to stick with the explicit type declaration.
Fun Fact π
The introduction of var was a bit controversial. Some developers loved the conciseness it brought, while others were concerned it would lead to less readable code. This debate highlights a core principle of software development: the importance of writing code that is easy for humans to understand.
Records: Concise Data Carrier Classes
The Old Way: The Pain of Plain Old Java Objects (POJOs)
Before Java 14, if you wanted to create a simple class just to hold data, you had to write a surprising amount of boilerplate code. These classes, often called "data carriers" or Plain Old Java Objects (POJOs), are everywhere in applications. They represent things like database records, JSON objects, or coordinates on a map.
Imagine you're creating a simple class to represent a Point with x and y coordinates. Here's what you had to write:
// Pre-Java 14
public final class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
@Override
public boolean equals(Object obj) {
// ... implementation for equals ...
}
@Override
public int hashCode() {
// ... implementation for hashCode ...
}
@Override
public String toString() {
return "Point[x=" + x + ", y=" + y + "]";
}
}Phew! That's a lot of code for something so simple. You have:
- Private final fields to make the class immutable.
- A constructor to initialize the fields.
- Getter methods to access the fields.
equals(),hashCode(), andtoString()methods, which are crucial for these objects to behave correctly in collections and for debugging.
The Problem: Too Much Boilerplate!
All this boilerplate code is tedious to write and, more importantly, it clutters up your codebase. It obscures the primary purpose of the class, which is simply to hold data. For every simple data carrier, you had to repeat this whole ceremony.
Think of it like wanting to send a simple "hello" text message, but first having to write a formal letter with a salutation, introduction, body, conclusion, and signature every single time. It's inefficient and distracts from the actual message.
The Solution: Records for Effortless Data Classes! π€
Java 14 introduced records as a way to create concise and immutable data carrier classes. With a record, you can declare the same Point class in just one line!
// With 'record'
public record Point(int x, int y) {}That's it! This single line of code does all of the following for you automatically:
- Creates a
public finalclass namedPoint. - Creates
private finalfields forxandy. - Creates a public constructor that takes
xandyas arguments. - Creates public "accessor" methods for
x()andy()(note the absence of thegetprefix). - Generates
equals(),hashCode(), andtoString()methods with implementations that use all the fields.
Itβs like having a text messaging app that handles all the formatting for you, so you can just focus on the message itself.
Under the Hood: What is a Record Really?
A record is a special kind of class that is designed to be a transparent and immutable holder for a fixed set of data. When the compiler sees the record declaration, it generates all the boilerplate code for you at compile time. The resulting .class file contains a regular class with all the methods you'd expect.
Key Characteristics of Records:
- Immutable by default: The fields of a record are
final, which means they cannot be changed after the object is created. - Concise: As you saw, the declaration is incredibly short and to the point.
- Accessor methods without
get: Instead ofgetX(), you havex(). This is a stylistic choice to emphasize that records are primarily about the data itself. - Implicitly
final: You cannot extend arecord. - Cannot be
abstract: They are meant to be concrete data carriers. - Can implement interfaces: You can still have a
recordimplement one or more interfaces. - Can have static methods and fields: Just like a regular class.
- Can have custom constructors and methods: While the default constructor and accessors are provided, you can add your own logic if needed.
Customizing Records
Sometimes, you might need to add some validation or custom logic to your record. You can add a "compact constructor" for this purpose.
For example, let's say we want to ensure that the coordinates of our Point are never negative.
public record Point(int x, int y) {
// Compact constructor for validation
public Point {
if (x < 0 || y < 0) {
throw new IllegalArgumentException("Coordinates cannot be negative");
}
}
}In a compact constructor, you don't need to write this.x = x;. This assignment is done for you implicitly after your validation logic runs. You can also add other methods to your record just like in a regular class.
public record Point(int x, int y) {
// You can add your own methods
public double distanceToOrigin() {
return Math.sqrt(x * x + y * y);
}
}When to Use Records
Records are a perfect fit whenever you need a simple, immutable object to bundle a few pieces of data together.
π Great Use Cases for Records:
- Data Transfer Objects (DTOs): Transferring data between different layers of your application (e.g., from a service to a controller).
- Representing database query results.
- Keys for a
Map. - Returning multiple values from a method.
A Fun Analogy π¦
Think of a record as a perfectly sized, pre-labeled box for a specific set of items. If you want to ship a book and a pen, you get a "BookAndPen" box. It's exactly the right size, it's sealed (immutable), and everyone knows what's inside just by looking at the label (toString()).
A traditional class is like getting a generic, oversized box. You have to put the items in, write your own labels, and make sure you seal it properly yourself. It gets the job done, but it's a lot more work.
Switch Expressions and Pattern Matching
The Old Way: The Classic (and Clunky) switch Statement
The switch statement has been a part of Java since the beginning. It's a useful control flow statement for handling different cases based on the value of a variable. However, the traditional switch statement has a few quirks that can make it error-prone and verbose.
Let's say we want to get the day of the week as a string. Here's how we might do it with a classic switch statement:
// Pre-Java 12
DayOfWeek day = DayOfWeek.MONDAY;
String dayType;
switch (day) {
case MONDAY:
case TUESDAY:
case WEDNESDAY:
case THURSDAY:
case FRIDAY:
dayType = "Weekday";
break;
case SATURDAY:
case SUNDAY:
dayType = "Weekend";
break;
default:
throw new IllegalStateException("Invalid day: " + day);
}
System.out.println(dayType);The Problems: Verbosity, "Fall-Through," and No Return Value
This classic approach has a few drawbacks:
- Verbosity: There's a lot of boilerplate with all the
caseandbreakkeywords. - The "Fall-Through" Trap: If you forget a
breakstatement, the code will "fall through" and execute the code in the nextcaseblock, which is a common source of bugs. π - It's a Statement, Not an Expression: A
switchstatement doesn't return a value. You have to declare a variable (dayTypein this case) and assign to it within eachcaseblock. This is more verbose and can lead to situations where the variable might not be initialized if you forget acase.
Itβs like a choose-your-own-adventure book where if you don't explicitly stop at the end of a chapter (break), you accidentally continue reading into the next one, leading to a very confusing story.
The Solution: Modern switch Expressions! β¨
Starting with Java 12 and enhanced in later versions, switch was upgraded to be used as an expression. A switch expression can return a value, which makes the code much more concise and safer.
Here's the same logic using a switch expression:
// With switch expression (Java 14+)
DayOfWeek day = DayOfWeek.MONDAY;
String dayType = switch (day) {
case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "Weekday";
case SATURDAY, SUNDAY -> "Weekend";
};
System.out.println(dayType);Wow, what a difference! Let's break down the improvements:
- Returns a Value: The entire
switchblock is an expression that evaluates to a value, which is then assigned todayType. - Arrow Syntax (
->): The new arrow syntax is more concise. The code to the right of the arrow is what's returned. - No More
break! With the arrow syntax, there is no "fall-through." Only the code to the right of the arrow for the matching case is executed. This eliminates a whole class of bugs. - Multiple Labels per Case: You can group multiple cases together with commas, making the code even cleaner.
- Compiler-Enforced Completeness: A
switchexpression must be exhaustive. This means you must cover all possible cases. If you are switching on anenum, for example, and you miss one of the values, the compiler will give you an error. This makes your code safer. If adefaultcase is needed, it must be provided.
You can also use the traditional case ...: syntax with a new yield keyword if you need a block of code to compute the value.
String dayType = switch (day) {
case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "Weekday";
case SATURDAY, SUNDAY -> {
System.out.println("It's the weekend!");
yield "Weekend"; // 'yield' returns the value from the block
}
};Going Further: Pattern Matching for switch (and instanceof)
The evolution of switch didn't stop there. Java has been progressively adding pattern matching capabilities, which take switch to a whole new level.
The Problem Before Pattern Matching:
Imagine you have a variable of type Object and you want to do different things based on its actual type. Before pattern matching, you'd have to use a chain of if-else statements with instanceof and explicit casting.
// Before pattern matching
Object obj = "Hello";
if (obj instanceof String) {
String s = (String) obj; // Tedious cast
System.out.println("It's a string of length: " + s.length());
} else if (obj instanceof Integer) {
Integer i = (Integer) obj; // Another cast
System.out.println("It's an integer with value: " + i);
}This pattern of instanceof followed by a cast is clumsy and repetitive.
Pattern Matching for instanceof (Java 16+):
Java 16 streamlined this by allowing you to declare a new variable right in the instanceof check.
// With pattern matching for instanceof
Object obj = "Hello";
if (obj instanceof String s) { // 's' is declared and cast automatically
System.out.println("It's a string of length: " + s.length());
} else if (obj instanceof Integer i) {
System.out.println("It's an integer with value: " + i);
}If obj is a String, it's automatically cast and assigned to the new variable s, which is then available inside the if block. No more manual casting!
Pattern Matching for switch (Preview in recent Java versions):
This same power is being brought to switch statements and expressions, allowing you to switch directly on the type of an object.
// With pattern matching for switch
Object obj = 123;
String result = switch (obj) {
case String s -> "A string of length " + s.length();
case Integer i -> "An integer with value " + i;
case null -> "It's null";
default -> "It's some other type";
};
System.out.println(result);This is incredibly powerful and expressive. It combines the type check and the cast in a very clean and readable way, and it even allows for handling null as a distinct case.
Sealed Classes: Controlling Inheritance
The Problem: Unrestricted Inheritance
In standard object-oriented programming in Java, when you create a class, you can either make it final (so it can't be extended at all) or non-final (so any class can extend it). There was no middle ground.
Imagine you're designing a system to represent shapes. You might have a Shape class and some specific implementations like Circle, Square, and Rectangle.
public abstract class Shape {
// ... common shape properties and methods ...
}
public class Circle extends Shape { /* ... */ }
public class Square extends Shape { /* ... */ }The problem is that anyone, anywhere, could create a new class that extends Shape.
// Some other developer's code in a different part of the application
public class Pentagon extends Shape { /* ... */ }
public class BizarreShape extends Shape { /* ... */ }Sometimes this is what you want, but in many cases, especially when designing a library or a framework, you want to explicitly define the only possible subtypes of a class. You want to say, "A Shape can only be a Circle, a Square, or a Rectangle, and nothing else." This wasn't possible before.
This is like creating a board game with a set of specific character types (e.g., warrior, mage, archer). You don't want players to be able to introduce their own, undefined character types that don't follow the game's rules.
The Solution: sealed Classes to the Rescue! π°
Introduced in Java 15, sealed classes and interfaces give you fine-grained control over your inheritance hierarchy. By declaring a class as sealed, you can specify exactly which other classes are permitted to extend it.
Here's how you would define our Shape hierarchy using sealed classes:
// Using 'sealed'
public abstract sealed class Shape
permits Circle, Square, Rectangle {
// ...
}
public final class Circle extends Shape { /* ... */ }
public final class Square extends Shape { /* ... */ }
public non-sealed class Rectangle extends Shape { /* ... */ }Let's break this down:
sealed: TheShapeclass is marked assealed.permits: Thepermitsclause lists all the direct subclasses that are allowed:Circle,Square, andRectangle. Any attempt to create another class that extendsShapewill result in a compile-time error.
The Rules for Subclasses
The subclasses of a sealed class must follow one of three rules:
final: The subclass can be declaredfinal, meaning it cannot be extended further. This is the most common choice. (CircleandSquarein our example).sealed: The subclass can also besealed, which means it can be extended, but only by the classes itpermits. This allows you to create a more complex, multi-level sealed hierarchy.non-sealed: The subclass can be declarednon-sealed. This opens up the class for extension by any other class, returning to the "old way" of inheritance for that specific branch of the hierarchy. (Rectanglein our example).
This gives you a powerful way to design and model your domain with more precision.
sealed Classes and switch Expressions: A Perfect Match
One of the biggest benefits of sealed classes is how well they work with pattern matching in switch expressions. When you switch over a sealed class, the compiler knows all the possible subtypes.
This means that if you cover all the permitted subtypes in your case labels, you don't need a default clause. The compiler can verify that your switch is exhaustive.
Shape shape = new Circle(); // Assume Circle is a final class extending Shape
// The compiler knows all possible shapes, so no 'default' is needed!
double area = switch (shape) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Square s -> s.side() * s.side();
case Rectangle r -> r.length() * r.width();
// No default needed here!
};This is fantastic for maintainability. If you later add a new permitted subtype to Shape (e.g., Triangle), the compiler will show you an error in all the switch expressions that don't handle the new Triangle case. This prevents you from forgetting to update your logic.
A Fun Analogy π
Think of a sealed class as a royal family. The sealed King or Queen (Shape) can decree who is in the line of succession (permits Circle, Square, ...). The permitted heirs must then declare their own status:
- A
finalprince or princess: They are part of the family but will not have heirs of their own in this context. - A
sealedprince or princess: They will have their own designated line of succession. - A
non-sealedprince or princess: They have decided to leave the royal line, and their descendants can be anyone.
This controlled inheritance brings more structure and predictability to your code's kingdom!
π References for Extra Reading
- The
varKeyword: - Records:
- Switch Expressions and Pattern Matching:
- Sealed Classes:
Challenge
Challenge: Modern Notification System
You are tasked with building the core logic for a notification processing system using modern Java features. Your goal is to model different types of notifications and create a function that processes them based on their type.
Requirements:
- Define a
sealedinterface namedNotification. - This interface must permit exactly three implementing classes:
EmailNotification,SmsNotification, andPushNotification. - Implement all three permitted classes as
recordswith the following fields:EmailNotification:String recipient,String subject,String bodySmsNotification:String phoneNumber,String messagePushNotification:String deviceToken,String alert
- Inside the
NotificationProcessorclass, complete theprocessNotificationmethod. This method takes aNotificationobject as input and must return aString. - Your implementation of
processNotificationmust use aswitchexpression that leverages pattern matching to handle each notification type. - The method should return a formatted string based on the notification type:
- For
EmailNotification:"Email sent to [recipient]: [subject]" - For
SmsNotification:"SMS sent to [phoneNumber]: [message]" - For
PushNotification:"Push sent to [deviceToken]: [alert]"
- For
- Your
switchexpression should be exhaustive and should not require adefaultcase.
Expected result
Your solution should consist of a single Java file containing the NotificationProcessor class, the sealed interface Notification, and the three record implementations.
The final code should correctly define the sealed hierarchy, where Notification permits only the three specified record types. The processNotification method must use a modern switch expression with arrow syntax (->) and pattern matching to deconstruct the notification object and directly access its components to build the return string. Because the switch operates on a sealed type, the compiler can verify that all permitted subtypes are handled, making a default clause unnecessary and ensuring type safety at compile time.