Java Algorithms How to - Evaluate math expressions in String


We would like to know how to evaluate math expressions in String.


import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
// ww  w  .j  a  v  a 2s .com
public class Main {
  public static void main(String[] args) throws Exception {
    // create a script engine manager
    ScriptEngineManager factory = new ScriptEngineManager();
    // create a JavaScript engine
    ScriptEngine engine = factory.getEngineByName("JavaScript");
    // evaluate JavaScript code from String
    Object obj = engine.eval("1+2");

The code above generates the following result.