Until Java SE 7, JDKs shipped with a JavaScript scripting engine based on Mozilla Rhino. Java SE 8 instead ship with a new engine called Oracle Nashorn, which is based on JSR 292 and invoke dynamic.

JDK 1.8 provides us the “$JAVA_HOME/bin/jjs” command-line tool as well as using Oracle Nashorn as an embedded scripting engine inside Java applications.

Many people do not like why JDK 8 is focusing more on the Java Scripting and why so much effort is being put on the JavaScript engine like Nashorn. Will it kill java? Introducing such features will harm java? Is it poisonous for java?

Other parts of this article an be found at:

JDK8 Based Nashorn JavaScript & Java to interact with MySQL Database. (part-2)

Server Side Java Script Nashorn, WildFly10, Undertow with MySQL (part-3)

Different people may have different opinion about it however here we will talk about how to use it and how to take benefit from it.

Why Nashorn? Any benefits/advantages?

Many people have a question in mind that why Nashorn has been introduced and What is important in it? What are the advantages of using it ?

1. Nashorn fully supports ECMAScript 5.1 specification along with some extensions, to 100% pure Java implementation and 100% complied to bytecode and not the interpreted mode as with Rhino. Simply Nashorn scripts do not need to be compiled.

2. Nashorn provides much better performance than Rhino engine.

2. Nashorn will support the javax.script (JSR 223) API. The javax.script (JSR 223) API is for calling back into JavaScript from Java.

2. It directly compiles the JavaScript code in-memory and passes the Java bytecode to the JVM, and uses invokedynamic which provides backward compatibility to JDK7 – See more at: http://www.nagarro.com/de/de/blog/post/33/Java-8-Nashorn-Engine-for-JavaScript-Interoperability-and-Performance

3. Nashorn provides a flexibility to the users that they can either programmatically use it from Java programs or they can utilize it from the command line tool “jjs” which is located in “$JAVA_HOME/bin” directory.

4. Unlike Rhino, which has its own JavaScript debugger, The Nashorn does not provide it’s own JavaScript debugger but it provides an ability to remotely debug applications using an IDE like IntelliJ IDEA 13.

5. It provides much faster execution and multi-threading of JavaScript while running in Java’s JRE.

6. Nashorn can be very easily integrated and used with JavaFX. Users can very easily interpret a JavaFX script application with Nashorn using the jjs command with the -fx option. See: http://docs.oracle.com/javase/8/docs/technotes/guides/scripting/nashorn/javafx.html

7. Nashron can help in executing the OS level commands very easily like following:

    var lines = `ls -ls`.split("\n");
    for each (var line in lines) {

8. With Nashorn it will support in invoking Java code from JavaScript and for Java to invoke JavaScript code.

9. So far no security risk or exposure has been identified with Nashorm.

Some simple startup demos

Lets start writing very simple javascipts statements and then execute these statements using the Nashorn and the “jjs” jjs command-line tool.
As JDK8 is needed to be present in the PATH so lets setup the environment first. Following are the steps for setting the JDK8 installation in the PATH in order to use the “jjs” utility.

Unix Based OS

export JAVA_HOME=/PATH/TO/jdk1.8.0_60
export PATH=$JAVA_HOME/bin/jjs:$PATH

Windows Based OS

set JAVA_HOME=C:\jdk1.8.0_60

Printing messages …

Once the environment is setup we can simply use the “print” function to display some messages on the jjs tool. Just type “jjs” in the command prompt to start this utility.

$ jjs
jjs> print ("What's New in MiddlewareMagic ? ");
What's New in MiddlewareMagic ? 


Running jjs in “scripting” mode

“jjs” tool provides us an option “-scripting” using this we can run the OS specific commands as well as part of our scripts. For example listing the files or copy/moving a file or directory…etc.

$ jjs
jjs> var listing = `ls -l`
ECMAScript Exception: SyntaxError: <shell>:1:14 Expected an operand but found error
var listing = `ls -l`

As we did not start the jjs utility with the “-scripting” option hence it is not able to recognize those OS commands and failing as mentioned above. So not we will start it with this option.

$ jjs -scripting

jjs> var listing = `ls -l`
jjs> print(listing);
total 64

drwx------+ 27 jsensharma  XXXX\Domain Users   918 Nov 24 15:19 Desktop
drwx------+ 41 jsensharma  XXXX\Domain Users  1394 Nov 19 16:24 Documents
drwx------+ 31 jsensharma  XXXX\Domain Users  1054 Nov 26 17:01 Downloads
drwx------@ 57 jsensharma  XXXX\Domain Users  1938 Nov 26 16:36 Library
drwxr-xr-x   7 jsensharma  XXXX\Domain Users   238 Nov  3 18:38 MiddlewareMagicDemos

jjs> print(`date`);
Fri Nov 27 11:11:23 IST 2015

Running a Nashorn script

It is also possible that we can combine the different functions as part of a java script file and then execute it by passing the file to the “jjs” command line tool as following:
Suppose we created a file with name “test.js” in the current directory as following:

//###### Simple JavaScript with some functions. ##
// Declaring a simple function.
function sayHello(a) { 
		return "Hello, "  + a; 

//###### Invoking the function sayHelo()   ##
var result = sayHello('MiddlewareMagic');
print("\n\t\t sayHello returned: " + result + "\n"); 

Once the above file is saved then we can execute it simply by passing the file to the “jjs” utility as an argument:

$ jjs /PATH/TO/test.js 

		 sayHello returned: Hello, MiddlewareMagic

Using Java API inside the JavaScript

Now lets read a file using the script and display it’s content in the jjs terminal. Suppose we want to read a file “/PATH/TO/module.xml” and then we also want to print its content in the jjs terminal.

$ jjs

jjs> var moduleFile = "/PATH/TO/module.xml";

jjs> var fileData = new java.lang.String(java.nio.file.Files.readAllBytes(java.nio.file.Paths.get(moduleFile)));

jjs> print(fileData)

Similarly we can also use some other Java APIs while using the above script like if we want to display the current date/time using the “java.util.Calendar” API then we can do the same as following:

jjs> print(java.util.Calendar.getInstance().getTime());

Fri Nov 27 11:08:32 IST 2015

Using JavaScript inside the Java code

In the above sample we have seen how to use the Java APIs inside the javascript , Now we will see how we can invoke a Java Script snippet or the java script functions inside a java code. The Java8 introduced us few new APIs which we need to use in order to achieve the same.
We will be using the “javax.script.ScriptEngineManager” and “javax.script.ScriptEngine” APIs here to invoke/execute javascript functions in java.

Lets create a simple Java Code “ExampleNashorn.java” in some directory as following:

import javax.script.*;
import java.io.*;

public class ExampleNashorn {
	public static void main(String ar[]) throws Exception {
		ScriptEngineManager enginManager = new ScriptEngineManager();
        // This method takes one String argument with the name of the script engine. 
        // To get an instance of the Nashorn engine, pass in "nashorn". 
        // Alternatively, you can use any of the following: 
        // "Nashorn", "javascript", "JavaScript", "js", "JS", "ecmascript", "ECMAScript".
        // Creating a Java Script Engine
		ScriptEngine engine = enginManager.getEngineByName("Nashorn");
		try {
            //// Directly executing JavaScript snippet: ////
		    final String rawJavaScript =  "print(java.lang.System.getProperty(\"java.home\"));" +
                                          "var Date = Java.type(\"java.util.Date\");" +
                                          "var dt = new Date(); " +
                                          "print('dt = ' + dt);";

		    //// Mixing Java and JavaScript  ////
			engine.put("a", new Integer(ar[0]));
			engine.put("b", new Integer(ar[1]));
			engine.eval("var c = (a+b);");
			System.out.println("Sum : " + ((Number)engine.get("c")).intValue());

			//// Executing a simple java script file ////
			FileReader javaScriptFileReader = new FileReader(new File("test.js"));

		} catch(final ScriptException se) {

In the above sample java code we have seen the following things:
1. Directly executing JavaScript snippet form Java code.
2. Mixing Java and JavaScript
3. Executing a simple java script file using java “engine.eval” API.

Now lets run the above code simply by passing the two arguments so that it can add those numbers.

$ javac ExampleNashorn.java 

$ java ExampleNashorn 100 200


dt = Fri Nov 27 11:26:32 IST 2015

Sum : 300

		 sayHello returned: Hello, MiddlewareMagic

The Source code of this demo can be found in the following repository.
Enjoy MiddlewareMagic
Jay SenSharma

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.