Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Nashorn JavaScript Engine in Java with Examples
Next article icon

Nashorn JavaScript Engine in Java with Examples

Last Updated : 06 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report
Nashorn: Nashorn is a JavaScript engine which is introduced in JDK 8. With the help of Nashorn, we can execute JavaScript code at Java Virtual Machine. Nashorn is introduced in JDK 8 to replace existing JavaScript engine i.e. Rhino. Nashorn is far better than Rhino in term of performance. The uses of invoking dynamic feature, conversion of JavaScript code into the bytecode directly into the memory etc makes the Nashorn more famous in JDK 8. We can execute JavaScript code by using the command-line tool and by embedding the JavaScript code into Java source code. Executing JavaScript code by using console: For Nashorn engine, Java 8 introduced one new command-line tool i.e.jjs. We have to follow the below steps to execute JavaScript code through the console:
  • Create one file named with geeks.js.
  • Open geeks.js and write following code into the file and save it. javascript
    var gfg= function(){       print("Welcome to Geeksforgeeks!!!");   };   gfg();  
  • Open CMD, write jjs geeks.js and press enter. It will generate the below output:
      Welcome to Geeksforgeeks!!!  
Executing JavaScript file by embedding JavaScript file into Java code: We can execute JavaScript file by embedding JavaScript file into Java code with the help of ScriptEngine class. ScriptEngine class is introduced in JDK 6. By the help of the ScriptEngine class, we can create a JavaScript engine and with the JavaScript engine, we can execute the javaScript file. Example 1: Java
// Program to illustrate embedding // of JavaScript file into Java code  import javax.script.*; import java.io.*;  public class Geeksforgeeks {     public static void main(String[] args)         throws Exception     {          // Here we are generating Nashorn JavaScript Engine         ScriptEngine ee = new ScriptEngineManager()                               .getEngineByName("Nashorn");          // Reading JavaScript file create in first approach         ee.eval(new FileReader("geeks.js"));     } } 
Output:
  Welcome to Geeksforgeeks!!!  
Example 2: Java
// Program to illustrate embedding // of JavaScript code into Java code  import javax.script.*; import java.io.*;  public class Geeksforgeeks {     public static void main(String[] args)         throws Exception     {          // Here we are generating Nashorn JavaScript Engine         ScriptEngine ee = new ScriptEngineManager()                               .getEngineByName("Nashorn");          // Instead of reading JavaScript code from a file.         // We can directly paste the JavaScript         // code inside Java Code         ee.eval("print('Welcome to Geeksforgeeks!!!"                 + " Executing JavaScript code with the"                 + " help of Nashorn engine');");     } } 
Output:
Welcome to Geeksforgeeks!!! Executing JavaScript code with the help of Nashorn engine
Apart from above, with the help of Nashorn JavaScript Engine, we can perform multiple operations like:
  1. Providing JavaScript variable from Java Code: Suppose we have one JavaScript file name with geeks.js and geeks.js requires one variable during execution. With the help of Nashorn, we can pass the variable to JavaScript file from java code. Example 1: geeks.js file, which needs name variable to get executed javascript
    // JavaScript file name with geeks.js print("Welcome to Geeksforgeeks!!! Mr. "+name);   
    Example 2: Java code providing name variable to the JS file Java
    // Program to illustrate passing of variable // from java code to javascript file  import javax.script.*; import java.io.*;  public class Geeksforgeeks {     public static void main(String[] args)         throws Exception     {         ScriptEngine ee             = new ScriptEngineManager()                   .getEngineByName("Nashorn");         Bindings bind             = ee.getBindings(                 ScriptContext.ENGINE_SCOPE);         bind.put("name", "Bishal Kumar Dubey");         ee.eval(new FileReader("geeks.js"));     } } 
    Output:
      Welcome to Geeksforgeeks!!! Mr. Bishal Kumar Dubey  
  2. Calling JavaScript function from Java code: We can call JavaScript function from Java code with the help of Nashorn. Suppose we create one file name with geeks.js and the file contains two functions like below: javascript
    // JavaScript file name with geeks.js  var func1 = function(){       print("Simple JavaScript function!!!");   }    var func2 = function(reader){       print("Hello "+reader);   }   
    Java
    // Program to illustrate calling of // JavaScript function from Java code  import javax.script.*; import java.io.*;  public class Geeksforgeeks {     public static void main(String[] args)         throws Exception     {         ScriptEngine ee             = new ScriptEngineManager()                   .getEngineByName("Nashorn");         ee.eval(new FileReader("geeks.js"));         Invocable invocable = (Invocable)ee;          // Here we are calling func1         invocable.invokeFunction("func1");          // Here we are calling func2         // as well as passing argument         invocable.invokeFunction("func2",                                  "Bishal Kumar Dubey");     } } 
    Output:
      Simple JavaScript function!!!  Hello Bishal Kumar Dubey  

Next Article
Nashorn JavaScript Engine in Java with Examples

B

bishaldubey
Improve
Article Tags :
  • Java
  • Technical Scripter
  • JavaScript
  • Web Technologies
  • Technical Scripter 2019
  • JavaScript-Questions
Practice Tags :
  • Java

Similar Reads

    What happens inside JavaScript Engine ?
    JavaScript is a multi-paradigm prototype-based language, which uses JavaScript Engine such as Chrome's V8 engine Firefox SpiderMonkey engine and etc. They convert the high level code into machine-readable code which lets computer to perform some specific tasks. We will understand this using an image
    3 min read
    JavaScript Set Programming Examples
    In JavaScript, the Set is a built-in collection that allows you to store unique values of any type, Set can store any type of value whether primitive or objects. It provides methods for adding, removing, and querying elements in an efficient way.JavaScriptlet s = new Set(["a", "b", "c"]); console.lo
    1 min read
    JavaScript Math Programming Examples
    The JavaScript Math Object is used to perform mathematical operations on numbers. The Math object does not have a constructor. All properties and methods of Math are fixed/static. All properties and methods of Math are static and can be called by using Math as an object.JavaScript Math Programming E
    2 min read
    JavaScript Course Interaction With User
    Javascript allows us the privilege to which we can interact with the user and respond accordingly. It includes several user-interface functions which help in the interaction. Let's take a look at them one by one. JavaScript Window alert() Method : It simply creates an alert box that may or may not h
    2 min read
    JavaScript Programming Examples
    JavaScript is a dynamic, widely-used programming language that plays a pivotal role in modern web development. Whether you're a beginner or an experienced developer, practicing JavaScript programming examples is an excellent way to refine your coding skills, enhance your problem-solving abilities, a
    15 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences