logo

Nashorn Javascript


Show

With Java 8, Nashorn, a way improved javascript engine is introduced, to exchange the prevailing Rhino. Nashorn provides 2 to 10 times better performance because it directly compiles the code in memory and passes the bytecode to JVM. Nashorn uses the invoke dynamics feature, introduced in Java 7 to enhance performance.

Jjs

Java 8 launched a new command-line tool for Nashorn Engine. jjs, to accomplish javascript codes at solace.

Explaining js file

Create and save the file with the name called sample.js in c:\> JAVA folder.

Sample.js
print('Hello World!');
Open Console and type the given Command.
C:\JAVA>jjs sample.js

It Will give the following output:
Hello World!

jjs in an Interactive Mode

Open Console and use the following command:

C:\JAVA>jjs
jjs> print("Hello, World!")
Hello, World!
jjs> quit()
>>

Now, Pass Arguments

Again Open Console and type the given command

C:\JAVA> jjs -- a b c
jjs> print('letters: ' +arguments.join(", "))
letters: a, b, c
jjs>

Call JavaScript from Java

You can use Script Engine Manager, via this javascript code can be called and explain in Java

Example

Create the below-given java program in any editor of your choice in, say, C:\> JAVA.

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

public class Java8Tester {

   public static void main(String args[]) {
      ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
      ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");
      String name = "Mahesh";
      Integer result = null;
      
      try {
         nashorn.eval("print('" + name + "')");
         result = (Integer) nashorn.eval("10 + 2");        

      } catch(ScriptException e) {
         System.out.println("Error executing script: "+ e.getMessage());
      }
      System.out.println(result.toString());
   }
}

Verify the Result Through:

Assemble the class by using javac compiler as follows-

C:\JAVA>javac Java8Tester.java

Now, run the Java8Tester as given:

C:\JAVA>java Java8Tester
The outcome will be: 
Mahesh
12

Calling Java from JavaScript

Let’s learn how to import and use java classes in Javascript with the help of given example

Now, Create and save sample.js in c:\> JAVA folder.

sample.js

var BigDecimal = Java.type('java.math.BigDecimal');

function calculate(amount, percentage) {

   var result = new BigDecimal(amount).multiply(new BigDecimal(percentage)).divide(
      new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_EVEN)  

   return result.toPlainString();
}
var result = calculate(568000000000000000023,13.9);
print(result);

Open the console and use the following Command:

C:\JAVA>jjs sample.js

Your Product should be this:

78952000000000000003.20