Java8 Tutorial on Java 8 Nashorn JavaScript

with java 8, nashorn, a much improved javascript engine is introduced, to replace the existing rhino. nashorn provides 2 to 10 times better performance, as it directly compiles the code in memory and passes the bytecode to jvm. nashorn uses invoke dynamics feature, introduced in java 7 to improve performance.

jjs

for nashorn engine, java 8 introduces a new command line tool, jjs, to execute javascript codes at console.

interpreting js file

create and save the file sample.js in c:\> java folder.

sample.js

print('hello world!');

open console and use the following command.

c:\java>jjs sample.js

it will produce the following output:

hello world!

jjs in interactive mode

open the console and use the following command.

c:\java>jjs
jjs> print("hello, world!")
hello, world!
jjs> quit()
>>

pass arguments

open the console and use the following command.

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

calling javascript from java

using scriptenginemanager, javascript code can be called and interpreted in java.

example

create the following java program using 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

compile the class using javac compiler as follows −

c:\java>javac java8tester.java

now run the java8tester as follows −

c:\java>java java8tester

it should produce the following result −

mahesh
12

calling java from javascript

the following example explains how to import and use java classes in java script.

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

it should produce the following output −

78952000000000000003.20