Skip to main content
Last updated February 25, 2011 23:09, by regwhitton
Feedicon  

Eval - A Simple Expression Evaluator for Java

Download the eval distribution from here: eval-dist-0.5.zip

Or use eval via the java.net maven repository (see https://maven2-repository.dev.java.net/)

Details:

  • groupId: net.java.dev.eval
  • artifactId: eval
  • version: 0.5


Eval is intended for use in simple domain specific languages, and was originally written for test configuration.

 Expression exp = new Expression("(x + y)/2");
 
 Map<String, BigDecimal> variables = new HashMap<String, BigDecimal>();
 variables.put("x", new BigDecimal("4.32"));
 variables.put("y", new BigDecimal("342.1"));
 
 BigDecimal result = exp.eval(variables);
 
 System.out.println(result);


The following operators are supported:

  • The basic arithmetic operations as provided by the BigDecimal class:
    • + Addition
    • - Subtraction
    • * multiplication
    • / division (rounds to 34 digits)
    • % the remainder when dividing the preceding number by the following number (this is not module - the result can be negative, rounds to 34 digits)
    • abs absolute of the following number (negative numbers have their sign reversed)
    • pow raise the preceding number to the power of the following number (this can only raise to power of positive integers or zero)
    • int round the following number to an integer
  • Ternary (or conditional) expressions.
    • condition ? value-if-condition-is-true : value-if-condition-is-true. For example: "x > y ? x : y" yields the larger of the two variables x and y
  • The following comparison operations:
    • < less than
    • <= less than or equals
    • == equals
    • > greater than
    • <= greater than or equals
    • != or <> not equals
  • The following boolean operations:
    • && and
    • || or


Comparison and boolean operation yield 1 for true, or 0 for false if used directly.

Expressions are evaluated using the precedence rules found in Java, and parentheses can be used to control the evaluation order.

Example expressions:

 2*2
 2+2
 100/2
 x/100 * 17.5
 2 pow 32 - 1
 2 pow (32 - 1)
 2 pow int 21.5
 abs -1.23E-12
 x > y ? x : y
 x > y && x != 4 ? x : y
 y > 4*x ? 4*y : z/3
 
 
Close
loading
Please Confirm
Close