Scripting in Java Tutorial - Scripting in Java HelloWorld








The Nashorn scripting engine can be invoked in two ways: By embedding the engine in the JVM or By using the jjs command-line tool.

Executing Your First Script in Java

The following code shows how to print a Message on the Standard Output Using Nashorn.

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
/*  w  ww.j av a  2 s.  c om*/
public class Main {
  public static void main(String[] args) {
    // Create a script engine manager
    ScriptEngineManager manager = new ScriptEngineManager();

    // Obtain a script engine from the manager
    ScriptEngine engine = manager.getEngineByName("JavaScript");

    // Store the script in a String
    String script = "print('hi from java2s.com!')";
    try {
      // Execute the script
      engine.eval(script);
    } catch (ScriptException e) {
      e.printStackTrace();
    }
  }
}

The code above generates the following result.





jjs Command-line Tool

jjs is command-line tool stored in the JDK_HOME\bin and JRE_HOME\bin directories.

The jjs tool can be used to execute Nashorn script in a file or execute scripts interactively.

The following command runs the jjs tool on a Windows command-prompt. The script is entered and executed. We can use quit() or exit() function to exit the jjs tool:

C:\>jjs
jjs> print('hi from java2s.com!');
hi from java2s.com!

jjs> quit()

The following code shows how to run a js source file with jjs command-line tool.

The Contents of the helloscripting.js File

// helloscripting.js
print('hi from java2s.com!');

The following command executes the script stored in the helloscripting.js.

C:\>jjs helloscripting.js
hi from java2s.com!

C:\>