April 1, 2013

Evaluate Simple Script Expressions using Java API


Are you looking for an easier way to evaluate expressions like "'ABC'=='XYZ' && (4!=6 || 3 !=5)" etc.. in simpler way in Java, then here comes the javax.script.ScriptEngineManager class in Java SE 1.6 onwards. One can simply pass any script to its engine (Not to mention, it should be a valid script) and voila, one line of code does all the magic hence saving all the time required in implementing old airtmentical,logical, boolean logic in your code. It will return the value as true/false. Not only this, if one want to evaluate any arithmetic operation on these, one can evaluate the value such expressions. e.g. 1+3 return 4 as output.

Program:

package myjava;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class ScriptDemo {


public static void main(String[] args) throws ScriptException {
System.out.println("Enter expression:::\n");

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Object val = null;

try {
String expr_to_eval = br.readLine();


ScriptEngineManager mgr = new ScriptEngineManager();

ScriptEngine engine = mgr.getEngineByName("JavaScript"); // Considers the input script as JavaScript

val = engine.eval(expr_to_eval);


} catch (Exception e) {
System.out.println("Exception occured");

} finally {
System.out.println("Expr after evaluation is " + val);

}

}



}

Sample Output1:
Enter expression:::

1+3
Expr after evaluation is 4.0

Sample Output2:
Enter expression:::

'ABC'=='ABC' && (1==4 || 3==3)
Expr after evaluation is true

This is a basic program, check out the complete API for more functionality.