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!')";
    try {
      // Execute the script
    } catch (ScriptException e) {

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:

jjs> print('hi from!');
hi from!

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!');

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

C:\>jjs helloscripting.js
hi from!