Java 8 – Nashorn – JavaScript Engine – Java + JavaScript Example

Java 8 introduced a new JavaScript Engine namely “Nashorn” which can execute JavaScript embedded in Java source code or from command line using command jjs.

Example :

 

OUTPUT

CodeForEach
Java + JS( reader of js file as input ) = 5
CodeForEach
Java + JS( script as input ) = 4

 

Code Explained in 3 steps :
i) Get JavaScript Engine – Nashorn using engine manager
ii) Read JavaScript using file reader or directly input the script
iii) evaluate the script by taking input either as reader or string as above and get returned value from JavaScript

References

Java 8 – new features and enhancements with examples

Author of CodeForEach.com . Loves coding and related technologies.
 

www.000webhost.com