Java8 Nashorn Javascript
# Java 8 Nashorn JavaScript
[ Java 8 New Features](#)
* * *
Nashorn is a JavaScript engine.
The Nashorn JavaScript Engine is no longer available in Java 15.
This has been marked as:
@deprecated (forRemoval = true)
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, which includes invokedynamic introduced in JDK 7, to compile JavaScript into Java bytecode.
Compared to the previous Rhino implementation, this brings a performance improvement of 2 to 10 times.
* * *
## jjs
jjs is a command-line tool based on the Nashorn engine. It accepts some JavaScript source code as arguments and executes that source code.
For example, we create a file named sample.js 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 from Java
Using ScriptEngineManager, JavaScript code can be executed in Java, as shown in the following 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 = ""; 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()); }}
Execute the above script, the output is:
$ javac Java8Tester.java $ java Java8TesterTutorial12
* * *
* * *
## Calling Java from JavaScript
The following example demonstrates how to reference a Java class 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
* * Java 8 New Features](#)
YouTip