Boolean Expression Evaluation using JEP in Java

There are not many open source library available for Boolean expression evaluation. If we have a requirement of evaluating an expression of this kind

A && ( B || C || D)

A && B && (C || D)

We may need to right our own parser to read the expression string and evaluate based on precedence. This code may be difficult to write as well.
JEP ( is a Java library for parsing and evaluating mathematical expressions. With this package you can allow your users to enter an arbitrary formula as a string, and instantly evaluate it. Jep supports user defined variables, constants, and functions. A number of common mathematical functions and constants are included.

Its version 2.4.1 is available as a GPL license which can be downloaded from following location

The JEP uses Double as result object so it means a value of 1.0 is equal to Boolean.TRUE and 0.0 is equal ant to Boolean.FALSE.

Below is a utility program which demonstrates how we can use JEP for Boolean Expression evaluation. This class can be used as it is in you application to make calls for Boolean expression evaluation.

This program requires the 2 distribution jars from JEP downloads.


These files should be available in the downloaded zip file in dist directory.

The addVariable() method of JEP is case sensitive for the variable name, so make sure you are using the exactly same case for expression and addVariable() method.

package expression;

import org.nfunk.jep.JEP;
import org.nfunk.jep.Node;

* @author Sachin Joshi
public class ExpressionEvaluator {
private String expression;
private JEP jep;

public ExpressionEvaluator(String expr) {
this.expression = expr;
jep = new JEP();

public JEP getJep() {
return jep;

public boolean evaluate() {
try {
Node n1 = jep.parse(expression);
Double result = (Double) jep.evaluate(n1);
System.out.println(expression + " = " + result);
return (!result.equals(0.0d));
} catch (Exception e) {
System.out.println("An error occured: " + e.getMessage());
return false;

public static void main(String[] args) {
ExpressionEvaluator e = new ExpressionEvaluator("x && (y || z || w)");
e.getJep().addVariable("x", Boolean.TRUE);
e.getJep().addVariable("x", Boolean.TRUE);
e.getJep().addVariable("y", Boolean.FALSE);
e.getJep().addVariable("z", Boolean.FALSE);
e.getJep().addVariable("w", Boolean.TRUE);
System.out.println("Result is : " + e.evaluate());

Post a Comment Default Comments