Java 21 – Java 21 features with example

By | October 10, 2023

The new version of Java, Java 21, is finally released on September 19, 2023, as the next long-term support (LTS) version. Because of this LTS version, it will be used in commercial support as the next stable version.

Java 21
Fig 1- JDK 21 LTS version

After working on a total of 2585 JIRA issues, of which 1868 were resolved by Oracle and the other 717 were completed by other members of the Java community, Oracle has released JDK 21 with the following 15 new features:

  • String Templates (JEP 430)
  • Sequenced Collections (JEP 431)
  • Generational ZGC (JEP 439)
  • Record Patterns (JEP 440)
  • Pattern Matching for switch (JEP 441)
  • Foreign Function & Memory API (JEP 442)
  • Unnamed Patterns and Variables (JEP 443)
  • Virtual Threads (JEP 444)
  • Unnamed Classes and Instance Main Methods (JEP 445)
  • Scoped Values (JEP 446)
  • Vector API (JEP 448)
  • Deprecate the Windows 32-bit x86 Port for Removal (JEP 449)
  • Prepare to Disallow the Dynamic Loading of Agents (JEP 451)
  • Key Encapsulation Mechanism API (JEP 452)
  • Structured Concurrency (JEP 453)

Download and Install Java 21

We can download and install the latest version of Java, JDK 21, from the Oracle Official Page. After installation, make sure to update the environment variable for JDK 21. We can check the current installed Java version and the JDK path using the following commands:

Java Version in CMD

BAT (Batchfile)
::To check Java version
java -version

::To check the path for jdk version
echo %JAVA_HOME%

Below is the output for the above commands:

How to check java version and path in CMD
Fig 2- Java: version and path in CMD

Java 21 features with examples

Let us understand a few of Java 21 new features with examples that were introduced in JDK 21.

Java 21 String Template

The string template contains embedded expressions that are evaluated at runtime. Similar to other programming languages, such as Python, etc. Java, in its latest version, JDK 21, also came with a string template feature.

  • String templates containing embedded expressions (evaluated at runtime).
  • A string can now contain variables, methods, or fields commutated at runtime.
Python
f"Hello{ name }!"

In an earlier version of Java, we needed to use concatenation to concatenate variables with strings.

Java
/**
 * Jdk-21 features
 * String Template Example
 * @author paulsofts
 */
public class Main {

	public static void main(String[] args) {
		/**
		 * Concatenation to concatenate variables with strings.
		 */
		int emp_id = 1303579;
		String emp_name = "Ankur";
		System.out.println("Employee Id: " + emp_id + "|" + "Employee Name: " + emp_name);
	}
}

The above program will have the following output:

String Concatenation
Fig 3- String concatenation

How to use String template in Java 21?

The string template is a preview feature, which means by default it is disabled. Its development has been successfully completed, but it is only available as a preview feature, which means it has been distributed for testing purposes. It may or may not be removed from Java 21.

Java
/**
 * Jdk-21 features
 * String Template Example
 * @author paulsofts
 */
public class Main {

	public static void main(String[] args) {
		/**
		 * Concatenation to concatenate variables with strings.
		 */
		int emp_id = 1303579;
		String emp_name = "Ankur";
		System.out.println("Employee Id: " + emp_id + "|" + "Employee Name: " + emp_name);
		
		/**
		 * String templates to concatenate variables with strings.
		 */
		System.out.println(STR."Employee Id: \{emp_id} |  Employee Name: \{emp_name}");
	}
}

The above program will give a compilation error as, by default, the String template feature is disabled.

String Template
Fig 4- String Template compilation error

How to enable String Template preview feature?

We will first compile our application using the standard Java compilation command and do the required steps as asked.

Fig 5- String Template: Compilation issue

As we can see above, it asked us to use the –enable-preview command.

String Template --enable-preview command
Fig 6- String Template: –enable-preview command

Now, it is asking us to enter the source or release version of JDK that we are trying to use in order to enable the preview feature.

Fig 7- String Template: Compiled successfully

As we can see above, our program compiled successfully. In a similar way, now we have to run our program, and we will have the following output:

String Template
Fig 8- String Template: Output

Java 21 Unnamed Patterns and Variables

Unnamed patterns and variables are also a preview feature. The unnamed pattern is used to match a record component without declaring the component’s name or its type, and unnamed variables are those that are not being used in the program. In Java 21, both can be replaced by an underscore (_) character. For example, in a try-catch block, we have catch (Exception e); sometimes, we never use this Exception variable e, and it can be replaced by an underscore character. In a similar way, we can use it in a lambda expression or switch statement when a variable is there but we are not using it.

Unnamed Variable in Java 21
Fig 9- Unnamed Variable Example

In the above program, we have the exception variable e, which is not being used anywhere in our program. In Java 21, it can be replaced by an underscore character (_).

Java
/**
 * Jdk-21 features
 * Unnamed Patter and Variable
 * @author paulsofts
 */
public class Main {

	public static void main(String[] args) {
		int num = 100;
		try {
			double res = num/0;
			System.out.print(res);		
		}catch(Exception _) {
			System.out.println("We can not divide a number by 0");
		}
	}
}

Below, we can see we are getting compilation errors in the IDE as it is a preview feature.

Fig 10- Unnamed variable output

Above, we replaced the exception variable e with the underscore character (_), and our program ran successfully. Make sure to use the –enable-preview method to compile and run the program, as it is a preview feature.

Java 21 Unnamed classes and Instance variable

We already have unnamed modules and packages. In the below program, we can see we are using the System.out.print() statement, in which the System class is coming from the java.lang package. We have not imported it, but we are still able to use it.

Java
/**
 * Jdk-21 features
 * Unnamed Classes and Instance Variable
 * Unnamed module and packages are already there in Java
 * 
 * @author paulsofts
 */
public class Main {

	public static void main(String[] args) {
		System.out.print("paulsofts...");
	}
}

In Java 21, we can now have unnamed classes as well. i.e., class without name. Although currently it is also a preview feature, In the below program, we have a class without a name.

Java
/**
 * Jdk-21 features
 * Unnamed Classes and Instance Variable
 * 
 * @author paulsofts
 */
	void main(String[] args) {
		System.out.print("paulsofts...");
	}

Below is the implementation for the above program.

Unnamed classes in Java 21
Fig 11- Unnamed classes and Instance variable

Java 21 Sequenced Collection

A new interface SequencedCollection<E> is introduced in JDK 21 for sequenced order. It will be used as an enhancement with the Collection framework. In this interface, a few new methods are added along with the methods promoted by Deque.

Java
interface SequencedCollection<E> extends Collection<E> {
    // new method
    SequencedCollection<E> reversed();
    // methods promoted from Deque
    void addFirst(E);
    void addLast(E);
    E getFirst();
    E getLast();
    E removeFirst();
    E removeLast();
}

Let’s implement and understand each of the methods of the SequencedCollection<E> interface.

Java
import java.util.*;

/**
 * Jdk-21 features
 * Sequenced collection
 * 
 * @author paulsofts
 */
public class Main{
	
	public static void main(String[] args) {
		
		List<String> list = new ArrayList<>();
		/**
		 * methods promoted from Deque
		 */
		list.addFirst("First element");
		list.addLast("Last element");
	
		System.out.println(list);
		
		System.out.println(list.getFirst());
		System.out.println(list.getLast());
		System.out.println(list.reversed());
		
		list.removeFirst();
		System.out.println(list);
		
		list.removeLast();
		System.out.println(list);
	}
}

Output:

Sequenced Collection in Java 21
Fig 12- Java 21: Sequenced Collection interface

Java 21 Record Patterns

Record classes are a special type of class that are used as the immutable carrier of the data, just like the POJO classes, and are developed to reduce boilerplate code. The record patterns are used to deconstruct the record values.

Java
/**
 * As of Java 16
 */
record Point(int x, int y) {}

static void printSum(Object obj) {
    if (obj instanceof Point p) {
        int x = p.x();
        int y = p.y();
        System.out.println(x+y);
    }
}

/**
 * As of Java 21
 */
static void printSum(Object obj) {
    if (obj instanceof Point(int x, int y)) {
        System.out.println(x+y);
    }
}

In the below example, we will create a record class for employees and use the Record pattern feature from Java 21 to understand it.

Java
/**
 * Jdk-21 features Record Patterns
 * 
 * @author paulsofts
 */

public class Main {

	static void testEmployee(Object obj) {
		if (obj instanceof Employee(int empId, String empName)) {
			//de-constructing the values of employee
			System.out.println("EmpId: " + empId + " | " + "EmpName: " + empName);
		}
	}

	public static void main(String[] args) {
		testEmployee(new Employee(1001, "Bhoomika"));
	}
}
/**
 * Record class for Employee
 */
record Employee(int empId, String empName) {

}

The output for above program:

Record Patterns in Java 21
Fig 13- Java 21: Record Pattern

Is Java 21 LTS or not?

Java 21 is an LTS version, i.e., a long-term support version, and hence used for commercial enterprise support.

Leave a Reply

Your email address will not be published. Required fields are marked *