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.