The largest Interview Solution Library on the web


« Previous | 1 | 2 | 3 | Next »

Java_8 New - Nashorn JavaScript Engine


With Java 8, Nashorn, a much improved javascript engine is introduced to replace the existing Rhino java script engine. Nashorn provides 2 to 10 times better performance as it directly compiles the code in memory and passes the bytecode to JVM.Nashorn uses invokedynamics feature, introduced in java 7 to improve performance.

jjs

For Nashorn engine, JAVA 8 introduces a new command line tool, jjs to execute java script code at console.

Interpretting js file.

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

sample.js

print('Hello World!');

Open console and use the following command.

C:\JAVA>jjs sample.js

See the result.

Hello World!

jjs in interactive mode

Open console and use the following command.

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

pass arguments

Open console and use the following command.

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

Calling JavaScript in JAVA

Using ScriptEngineManager, JavaScript code can be called and interpretted 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;

publicclassJava8Tester{
publicstaticvoid main(String args[]){
ScriptEngineManager scriptEngineManager =newScriptEngineManager();
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 to see the result

C:\JAVA>java Java8Tester

See the result.

Mahesh
12

Calling Java from JavaScript


Following example will show how to import and use java classes in java script.
Create and save sample.js in c: > JAVA folder.

sample.js

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

function calculate(amount, percentage){
var result =newBigDecimal(amount).multiply(
newBigDecimal(percentage)).divide(
newBigDecimal("100"),2,BigDecimal.ROUND_HALF_EVEN);
return result.toPlainString();
}
var result = calculate(568000000000000000023,13.9);
print(result);

Open console and use the following command.

C:\JAVA>jjs sample.js

See the result.

78952000000000000003.20
« Previous | 1 | 2 | 3 | Next »


copyright © 2014 - all rights riserved by javatechnologycenter.com