RPN Calculator in Java — A Practical Stack Implementation

Steve Pesce
3 min readNov 22, 2020

After last weeks blog post, What is a Stack and how to Create one in Java, I figured it would be nice to give a practical example of using a stack in Java.

Reverse Polish Notation (also known as Postfix Notation) is a different way to write mathematical expressions. Normally, we use Infix notation to write algebraic expressions, where operators are between operands. While RPN expressions may be difficult to understand at first, they simplify algebraic expressions due to RPN doing away with parenthesis and the order of operations.

In RPN, the operators follow the operands. For example 3 + 2 becomes 3 2 +, 5 / 3 becomes 5 3 /, and so on. If we have 3 + 5 * 2 [written more clearly with parenthesis as 3 + (5 * 2)], can be written in RPN as 3 5 2 * +. The following shows the flow of solving this RPN expression.

Is it clear why a stack would come in handy when solving this programmatically? Consider how we are solving this — starting from the left, look for the first operator, then apply that operation to the two numbers preceding it. This animation will show you step by step how a stack is used to solve it:

--

--

No responses yet