Expr4J
Expression Calculation Engine for Java
About
Expr4J provides an expression calculation engine (and general purpose expression language) for Java and provides:
  • A general purpose expression parser, intended to be used where mathematical expressions are useful (eg. in a spreadsheet) and compatible with Excel.
  • A dependency engine for calculating spreadsheet-like dependency expressions (eg. A2=A1*35).
  • An implementation of the excel built-in functions for compatibility.

Expr4J is licensed under the Common Public License (CPL).
Download
The latest download is available from the Project Page.
Usage
The following class (included in the download) implements a command-line interpreter of expressions.
package org.boris.expr.util;

import java.io.*;
import org.boris.expr.*;
import org.boris.expr.parser.ExprParser;

public class ExprEvaluator
{
    public static void main(String[] args) throws Exception {
        SimpleEvaluationContext context = new SimpleEvaluationContext();
        System.out.println("Expr Evaluator v1.0");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            try {
                System.out.print(">");
                String line = br.readLine();
                if (line == null)
                    break;
                Expr e = ExprParser.parse(line);
                Exprs.toUpperCase(e);
                if (e instanceof ExprEvaluatable) {
                    e = ((ExprEvaluatable) e).evaluate(context);
                }
                System.out.println(e);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
Dependency Engine Example
The following code snippet shows usage of the dependency engine:
package org.boris.expr.util;

import org.boris.expr.BasicEngineProvider;
import org.boris.expr.engine.DependencyEngine;
import org.boris.expr.engine.Range;

public class DependencyExample
{
    public static void main(String[] args) throws Exception {
        DependencyEngine e = new DependencyEngine(new BasicEngineProvider());
        e.set("B1", "=A1*2");
        e.set("A1", "=12*2");
        e.set("C1", "=B1*A1");
        System.out.println(e.getValue(Range.valueOf("B1")));
        System.out.println(e.getValue(Range.valueOf("C1")));
        e.set("A1", "2");
        System.out.println(e.getValue(Range.valueOf("B1")));
        System.out.println(e.getValue(Range.valueOf("C1")));
    }
}
Change History
V0.0.1
  • Initial version.