Have you ever needed to evaluate a Java class, or just perform some quick tests to see how a statement is working? Writing a full Java program just to test a single command might be a solution. A better one would be to use a REPL (Read Eval Print Loop) tool for an interactive test of Java constructs.

I’m going to write about the upcoming REPL tool of Java 9 soon. But before, I like to show how to perform this task with the recent Java 8   version.

The bad news: There is no REPL tool included.
The good news: Take Nashorn for your REPL experiments.

Nashorn is the JavaScript engine implemented with Java. It is included in the Java 8 JRE as well as the JDK.

You may start Nashorn at the command line. Even better, you might run it inside the NetBeans IDE, using the terminal window [1].

Although named Nashorn, the executable engine is jjs. You may remember this name as “Java JavaScript”. On Windows it is jjs.exe, but normally you start it without typing the extension.

To get in touch with Nashorn, we’ll invoke it, print a HelloWorld from Java and quit.

Nashorn seesion in NetBeans terminal window

Nashorn seesion in NetBeans terminal window

If no path links to jjs, we need to start it by typing the full path. You need to adopt the path to your environment.

c:/Program\ Files/Java/jdk1.8.0_74/bin/jjs.exe

At the command prompt we get, we can invoke JavaScript commands. It is quite easy to perform a printout. Because we want a kind of REPL for Java, we’re going to use Java’s System class to perform the print. This is a bit more of work, but we can use the same principle to invoke other Java statements of our interest.

First thing we need to do, is to import the needed Java class and assign it to a JavaScript variable.

var system = Java.type("java.lang.System")

Once the Java class is assigned to that var, you can invoke its methods.

system.out.println ("Hello from Java")

To finish Nashorn simply type

quit()

In my book Java Lambdas and (parallel) Streams [2], I show different tasks to query data by Lambda statements. In the next part of this short series, I’m going to show, how to create the example data and then interactively querying it.

Stay tuned!

 

[1] blog.mueller-bruehl.de/netbeans/netbeans-and-terminal-window

[2] leanpub.com/lambdas