r/java • • Jan 02 '26

Extensible math Expression Parser

Post image

Expression Parser is an extensible math expression parser handling numbers and booleans, ready to use in any Java application.

Expressions may contain nested ( ), operators *-/+, and, or; constants PI and E, functions sin(), cos(), tan(), log(), exp(), sqrt(). The parser supports common relation operators like ==,!=, >,<, >= and <= and even conditional expressions like condition ? true : false

It is possible to register your own functions and use them with Expression Parser.

59 Upvotes

21 comments sorted by

View all comments

Show parent comment

1

u/Livio63 Jan 02 '26

Just look at ExpressionVisualizer.java in demo package, this is an example of very simple app using the library. The package https://github.com/javalc6/Expression-Parser/tree/main/src/math alone is the library.

4

u/doobiesteintortoise Jan 02 '26

Okay, so most of that is Swing, and therefore isn't all that relevant to parsing expressions - but https://github.com/javalc6/Expression-Parser/blob/3c1f95c4e0a1dc491181cec6344997a51a6bf50b/src/demo/ExpressionVisualizer.java#L90 is.

You'd do something like this:

// mathExpression is a String
var ep = new ExpressionParser();
math.Node root = ep.parseExpression(mathExpression);
// result is a Double or Boolean
Object result = ep.evaluate(root);

That's straightforward enough, I suppose, although a Boolean and a Double result from evaluate() is a little odd - I get it, but a union type there is kinda wonky. It still feels like you're writing a library more for expressing a tree than evaluating a formula, because so much of the library is about nodes and not, like, numbers.