JavaData & JavaExplore Scripting in Java

Explore Scripting in Java

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

One of the interesting API features included from Java 6 and its later version is the javax.script package. Developers now can literally embed a scripting language into a Java application. This feature opened a new horizon of application development because the handshake between scripting and core Java may not have been the forefront requirement but nonetheless added another feature to the flow of application development that can now “also use scripting”. Java includes into its umbrella variegated scripting languages such as Rhino JavaScript, Groovy, Jython, JRuby, Nashorn JavaScript, and so forth. The best utility of this feature rests on to the creative mind of the developers. Let us all unravel its power gradually. In this article, we are going to look into some nooks and corners and key aspects of scripting in Java in general.

A Peek into the Integration

Java Virtual Machine (JVM) is quite generous in providing an execution layer for any language-neutral byte code. That means, pretty much any language that can be converted into byte code can ride on JVM. A script is a sequence of characters written according to the syntax of a scripting language (such as Python, JavaScript, Ruby, and so on). These scripts are embedded into the Java code that are evaluated or interpreted by the runtime environment called the script engines. This script engine is the interpreter that parses the script and generates intermediate code and is totally responsible for the execution of the script. It stores the variable declared in the script in a symbol table data structure like in any language. Note that, if we want to embed a script within Java code, we must have installed relevant script engines that work in sync with JVM.

Here is some simple code to check the list of script engines installed.

import java.util.List;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;

public class ScriptingTest {
   public static void main(String[] args) {
      ScriptEngineManager scriptingEngineManager=new
         ScriptEngineManager();
      List<ScriptEngineFactory> list=
         scriptingEngineManager.getEngineFactories();
      for(ScriptEngineFactory factory: list){
         System.out.println("Engine Name: "
            +factory.getEngineName());
         System.out.println("Engine Version: "+
            factory.getEngineVersion());
         System.out.println("Languge Name: "+
            factory.getLanguageName());
         System.out.println("Languge Version: "+
            factory.getLanguageVersion());
         System.out.println("Engine  Short Names: "+
            factory.getNames());
         System.out.println("Mime Types: "+
            factory.getMimeTypes());
         System.out.println("");
      }
   }
}

Oracle’s Nashorn JavaScript is the default engine installed with JDK 8, replacing JDK 7’s Rhino JavaScript engine. Experts suggest the Nashhorn JavaScript engine is faster and more lightweight than Rhino.

Engine Name: Oracle Nashorn
Engine Version: 1.8.0_40
Languge Name: ECMAScript
Languge Version: ECMA - 262 Edition 5.1
Engine Short Names: [nashorn, Nashorn, js, JS,
   JavaScript, javascript, ECMAScript, ecmascript]
Mime Types: [application/javascript,
   application/ecmascript, text/javascript,
   text/ecmascript]

For more info in other script engines, follow these links:

The main difference between a scripting language and a typical programming language is that programming languages are compiled whereas the source code of scripts is not compiled but interpreted at runtime. (Though all scripting languages do not follow this methodology, many are compiled for performance; yet typically, this is the basic difference). What the Java platform did is provide a platform for different script engines to function in sync with the JVM so that source code can be co-bundled with no visible difference in the output.

Why to Integrate

There can be several opinions on why to integrate Java with another scripting language. Experts opine from different perspectives. A couple of compelling reasons, with which I could not disagree are as follows:

  • Some scripting languages are great for a specific task such as Perl, exceptional for text processing. This capability can be utilized to the advantage of the Java programmer.
  • Scripting languages are inherently dynamic; as a result, there are aspects of execution behavior decided at runtime. Java can take advantage of this program behavior and extend its capability by injecting objects and function during runtime.

To Begin with

Let us get into the code structure of integrating a script in Java code. With only Nashorn JavaScript engine installed, the script language we’ll be using is JavaScript. Now, to begin with, we must follow the following three-fold path of integration.

  1. Create a ScriptEngineManager.
  2. Get an instance of ScriptEngine. The instance of this interface represents the script engine in the Java program. And the specific engine is called by the parameter passed to the getEngineByName() function.
  3. Execute the eval() method of the engine to run the script. Live scripts are passed as a string according to the relevant scripting language before executing eval().
public class ScriptingTest {
   public static void main(String[] args) {
      ScriptEngineManager manager=new
         ScriptEngineManager();
      ScriptEngine scriptEngine=manager.getEngineByName
         ("JavaScript");
      try{
         scriptEngine.eval("print('JavaScript to
            print this text')");
      }catch(ScriptException e){
         e.printStackTrace();
      }
   }
}

If we want to execute a JavaScript function in Java code, we would use this code:

scriptEngine.eval("function F2C(farenheit){"
   + "var celcius =(5/9)*(farenheit-32);"
   + "return celcius; }");
scriptEngine.eval("print('Celcius: '+ F2C(100))");

In case we want to load and execute an external JavaScript file from Java code, we can alter the string passed to eval() as follows:

scriptEngine.eval("load('src/js/script1.js')");

These are a glimpse into scripting in Java. We’ll see more about scripting in the next few articles. Stay tuned.

Conclusion

Scripting and Java should be weighed in the common complimentary parlance. There is no conflict as some believe one will overpower other; scripting can never replace a standard and versatile language like Java. It will always be an assisting language, providing some impressive and valuable inputs when collaborated with giants like Java. Though not very convinced about the actual utility of integration in extensive programming/enterprise arena, take it as an another feature and of course fun of programming; we now can tweak JavaScript, Ruby, and the liike into Java code as we had done with HTML in Java Swing.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories