Java 23 brings couple of new features to developers, most of which are still in preview, allowing us to test them before they are officially adopted. This blog will walk you through some of these features, highlighting the potential improvements and how they can simplify our day-to-day coding experience. Don’t forget, to compile and run these features, you need to use the --enable-preview flag.
Let’s dive in!
Feature 1: Markdown in JavaDoc – JEP 467
Traditionally we have been using HTML to format JavaDoc comments. But now, with Java 23, we can use Markdown to write JavaDoc comments. This allows developers to format and style JavaDoc comments more efficiently with less verbosity.
To use Markdown, we should start all lines of JavaDoc comment with three slashes. For example
/// **Calculate Square**
/// This method calculates the square of a given number.
///
/// **Parameter:**
/// - `number`: The number to be squared.
///
/// **Returns:**
/// The square of the provided number.
int calculateSquare(int number) {
return number * number;
}
Feature 2: Import an entire module (Preview) – JEP 476
One of the new features in Java 23 is the ability to import an entire java module. Traditionally, you would have to import each required package or class explicitly (except java.lang). Now, with this module-wide import, all classes from a module are available without needing individual imports.
For example, we can import the complete java.base module and use classes from this module (like List, Map, Collectors, etc) without needing individual imports.
import module java.base;
...
List<String> names = List.of("John", "Jennie", "Jim", "Jack", "Joe");
Class Name Ambiguity
If two imported modules have the same class name, then compilation results in error. For example, class Date is present in both java.base and java.sql. So if you import both modules, it results in compilation error. To resolve the compilation error, import the desired Date class with package name.
import module java.base;
import module java.sql;
import java.util.Date; //removal of this import results in compilation error
Date date = new Date();
Feature 3: Primitive Types in Patterns, instanceof and switch (Preview) – JEP 455
So far, instanceof works well with object and not all with primitives. And switch works well with objects and to some extend with primitives. With Java 23, all primitive types can now also be used in pattern matching – both in instanceof and switch
long y = 100;
if (y instanceof short s) {
println(s + " is a short");
}
double value = ...
switch (value) {
case byte b -> println(value + " instanceof byte: " + b);
case short s -> println(value + " instanceof short: " + s);
}
Apart from these features, several preview and incubator features are presented again in Java-23 with no/minor changes. Few of them worth mentioning