exp4j Java library for evaluating math expressions

exp4j Java library for evaluating math expressions

exp4j is a free Java library that can be used to evaluate mathematical expressions. It implements Dijkstra’s Shunting-yard algorithm to translate expressions from infix notation to postfix notation and calculates the result using a simple Stack algorithm. exp4j comes with a standard set of built-in functions and operators. Additionally users can create custom operators and functions. In this post we will see example program using exp4j Java library for evaluating math expressions.

Download exp4j

You can download the binary jar here or you can add the maven dependency as below.

Evaluating an expression

To evaluate an expression, first an Expression object has to be created using the ExpressionBuilder class passing the expression string as a parameter. Any given variables can be set on the Expression object (returned by ExpressionBuilder) via calls to Expression.variable() or Expression.variables() method. Custom functions and custom operators can be set via calls to ExpressionBuilder.function() and ExpressionBuilder.operator() methods.

Following is an example Java program showing the usage of exp4j library.

Below is the output of running the above program.

Custom functions

You can extend the abstract class Function in order to use custom functions in expressions. you only have to implement the apply(double… args) method.

Following example shows the implementation of a custom function to calculate average of 4 arguments.

Below is the output

Validation of expression

exp4j has an added feature to validate expressions. Users can call Expression.validate() to check if an expression is valid i.e. variables are properly set. Below is an example showing the usage of validate method.


If you try to evaluate an invalid expression i.e. without setting variables, it will thrown an exception like below.

Exception in thread “main” java.lang.IllegalArgumentException: No value has been set for the setVariable ‘x’.
at net.objecthunter.exp4j.Expression.evaluate(Expression.java:168)
at posts.Exp4jValidateExample.main(Exp4jExample.java:57)

Hope you find this post useful. exp4j is a simple Java library to evaluate mathematical expression. There are also some advanced libraries like JEval or The Apache Commons Mathematics Library which can be used for this purpose.

If you have any doubt, post it in the comments section.

The following two tabs change content below.
Working as a Java developer since 2010. Passionate about programming in Java. I am a part time blogger.
One comment
  1. Hi,

    Another nice math expression parser you could write about is MathParser.org-mXparser 🙂 Please follow the tutorial section – I hope you will find it helpful.

    Best regards

Add Comment

Required fields are marked *. Your email address will not be published.