Execute mathematical string expressions in Java
1 Overview
In this tutorial, we will discuss various methods of executing mathematical string expressions using Java. This feature may come in handy in projects where we want to execute mathematical expressions provided in string format.
First, we will discuss some third-party libraries and their usage. Next, we will see how to use the built-in Java Scripting API to accomplish this task.
2.exp4j
exp4j is an open source library that can be used to evaluate mathematical expressions and functions. The library implements Dijkstra's Shutting Yard algorithm, which is a method of parsing mathematical expressions specified by infix symbols .
In addition to using standard operators and functions, exp4j also allows us to create custom operators and functions.
2.1. Add Maven dependency
To use exp4j, we need to add Maven dependencies to the project :
<dependency>
<groupId>net.objecthunter</groupId>
<artifactId>exp4j</artifactId>
<version>0.4.8</version>
</dependency>
2.2. Evaluate simple expressions
We can evaluate String
simple mathematical expressions provided in the format:
@Test
public void givenSimpleExpression_whenCallEvaluateMethod_thenSuccess() {
Expression expression = new ExpressionBuilder("3+2").build();
double result = expression.evaluate();
Assertions.assertEquals(5, result);
}
In the above code snippet, we first create an ExpressionBuilder
instance. Then, assign it to a Expression
reference, and the expression is used to evaluate the expression.
2.3. Use variables in expressions
Now that we know how to calculate simple expressions, let's add some variables to the expression:
@Test
public void givenTwoVariables_whenCallEvaluateMethod_thenSuccess() {
Expression expression = new ExpressionBuilder("3x+2y")
.variables("x", "y")
.build()
.setVariable("x", 2)
.setVariable("y", 3);
double result = expression.evaluate();
Assertions.assertEquals(12, result);
}
In the above example, we use the variables
method to introduce two variables x
and y,
. Using this method , we can add the required number of variables to the expression . After declaring variables, you can setVariable
assign values to them using methods.
2.4. Evaluate expressions containing mathematical functions
Let us now look at a short example of how to evaluate some standard mathematical functions:
@Test
public void givenMathFunctions_whenCallEvaluateMethod_thenSuccess() {
Expression expression = new ExpressionBuilder("sin(x)*sin(x)+cos(x)*cos(x)")
.variables("x")
.build()
.setVariable("x", 0.5);
double result = expression.evaluate();
Assertions.assertEquals(1, result);
}
3.Javaluator
Javaluator is another free lightweight independent library. Like exp4j, Javaluator is also used to evaluate infix expressions .
3.1. Add Maven dependency
We can use Javaluator in the project with the following Maven dependencies :
<dependency>
<groupId>com.fathzer</groupId>
<artifactId>javaluator</artifactId>
<version>3.0.3</version>
</dependency>
3.2. Evaluate simple expressions
To use Javaluator to evaluate expressions, we first need to create DoubleEvaluator
an instance:
@Test
public void givenExpression_whenCallEvaluateMethod_thenSuccess() {
String expression = "3+2";
DoubleEvaluator eval = new DoubleEvaluator();
Double result = eval.evaluate(expression);
Assertions.assertEquals(5, result);
}
3.3. Evaluate expressions containing variables
To evaluate expressions containing variables, we use StaticVariableSet
:
@Test
public void givenVariables_whenCallEvaluateMethod_thenSuccess() {
String expression = "3*x+2*y";
DoubleEvaluator eval = new DoubleEvaluator();
StaticVariableSet<Double> variables = new StaticVariableSet<Double>();
variables.set("x", 2.0);
variables.set("y", 3.0);
Double result = eval.evaluate(expression, variables);
Assertions.assertEquals(12, result);
}
Then, we use StaticVariableSet#set
methods to assign values to variables.
3.4. Evaluate expressions containing mathematical functions
We can also use the Javaluator library to solve expressions containing mathematical functions:
@Test
public void givenMathFunction_whenCallEvaluateMethod_thenSuccess() {
String expression = "sin(x)*sin(x)+cos(x)*cos(x)";
DoubleEvaluator eval = new DoubleEvaluator();
StaticVariableSet<Double> variables = new StaticVariableSet<Double>();
variables.set("x", 0.5);
Double result = eval.evaluate(expression, variables);
Assertions.assertEquals(1, result);
}
4.Java Script API
Now that we have discussed third-party libraries, let's now discuss how to use the built-in API for this purpose. Java already comes with a small but powerful scripting API. All classes and interfaces of this API are in the javax.script
package.
It contains ScriptEngineManager
and ScriptEngine
interfaces so that we can evaluate JavaScript. Before Java 8, the Rhino
engine came with Java. However, starting with Java 8, Java comes with an updated and more powerful Nashorn engine.
4.1. Get an ScriptEngine
instance
To create ScriptEngine
, we must first create ScriptEngineManager
an instance. After we have the instance, we need to call the ScriptEngineManager#getEngineByName
method to get ScriptEngine
:
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("JavaScript");
Please note that it Nashorn
is the default JavaScript engine included with the JDK.
4.2. Evaluate simple expressions
Now, we can use the above scriptEngine
instance to call the ScriptEngine#eval
method:
String expression = "3+2";
Integer result = (Integer) scriptEngine.eval(expression);
Assertions.assertEquals(5, result);
4.3. Evaluate expressions containing variables
To evaluate expressions containing variables, we need to declare and initialize variables:
String expression = "x=2; y=3; 3*x+2*y;";
Double result = (Double) scriptEngine.eval(expression);
Assertions.assertEquals(12, result);
Since we are using a JavaScript engine, we can directly add variables to expressions just like in JavaScript .
**Note-JavaScript has no direct way to perform mathematical operations and requires access to Math
objects. Therefore, we cannot use the Java Scripting API to solve mathematical expressions.
**
5 Conclusion
In this article, we have seen various techniques for evaluating mathematical expressions using Java.
0 Comments