«Back to Home

Core Java

Topics

Nashorn JavaSript In Java

Nashorn JavaSript
 
Nashorn an improved javascript engine is introduced in Java 8 to change the existing Rhino. It gives better performance, because it directly compiles the code in memory and passes the bytecode to JVM. It uses invokedynamics feature which introduced in Java 7 to improve performance.
 
jjs

Java 8 introduces a new command line tool for Nashorn engine jjs, to perform JavaScript codes at console.
 
Interpreting js File

Create and save the file first.js in c:\> JAVA folder.
 
first.js
 
display('Java 8');
 
Then, open console and use the command.
 
$jjs first.js
 
Output

Java 8
 
jjs in Interactive Mode

Open the console and use the command.
 
$jjs
 
jjs> display("Java 8")
 
Java 8
 
jjs> quit()
 
>>
 
Pass Arguments

Open the console and use the command.
 
$jjs – x y z
 
jjs> display('letters: ' +arguments.join(", "))
 
letters: x, y, z
 
jjs>
 
Call JavaScript from Java

With the usage of ScriptEngineManager, JavaScript code can be called and interpreted in Java.
 
Let’s see an example of Nashorn JavaScript.
 
Code
  1. import javax.script.ScriptEngineManager;  
  2. import javax.script.ScriptEngine;  
  3. import javax.script.ScriptException;  
  4. public class NashornJavaScriptExample {  
  5.     public static void main(String args[]) {  
  6.         ScriptEngineManager s = new ScriptEngineManager();  
  7.         ScriptEngine n = s.getEngineByName("Nashorn");  
  8.         String name = "Java";  
  9.         Integer result = null;  
  10.         try {  
  11.             n.eval("print('" + name + "')");  
  12.             result = (Integer) n.eval("6 + 2");  
  13.         } catch (ScriptException e) {  
  14.             System.out.println("Error: " + e.getMessage());  
  15.         }  
  16.         System.out.println(result.toString());  
  17.     }  
  18. }  
22

Output

23

Summary

Thus, we learned that Nashorn an improved javascript engine is introduced in Java 8 to change the existing Rhino. It gives better performance and also learns how to use it in Java.