Nashorn JavaScript Engine in Java with Examples

Nashorn: Nashorn is a JavaScript engine which is introduced in JDK 8. With the help of Nashorn, we can execute JavaScript code at Java Virtual Machine. Nashorn is introduced in JDK 8 to replace existing JavaScript engine i.e. Rhino. Nashorn is far better than Rhino in term of performance. The uses of invoking dynamic feature, conversion of JavaScript code into the bytecode directly into the memory etc makes the Nashorn more famous in JDK 8. We can execute JavaScript code by using the command-line tool and by embedding the JavaScript code into Java source code.

Executing JavaScript code by using console: For Nashorn engine, Java 8 introduced one new command-line tool i.e.jjl. We have to follow the below steps to execute JavaScript code through the console:

  • Create one file named with geeks.js.
  • Open geeks.js and write following code into the file and save it.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    var gfg= function(){  
        print("Welcome to Geeksforgeeks!!!");  
    };  
    gfg(); 

    chevron_right

    
    

  • Open CMD, write jjl geeks.js and press enter. It will generate the below output:
    Welcome to Geeksforgeeks!!!
    

Executing JavaScript file by embedding JavaScript file into Java code: We can execute JavaScript file by embedding JavaScript file into Java code with the help of ScriptEngine class. ScriptEngine class is introduced in JDK 6. By the help of the ScriptEngine class, we can create a JavaScript engine and with the JavaScript engine, we can execute the javaScript file.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Program to illustrate embedding
// of JavaScript file into Java code
  
import javax.script.*;
import java.io.*;
  
public class Geeksforgeeks {
    public static void main(String[] args)
        throws Exception
    {
  
        // Here we are generating Nashorn JavaScript Engine
        ScriptEngine ee = new ScriptEngineManager()
                              .getEngineByName("Nashorn");
  
        // Reading JavaScript file create in first approach
        ee.eval(new FileReader("geeks.js"));
    }
}

chevron_right


Output:



Welcome to Geeksforgeeks!!!

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Program to illustrate embedding
// of JavaScript code into Java code
  
import javax.script.*;
import java.io.*;
  
public class Geeksforgeeks {
    public static void main(String[] args)
        throws Exception
    {
  
        // Here we are generating Nashorn JavaScript Engine
        ScriptEngine ee = new ScriptEngineManager()
                              .getEngineByName("Nashorn");
  
        // Instead of reading JavaScript code from a file.
        // We can directly paste the JavaScript
        // code inside Java Code
        ee.eval("print('Welcome to Geeksforgeeks!!!"
                + " Executing JavaScript code with the"
                + " help of Nashorn engine');");
    }
}

chevron_right


Output:

Welcome to Geeksforgeeks!!! Executing JavaScript code with the help of Nashorn engine

Apart from above, with the help of Nashorn JavaScript Engine, we can perform multiple operations like:

  1. Providing JavaScript variable from Java Code: Suppose we have one JavaScript file name with geeks.js and geeks.js requires one variable during execution. With the help of Nashorn, we can pass the variable to JavaScript file from java code.

    Example 1: geeks.js file, which needs name variable to get executed

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // JavaScript file name with geeks.js
    print("Welcome to Geeksforgeeks!!! Mr. "+name);  

    chevron_right

    
    

    Example 2: Java code providing name variable to the JS file

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Program to illustrate passing of variable
    // from java code to javascript file
      
    import javax.script.*;
    import java.io.*;
      
    public class Geeksforgeeks {
        public static void main(String[] args)
            throws Exception
        {
            ScriptEngine ee
                = new ScriptEngineManager()
                      .getEngineByName("Nashorn");
            Bindings bind
                = ee.getBindings(
                    ScriptContext.ENGINE_SCOPE);
            bind.put("name", "Bishal Kumar Dubey");
            ee.eval(new FileReader("geeks.js"));
        }
    }

    chevron_right

    
    

    Output:

    Welcome to Geeksforgeeks!!! Mr. Bishal Kumar Dubey
    
  2. Calling JavaScript function from Java code: We can call JavaScript function from Java code with the help of Nashorn. Suppose we create one file name with geeks.js and the file contains two functions like below:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // JavaScript file name with geeks.js
      
    var func1 = function(){  
        print("Simple JavaScript function!!!");  
    }  
      
    var func2 = function(reader){  
        print("Hello "+reader);  
    }  

    chevron_right

    
    

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Program to illustrate calling of
    // JavaScript function from Java code
      
    import javax.script.*;
    import java.io.*;
      
    public class Geeksforgeeks {
        public static void main(String[] args)
            throws Exception
        {
            ScriptEngine ee
                = new ScriptEngineManager()
                      .getEngineByName("Nashorn");
            ee.eval(new FileReader("geeks.js"));
            Invocable invocable = (Invocable)ee;
      
            // Here we are calling func1
            invocable.invokeFunction("func1");
      
            // Here we are calling func2
            // as well as passing argument
            invocable.invokeFunction("func2",
                                     "Bishal Kumar Dubey");
        }
    }

    chevron_right

    
    

    Output:

    Simple JavaScript function!!!
    Hello Bishal Kumar Dubey
    

full-stack-img




My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.