Java21 Features you must know.

Vikas Taank
4 min readDec 29, 2023

--

String Templates

String templates in Java allows embedding of literal text with expression in Java and this has been introduced as a Preview Feature.

The motivation of String templates are:

  1. Allows embedding expressions directly with in a string.
  2. Improves readability.
  3. A better much safer approach to string concatenation.
  4. Reduce the usage of String Builder.

Consider Below Example without String Template:

String name = "Duke";
String message = "My name is"+ name;

Using String Template:

String name = "Duke";
String info = STR."My name is \{name}";
System.out.println(info);
//My name is Duke

The template processor STR is one of the template processors that’s included in the JDK. It automatically performs string interpolation by replacing each embedded expression in the template with its value, converted to a string. The JDK includes two other template processors:

  • The FMT template processor.
  • The Raw template processor.

Another Example from Oracle.

String user = "Duke";   
char option = 'b';
String choice = STR."\{user} has chosen option \{option}";
System.out.println(choice);
//Duke has chosen option b

Virtual Threads

Virtual threads are light weight efficient alternative to the threads in Java. Virtual threads helps in creating highly concurrent application and this is the part of the Project Loom. The main characteristic of the virtual threads are:

  1. Virtual threads are light weight as opposed to the platform or kernel threads. They are cheap to create and destroy and millions of threads can be created to execute tasks concurrently.
  2. Virtual thread simplifies the concurrent programming model.
  3. Virtual threads are managed by Java virtual machine and not the underlying operation thread.
  4. There is no one to one mapping between virtual thread and OS thread.
  5. JVM can handle large number of virtual threads with limited number of OS threads.
  6. Virtual threads perform better even at high I/O operations.

How Virtual Threads Work

  1. In a server application , a thread is created per request basis which is not scalable and that leads to overhead of context switching and thread creation. With light weight nature of the Virtual threads, this is significantly reduced.
  2. JVM can use very small number of OS thread in order to create multiple Virtual threads which increased efficiency and helps in parallelizing multiple requests.
  3. When a virtual thread blocks it is suspended by the JVM and the carrier thread is able to run other virtual threads.

Creating virtual threads.

import java.lang.Thread;

public class VirtualThreadExample {
public static void main(String[] args) {
Thread thread = Thread.startVirtualThread(() -> {
System.out.println("This is a virtual thread!");
// Your task here
});
thread.join(); // Optional: Wait for the virtual thread to finish
}
}

Using Builder Factory Method:

import java.lang.Thread;

public class VirtualThreadExampleFactory {
public static void main(String[] args) throws InterruptedException {
Thread thread = Thread.ofVirtual().unstarted(() -> {
System.out.println("This is a virtual thread created using Thread.Builder!");
// Your task here
});
thread.start();
thread.join(); // Wait for the virtual thread to finish
}
}

Record Templates:

Record patterns in Java, introduced as part of Project Amber, are a feature aimed at enhancing the language’s pattern matching capabilities, particularly for record types.

Record patterns extend the Record functionality by providing pattern matching and deconstruction of record values.

For example let’s Consider a Record.

public record Employee(String name x, double  salary) {}

Lets Deconstruct and pattern match an Employee Record

Employee employee = new Point("Vikas", 3456.89);

if (employee instanceof Employee(String name, double salary)) {
System.out.println("Name : " + name+ ", Salary: " + salary);
}

Usage in Switch Expression:

String details = switch(employee) {
case Employee(String name, double salary) when salary> 2000.89-> "Employee is Manager";
case Employee(String name, double salary) -> "Employee is (" + name+ ", " salary+ + ")";
default -> "Unknown Employee";
};

Pattern Matching for Switch Statements:

Key Aspects of Pattern Matching for Switch

  1. Switch case can match the pattern now instead of just matching the constant value.
  2. Reduce boilerplate code like if-else-if statements.
  3. More expressive and readable code.
  4. Eliminate type casting using instanceOf.

Lets look at the below example:

if (object instanceof String) {
String s = (String) obj;
// Handle string case
} else if (obj instanceof Integer) {
Integer i = (Integer) obj;
// Handle integer case
} // and so on...

Now lets use the Pattern Matching for the Switch Statement.

switch (object) {
case String s -> // Handle string case
case Integer i -> // Handle integer case
// and so on...
default -> // Handle the default case
}

Lets Look at the record.

public record Point(int x, int y) {}
public class SwitchPatternMatchingExample {
public static void main(String[] args) {
Object obj = // ... some object

String result = switch (obj) {
case String s -> "String of length " + s.length();
case Integer i -> "Integer with value " + i;
case Point p && p.x == p.y -> "Same X,Y Cooridinates "
case Point p-> "Point with X Axis " + r.x + " and Y Axis " + p.y;
default -> "Unknown object";
};

System.out.println(result);
}
}

Lets look at an ENUM example:

public enum TrafficLightsColors {
RED, YELLOW, GREEN;
}

Lets Look at the Switch Statement:

public class TrafficLightColorExample {
public static void main(String[] args) {
TrafficLightsColors light = // some value from TrafficLight enum

String action = switch (light) {
case RED -> "Stop";
case YELLOW -> "Prepare to stop";
case GREEN -> "Go";
};

System.out.println("The light is " + light + ": " + action);
}
}

There are other significant Java 21 features and you can find the detailed list in the reference below. Please share and clap if you liked my content.

References:

https://docs.oracle.com/en/java/javase/21/language/string-templates.html#GUID-0D9CC931-454D-4A57-9943-18C2464EEBCC

--

--

Vikas Taank

I am new to Medium, trying to articulate my learnings so far . Please Join medium to read my articles. Please support- https://ko-fi.com/vikastaank