Java Program to evaluate mathematical expressions in String

Java 8Object Oriented ProgrammingProgramming

To evaluate mathematical expression in String, use Nashorn JavaScript in Java i.e. scripting. Nashorn invoke dynamics feature, introduced in Java 7 to improve performance.

For scripting, use the ScriptEngineManager class for the engine −

ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("JavaScript");

Now for JavaScript code from string, use eval i.e. execute the script. Here, we are evaluating mathematical expressions in a string −

Object ob = scriptEngine.eval("9 + 15 + 30");
System.out.println("Result of evaluating mathematical expressions in String = "+ob);

Example

 Live Demo

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class Main {
   public static void main(String[] args) throws Exception {
      ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
      ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("JavaScript");
      // JavaScript code from String
      Object ob = scriptEngine.eval("9 + 15 + 30");
      System.out.println("Result of evaluating mathematical expressions in String = "+ob);
   }
}

Output

Result of evaluating mathematical expressions in String = 54
raja
Published on 23-Apr-2019 08:28:07
Advertisements