Java Nashorn

Nashorn is a JavaScript engine. It is used to execute JavaScript code dynamically at JVM (Java Virtual Machine). Java provides a command-line tool jjs which is used to execute JavaScript code.

You can execute JavaScript code by using jjs command-line tool and by embedding into Java source code.


Example: Executing by Using Terminal

Following is the step by step process to execute JavaScript code at the JVM.

1) Create a file hello.js.

2) Write and save the following code into the file.

3) Open terminal

4) Write command jjs hello.js and press enter.

After executing command, you will see the below output.

Output:

Hello Nashorn

Example: Executing JavaScript file in Java Code

You can execute JavaScript file directly from your Java file. In the following code, we are reading a file hello.js with the help of FileReader class.

Output:

Hello Nashorn

Example: Embedding JavaScript Code in Java Source File

You can embed your JavaScript code in Java source file. Java compiler will not complaint but it is not good practice when you have large source code. In the following example, we are evaluating JavaScript code.

Output:

Hello Nashorn

Example: Embedding JavaScript Expression

You can embed JavaScript expressions and variables in JavaScript code. In the following code we are embedding a variable to string. To execute this program you need to pass a flag -scripting in command-line.

File: hello.js

Command: jjs -scripting hello.js

Output:

Hello Nashorn

Heredocs

In Nashorn, heredocs are simply multi-line strings. You can create it with << followed by a special termination marker, which is EOF. You can also embed JavaScript expressions in ${...} expressions.


Example : Heredocs in JavaScript File

file: hello.js

Command: jjs -scripting hello.js

Output:

This is a java script file
it contains multiple lines
of code.
let's execute.

Example: Setting JavaScript variable in Java File

You can pass value to JavaScript variable in the Java file. In the followed example, we are binding and passing variable to JavaScript file.

File: hello.js

File: NashornExample.java

Output:

Hello Nashorn

Import Java Package in JavaScript File

Java provides a facility to import Java package inside the JavaScript code. Here, we are using two approaches to import Java packages.


Example1: Import Java Package in JavaScript File

File: hello.js

Output:

2

Example2: Import Java Package in JavaScript File

File: hello.js

Output:

[12, 20]
class java.util.ArrayList

Example3: Import Java Package in JavaScript File

you can import multiple packages at the same time.

File: hello.js

Output:

[abc, hello.js, INDIA]

Calling JavaScript function inside Java code

You can call JavaScript function inside the Java file. In the followed example, we are calling JavaScript functions.


Example: Calling function inside Java code

File: hello.js

File: NashornExample.java

Output:

This is JavaScript function
Hello Nashorn




Latest Courses