Easy Tutorial
❮ Java Arraylist Removerange Java String Tostring ❯

Java 8 Nashorn JavaScript

Java 8 New Features


Nashorn is a JavaScript engine.

It has been marked as:

@deprecated (forRemoval = true)

in Java 11.

Starting from JDK 1.8, Nashorn replaced Rhino (JDK 1.6, JDK 1.7) as Java's embedded JavaScript engine. Nashorn fully supports the ECMAScript 5.1 specification and some extensions. It uses new language features based on JSR 292, including invokedynamic introduced in JDK 7, to compile JavaScript into Java bytecode.

This results in a performance improvement of 2 to 10 times compared to the previous Rhino implementation.


jjs

jjs is a command-line tool based on the Nashorn engine. It accepts some JavaScript source code as parameters and executes these source codes.

For example, we create a sample.js file with the following content:

print('Hello World!');

Open the console and enter the following command:

$ jjs sample.js

The output of the above program is:

Hello World!

jjs Interactive Programming

Open the console and enter the following command:

$ jjs
jjs> print("Hello, World!")
Hello, World!
jjs> quit()
>>

Passing Arguments

Open the console and enter the following command:

$ jjs -- a b c
jjs> print('Letters: ' + arguments.join(", "))
Letters: a, b, c
jjs>

Calling JavaScript in Java

Using ScriptEngineManager, JavaScript code can be executed in Java. Here is an example:

Java8Tester.java File

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 = "tutorialpro";
      Integer result = null;

      try {
         nashorn.eval("print('" + name + "')");
         result = (Integer) nashorn.eval("10 + 2");

      } catch(ScriptException e){
         System.out.println("Script execution error: " + e.getMessage());
      }

      System.out.println(result.toString());
   }
}

Executing the above script outputs:

$ javac Java8Tester.java 
$ java Java8Tester
tutorialpro
12

Calling Java in JavaScript

The following example demonstrates how to reference Java classes in JavaScript:

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);

We use the jjs command to execute the above script, and the output is as follows:

$ jjs sample.js
78952000000000002017.94

New Features in Java 8

❮ Java Arraylist Removerange Java String Tostring ❯