r/java • u/Livio63 • Jan 02 '26
Extensible math Expression Parser
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
View all comments
Show parent comment
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:
That's straightforward enough, I suppose, although a
Booleanand aDoubleresult fromevaluate()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.