Java NashornNashorn 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 TerminalFollowing 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 CodeYou 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 FileYou 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 ExpressionYou 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 HeredocsIn 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 Filefile: 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 FileYou 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 FileJava 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 FileFile: hello.js Output: 2 Example2: Import Java Package in JavaScript FileFile: hello.js Output: [12, 20] class java.util.ArrayList Example3: Import Java Package in JavaScript Fileyou can import multiple packages at the same time. File: hello.js Output: [abc, hello.js, INDIA] Calling JavaScript function inside Java codeYou can call JavaScript function inside the Java file. In the followed example, we are calling JavaScript functions. Example: Calling function inside Java codeFile: hello.js File: NashornExample.java Output: This is JavaScript function Hello Nashorn Next TopicJava 8 Parallel Array Sorting |