Java Nashorn

Last updated on Dec 26 2022
Prabhas Ramanathan

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.

Table of Contents

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.
1. var hello = function(){
2. print(“Hello Nashorn”);
3. };
4. hello();
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.

1. import javax.script.*; 
2. import java.io.*; 
3. public class NashornExample { 
4. public static void main(String[] args) throws Exception{ 
5. // Creating script engine 
6. ScriptEngine ee = new ScriptEngineManager().getEngineByName("Nashorn"); 
7. // Reading Nashorn file 
8. ee.eval(new FileReader("js/hello.js")); 
9. } 
10. }

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.

1. import javax.script.*; 
2. public class NashornExample { 
3. public static void main(String[] args) throws Exception{ 
4. // Creating script engine 
5. ScriptEngine ee = new ScriptEngineManager().getEngineByName("Nashorn"); 
6. // Evaluating Nashorn code 
7. ee.eval("print('Hello Nashorn');"); 
8. } 
9. }

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

1. var hello = function(msg){ 
2. print("Hello ${msg}"); 
3. }; 

4. hello("Nashron");

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
1. var message = <<EOF
2. This is a java script file
3. it contains multiple lines
4. of code.
5. let’s execute.
6. EOF
7. print(message)
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

1. print("Hello "+name); 
File: NashornExample.java
1. import javax.script.*; 
2. import java.io.*; 
3. public class NashornExample { 
4. public static void main(String[] args) throws Exception{ 
5. // Creating script engine 
6. ScriptEngine ee = new ScriptEngineManager().getEngineByName("Nashorn"); 
7. //Binding script and Define scope of script 
8. Bindings bind = ee.getBindings(ScriptContext.ENGINE_SCOPE); 
9. bind.put("name", "Nashorn"); 
10. // Reading Nashorn file 
11. ee.eval(new FileReader("js/hello.js")); 
12. } 
13. }

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
1. print(java.lang.Math.sqrt(4));
Output:
2

 

Example2: Import Java Package in JavaScript File

File: hello.js

1. var importFile = new JavaImporter(java.util); 
2. var a = new importFile.ArrayList(); 
3. a.add(12); 
4. a.add(20); 
5. print(a); 
6. print(a.getClass());

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

1. var importIt = new JavaImporter(java.lang.String,java.util,java.io); 
2. with (importIt) { 
3. var linkedHS = new LinkedHashSet(); 
4. linkedHS.add(new File("abc")); 
5. linkedHS.add(new File("hello.js")); 
6. linkedHS.add("india".toUpperCase()); 
7. } 
8. print(linkedHS);

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

1. var functionDemo1 = function(){ 
2. print("This is JavaScript function"); 
3. } 
4. var functionDemo2 = function(message){ 
5. print("Hello "+message); 
6. }

File: NashornExample.java

1. import javax.script.*; 
2. import java.io.*; 
3. public class NashornExample { 
4. public static void main(String[] args) throws Exception{ 
5. // Creating script engine 
6. ScriptEngine ee = new ScriptEngineManager().getEngineByName("Nashorn"); 
7. // Reading Nashorn file 
8. ee.eval(new FileReader("js/hello.js")); 
9. Invocable invocable = (Invocable)ee; 
10. // calling a function 
11. invocable.invokeFunction("functionDemo1"); 
12. // calling a function and passing variable as well. 
13. invocable.invokeFunction("functionDemo2","Nashorn"); 
14. } 
15. }

Output:
This is JavaScript function
Hello Nashorn

So, this brings us to the end of blog. This Tecklearn ‘Java Nashorn’ blog helps you with commonly asked questions if you are looking out for a job in Java Programming. If you wish to learn Java and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

Java and JEE Training

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

• Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
• Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
• Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

• Java Fundamentals
• Introduction to Java Basics
• Features of Java
• Various components of Java language
• Benefits of Java over other programming languages
• Key Benefits of Java

Installation and IDE’s for Java Programming Language

• Installation of Java
• Setting up of Eclipse IDE
• Components of Java Program
• Editors and IDEs used for Java Programming
• Writing a Simple Java Program

Data Handling and Functions

• Data types, Operations, Compilation process, Class files, Loops, Conditions
• Using Loop Constructs
• Arrays- Single Dimensional and Multi-Dimensional
• Functions
• Functions with Arguments

OOPS in Java: Concept of Object Orientation

• Object Oriented Programming in Java
• Implement classes and objects in Java
• Create Class Constructors
• Overload Constructors
• Inheritance
• Inherit Classes and create sub-classes
• Implement abstract classes and methods
• Use static keyword
• Implement Interfaces and use it

Polymorphism, Packages and String Handling

• Concept of Static and Run time Polymorphism
• Function Overloading
• String Handling –String Class
• Java Packages

Exception Handling and Multi-Threading

• Exception handling
• Various Types of Exception Handling
• Introduction to multi-threading in Java
• Extending the thread class
• Synchronizing the thread

File Handling in Java

• Input Output Streams
• Java.io Package
• File Handling in Java

Java Collections

• Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
• Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
• Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

• Introduction to SQL: Connect, Insert, Update, Delete, Select
• Introduction to JDBC and Architecture of JDBC
• Insert/Update/Delete/Select Operations using JDBC
• Batch Processing Transaction
• Management: Commit and Rollback

Java Enterprise Edition – Servlets

• Introduction to J2EE
• Client Server architecture
• URL, Port Number, Request, Response
• Need for servlets
• Servlet fundamentals
• Setting up a web project in Eclipse
• Configuring and running the web app with servlets
• GET and POST request in web application with demo
• Servlet lifecycle
• Servlets Continued
• Session tracking and filter
• Forward and include Servlet request dispatchers

Java Server Pages (JSP)

• Fundamentals of Java Server Page
• Writing a code using JSP
• The architecture of JSP
• JSP Continued
• JSP elements: Scriptlets, expressions, declaration
• JSP standard actions
• JSP directives
• Introduction to JavaBeans
• ServletConfig and ServletContext
• Servlet Chaining
• Cookies Management
• Session Management

Hibernate

• Introduction to Hibernate
• Introduction to ORM
• ORM features
• Hibernate as an ORM framework
• Hibernate features
• Setting up a project with Hibernate framework
• Basic APIs needed to do CRUD operations with Hibernate
• Hibernate Architecture

POJO (Plain Old Java Object)

• POJO (Plain Old Java Object)
• Persistent Objects
• Lifecycle of Persistent Object

Spring

• Introduction to Spring
• Spring Fundamentals
• Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

 

 

0 responses on "Java Nashorn"

Leave a Message

Your email address will not be published. Required fields are marked *