Java - Nashorn JavaScript Engine

Hello there, aspiring programmers! I'm thrilled to be your guide on this exciting journey into the world of Java and the Nashorn JavaScript Engine. As someone who's been teaching computer science for over a decade, I can assure you that this is going to be a fun and enlightening experience. So, let's dive in!

Java - Nashorn JavaScript

What is Nashorn JavaScript Engine?

Nashorn (pronounced "nass-horn") is a lightweight, high-performance JavaScript engine that was introduced with Java 8. It's like a bridge between Java and JavaScript, allowing you to run JavaScript code within a Java application. Cool, right?

A Little History

Back in my early days of teaching, we had to use separate environments for Java and JavaScript. It was like trying to make a peanut butter and jelly sandwich with two separate plates! Nashorn changed all that, bringing these two powerful languages together in one delicious combination.

Execute JavaScript via Command Line Tools

Let's start with something simple. Nashorn comes with a command-line tool called jjs that allows you to execute JavaScript directly from your terminal.

Example 1: Hello, Nashorn!

Open your command prompt and type:

jjs
print("Hello, Nashorn!");

You should see "Hello, Nashorn!" printed on your screen. Congratulations! You've just run your first JavaScript code using Nashorn.

Execute JavaScript Directly in Command Prompt

You can also run JavaScript files directly from the command line.

Example 2: Running a JavaScript File

  1. Create a file named greet.js with the following content:
var name = "Alice";
print("Hello, " + name + "!");
  1. Run it using jjs:
jjs greet.js

You should see "Hello, Alice!" printed on your screen.

Passing Arguments to jjs

Nashorn allows you to pass arguments to your JavaScript code, just like you would with Java.

Example 3: Passing Arguments

Create a file named greet_with_args.js:

var name = $ARG[0];
print("Hello, " + name + "!");

Run it with an argument:

jjs greet_with_args.js -- Bob

You should see "Hello, Bob!" printed.

Calling JavaScript from Java

Now, let's get to the really exciting part - calling JavaScript from within your Java code!

Example 4: Evaluating JavaScript in Java

import javax.script.*;

public class JavaScriptInJava {
    public static void main(String[] args) throws ScriptException {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("nashorn");

        engine.eval("print('Hello from JavaScript!');");
    }
}

When you run this Java program, it will print "Hello from JavaScript!" using the Nashorn engine.

Calling Java from JavaScript

The real power of Nashorn comes from its ability to use Java classes and methods within JavaScript code.

Example 5: Using Java Classes in JavaScript

import javax.script.*;

public class JavaInJavaScript {
    public static void main(String[] args) throws ScriptException {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("nashorn");

        engine.eval("var ArrayList = Java.type('java.util.ArrayList');" +
                    "var list = new ArrayList();" +
                    "list.add('Hello');" +
                    "list.add('World');" +
                    "print(list);");
    }
}

This code creates a Java ArrayList, adds elements to it, and prints it - all from within JavaScript!

Advanced Features

Nashorn offers many advanced features that make it a powerful tool for Java developers.

Example 6: Using Java 8 Lambda Expressions

import javax.script.*;

public class LambdaInNashorn {
    public static void main(String[] args) throws ScriptException {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("nashorn");

        engine.eval("var list = [1, 2, 3, 4, 5];" +
                    "list.forEach(function(num) { print(num * 2); });");
    }
}

This example demonstrates how you can use Java 8 lambda expressions within JavaScript code running on Nashorn.

Methods Table

Here's a table of some important methods you can use with Nashorn:

Method Description
ScriptEngineManager.getEngineByName("nashorn") Get the Nashorn script engine
ScriptEngine.eval(String script) Evaluate a JavaScript script
ScriptEngine.put(String key, Object value) Set a variable in the script engine
ScriptEngine.get(String key) Get a variable from the script engine
Invocable.invokeFunction(String name, Object... args) Invoke a JavaScript function

Conclusion

And there you have it, folks! We've just scratched the surface of what Nashorn can do, but I hope this introduction has sparked your curiosity. Remember, the key to mastering programming is practice, so don't be afraid to experiment with these examples and create your own.

As I always tell my students, coding is like learning to ride a bike - it might seem daunting at first, but with practice, you'll be zooming along in no time. And who knows? Maybe one day you'll be teaching others about the wonders of Nashorn!

Keep coding, keep learning, and most importantly, have fun! Until next time, this is your friendly neighborhood computer science teacher signing off. Happy coding!

Credits: Image by storyset