W3docs

How to evaluate a math expression given in string form?

There are a few different ways to evaluate a math expression given in string form:

There are a few different ways to evaluate a math expression given in string form in Java:

  1. Use a library: One option is to use a library like exp4j or JEP, which can parse and evaluate a string representation of a math expression.
  2. Write your own parser: You could also write your own code to parse the string and evaluate the expression. This would involve breaking the string down into its individual tokens (e.g., numbers, operators) and then using those tokens to perform the necessary calculations.
  3. Use ScriptEngine eval(): Java provides a built-in ScriptEngineManager that can evaluate strings using JavaScript or other scripting engines. However, this is generally not recommended for production, as it can be insecure (since it will execute any arbitrary code passed to it) and is slower than dedicated math libraries. Note that the default Nashorn JavaScript engine was removed in Java 15, so you may need to add a third-party engine like GraalVM JavaScript or verify engine availability at runtime.

Here is an example of how you might use ScriptEngineManager to evaluate a math expression given in string form:


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

public class MathEvaluator {
    public static double evaluate(String expression) {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        try {
            return ((Number) engine.eval(expression)).doubleValue();
        } catch (ScriptException e) {
            throw new RuntimeException("Invalid expression", e);
        }
    }

    public static void main(String[] args) {
        System.out.println(evaluate("2 + 3"));       // prints 5.0
        System.out.println(evaluate("Math.sin(Math.PI/2)")); // prints 1.0
    }
}