Java 8 : Nashorn JavaScript Engine

Java 8 introduced a new Nashorn Javascript Engine to replace existing Rhino. Nashorn Javascript engine provides 2 to 10 times better performance and it directly compiles the code in memory and passes the bytecode to JVM. Nashorn JavaScript Engine enhanced version of javax.script.ScriptEngine and follows the same set of rules, permitting for Java and JavaScript interoperability.

Points to remember

  • Use jjs command to run Javascript through Nashhorn Engine.
  • The class name for the Nashorn Javascript engine is jdk.nashorn.api.scripting.NashornScriptEngine.

Exmaple: Nashorn JavaScript Engine

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class NashornEngineTest {

	public static void main(String[] args) {
		try {
			ScriptEngineManager manager = new ScriptEngineManager();
			ScriptEngine engine = manager.getEngineByName("JavaScript");

			System.out.println(engine.getClass().getName());
			System.out.println("Result:"
					+ engine.eval("function increment() { return 1; }; increment() + 1;"));
		} catch (ScriptException ex) {
			ex.printStackTrace();
		}

	}

}

Output


jdk.nashorn.api.scripting.NashornScriptEngine
Result:2.0

References