Java 8 - Nashorn - JavaScript Engine - Java + JavaScript Example

Java 8 introduced a new JavaScript Engine namely "Nashorn" which can execute JavaScript embedded in Java source code or from command line using command jjs.

Example :

// demo.js file
(function() {
	return 3;
package com.codeforeach.demo;


import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

public class JavaScriptInJavaDemo {

  public static void main(String[] args) throws Exception {
    int valueFromJava = 2;

    // get instance of JS Engine
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("Nashorn");

    // use a reader to read script from file
    Reader reader = new FileReader("demo.js");

    // evaluate script and get returned value
    int valueFromJS1 = (Integer) engine.eval(reader);

    System.out.println("Java + JS( reader of js file as input ) = " + (valueFromJava + valueFromJS1));

    // evaluate embedded script and get returned value
    int valueFromJS2 = (Integer) engine.eval("(function() { print('CodeForEach') ; return 2 })()");

    System.out.println("Java + JS( script as input ) = " + (valueFromJS2 + valueFromJava));


Java + JS( reader of js file as input ) = 5
Java + JS( script as input ) = 4


Code Explained in 3 steps :
i) Get JavaScript Engine - Nashorn using engine manager
ii) Read JavaScript using file reader or directly input the script
iii) evaluate the script by taking input either as reader or string as above and get returned value from JavaScript


Java 8 – new features and enhancements with examples


Submit a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>