Evaluate Arithmetic Strings

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

// Obtain an instance of JavaScript engine.
// The JDK bundled Nashorn under this name from Java 8 through 14. It was removed in Java 15.
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");

//String to be evaluated
String str = "3+2*4+5";
//Value after doing Arithmetic operation with operator precedence will be 16

//Printing the value
try {
    System.out.println(engine.eval(str));
} catch (ScriptException ex) {
    ex.printStackTrace();
}

//Outcome:
//Value of the string after arithmetic evaluation is printed on standard output.
//Nashorn prints 16.0. getEngineByName returns null after Nashorn is removed, and eval would then throw NullPointerException.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents