Clean • Professional
The Nashorn JavaScript Engine is one of the most interesting features introduced in Java 8. It allows developers to execute JavaScript code directly inside Java applications, making Java more flexible and dynamic.
Nashorn is a JavaScript engine written in Java that runs on the JVM (Java Virtual Machine).
In simple terms: It enables you to run JavaScript code from Java programs and even interact with Java objects using JavaScript.
Before Java 8, Java used the Rhino JavaScript engine, which had several limitations:
👉 Nashorn solved these problems by:
Java provides the Scripting API (javax.script) to interact with Nashorn.
Step 1: Create Script Engine
ScriptEngine engine = new ScriptEngineManager()
.getEngineByName("nashorn");
Step 2: Execute JavaScript Code
engine.eval("print('Hello from JavaScript')");
Output:
Hello from JavaScript
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class NashornExample {
public static void main(String[] args) throws Exception {
ScriptEngine engine = new ScriptEngineManager()
.getEngineByName("nashorn");
engine.eval("print('Hello Nashorn')");
}
}
You can run .js files inside Java.
engine.eval(new FileReader("script.js"));
This is where Nashorn becomes powerful.
1. Calling Java Code from JavaScript
engine.eval("var ArrayList = Java.type('java.util.ArrayList');");
engine.eval("var list = new ArrayList();");
engine.eval("list.add('Java'); print(list);");
👉 JavaScript is using Java classes directly.
2. Calling JavaScript Function from Java
import javax.script.*;
ScriptEngine engine = new ScriptEngineManager()
.getEngineByName("nashorn");
engine.eval("function greet(name) { return 'Hello ' + name; }");
Invocable invocable = (Invocable) engine;
String result = (String) invocable.invokeFunction("greet", "Amit");
System.out.println(result);
Output:
Hello Amit
Java → JavaScript
engine.put("x", 10);
engine.eval("print(x + 5)");
JavaScript → Java
Object result = engine.eval("10 + 20");
System.out.println(result);
Java 8 provides a command-line tool called jjs.
Run JavaScript file:
jjs script.js
Interactive Mode:
jjs
Nashorn was used in:
| Feature | Nashorn | Modern Tools |
|---|---|---|
| Status | Deprecated | Actively maintained |
| JS Support | Limited | Full ES6+ |
| Performance | Good | Better |
| Use Case | Embedded scripting | Full JS apps |
The Nashorn JavaScript Engine was a powerful addition to Java 8 that enabled seamless integration between Java and JavaScript.
It helped developers:
Even though it’s deprecated today, it remains an important concept for interviews and understanding Java evolution.