<tutorialjinni.com/>

JAVA Evaluate Mathematical Expression String

Posted Under: JAVA, Programming, Snippets on Jan 29, 2017
Java do not have an eval() method. But with the introduction of ScriptEngine class in JDK 1.6 it is possible to evaluate a string as a piece of code in JAVA. Below code is one such example it evaluates a string which is complex mathematical expression.
import javax.script.*;

public class Calculator {

    public static void main(String[] args) throws Exception {
        
        String expression = "11 + (Math.exp(2.010635 + Math.sin(Math.PI/2)*3) + 50) / 2";
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("javascript");
        Object result = engine.eval(expression);
        System.out.println(result);// 110.99997794278411
        
    }   
}


imgae