Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean Expression Evaluation in Java

I'm looking for a relatively simpler (when compared with writing a parser) way to evaluate boolean expressions in Java, and I do not want to use the JEP library.

I have a String expression like: (x > 4 || x < 8 && p > 6) and my aim is to replace the variables with values.

Is there a way by which I can evaluate this expression?

Bear in mind that this can be any level deep so writing a parser would be very complex.

like image 724
TJ- Avatar asked Nov 15 '09 05:11

TJ-


People also ask

Which expression evaluates to true in Java?

These operators include equality ( == ) and inequality ( != ). The former operator returns true when both operands are equal; the latter operator returns true when both operands are unequal.

What is Boolean expression in Java example?

A Boolean expression is a Java expression that returns a Boolean value: true or false .


2 Answers

Use Apache Commons Jexl; which is exactly designed for such requirement.

http://commons.apache.org/jexl/

like image 177
Venkat Sadasivam Avatar answered Oct 11 '22 00:10

Venkat Sadasivam


Using jexl (http://commons.apache.org/jexl/), you can accomplish this like this

    JexlEngine jexl = new JexlEngine();
    jexl.setSilent(true);
    jexl.setLenient(true);

    Expression expression = jexl.createExpression("(a || b && (c && d))");
    JexlContext jexlContext = new MapContext();

    //b and c and d should pass
    jexlContext.set("b",true);
    jexlContext.set("c",true);
    jexlContext.set("d",true);

    assertTrue((Boolean)expression.evaluate(jexlContext));

    jexlContext = new MapContext();

    //b and c and NOT d should be false
    jexlContext.set("b",true);
    jexlContext.set("c",true);

    //note this works without setting d to false on the context
    //because null evaluates to false

    assertFalse((Boolean)expression.evaluate(jexlContext));
like image 31
Matthew Kirkley Avatar answered Oct 11 '22 01:10

Matthew Kirkley