Search

Dark theme | Light theme
Showing posts with label Java 21. Show all posts
Showing posts with label Java 21. Show all posts

September 11, 2025

Java Joy: Return Default Value For Null Value

Since Java 9 the methods requireNonNullElse and requireNonNullElseGet are part of the java.util.Objects class. The method requireNonNullElse accepts two arguments. The first argument is an object that will be returned if that object is not null. The second argument is an object to be returned when the first argument is null. With this method you can replace the following ternary operator if (a != null) ? a : b (or if (a == null) ? b : a) with Objects.requireNonNullElse(a, b).
The method requireNonNullElseGet allows to define a Supplier function as second argument. The Supplier is only invoked when the first argument is null, so it is lazy and will only be invoked when the first argument is null.

October 8, 2024

Java Joy: Using JShell With Standard Input

The Java Development Kit (JDK) includes a tool called jshell that can be used to interactively test Java code. Normally we run jshell and type Java code to be executed from an interactive shell. But we can also use jshell as a tool on the command line to accept standard input containing Java code to be executed. The output of the code can be used as input for another tool on the command line. We run jshell - to run jshell and accept standard input. The simplest way to pass Java code to jshell is to use echo to print the Java code to standard output and pipe it to jshell.

The following example shows how to use jshell and echo to get the default time zone of our system:

$ echo 'System.out.println(TimeZone.getDefault().getID());' | jshell -
Europe/Amsterdam

In the following example we fetch all Java system properties using jshell and then use grep to find the system properties with file in the name:

$ echo 'System.getProperties().list(System.out)' | jshell - | grep file
file.separator=/
file.encoding=UTF-8

The next example uses multi-line standard input:

$ jshell - << EOF
int square(int n) {
    return n * n;
}

IntStream.range(1, 10).map(n -> square(n)).forEach(System.out::println);
EOF

1
4
9
16
25
36
49
64
81

Written with Java 21.0.4.