Flat Preloader Icon

Java Nashorn

Nashorn is a JavaScript engine for the Java Virtual Machine (JVM) that was introduced in Java 8 as a replacement for the earlier Rhino JavaScript engine. Nashorn provides the capability to execute JavaScript code within a Java application, making it a useful tool for embedding JavaScript functionality and scripting into Java applications.

  • JavaScript Engine: Nashorn is a full-featured JavaScript engine that complies with the ECMAScript 5.1 standard. It allows you to execute JavaScript code directly from Java applications.
  • Integration: Nashorn is tightly integrated with the Java platform, which means you can seamlessly interact with Java classes, objects, and APIs from your JavaScript code.
  • Performance: One of Nashorn’s key improvements over Rhino is its superior performance. Nashorn uses just-in-time (JIT) compilation, which can make JavaScript execution faster than with the earlier Rhino engine.
  • Command-Line Tool: Nashorn provides a command-line tool called jjs that allows you to run JavaScript code from the command line.
  • Embeddable: You can embed Nashorn into your Java applications to execute JavaScript code, handle scripting tasks, and create extensible applications.

  • Here’s a basic example of using Nashorn to execute JavaScript code from a Java application:
    					import javax.script.ScriptEngine;
    import javax.script.ScriptEngineManager;
    import javax.script.ScriptException;
    public class NashornExample {
        public static void main(String[] args) {
            ScriptEngineManager engineManager = 
            new ScriptEngineManager();
            ScriptEngine engine = 
            try {
                // Execute JavaScript code
    ("var greeting = 'Hello, Nashorn!'; print(greeting);");
            } catch (ScriptException e) {
    In the example above, we use the javax.script package to create a ScriptEngine with the Nashorn engine. We then use engine.eval to execute a simple JavaScript code snippet, which prints “Hello, Nashorn!” to the console.

    Share on: