Stack Evaluate Expression Java
Fast recall
Quick revision
Core answer
Whether you can evaluate postfix with one stack and know infix needs precedence handling
Popping operands in the wrong order for non-commutative ops (subtraction/division), or ignoring precedence in infix
Note operand order matters (second pop is the left operand) and mention shunting-yard for infix
Interview-ready guide
Interview answer
A stack is the natural tool for evaluating expressions.
The easiest case is postfix notation, also called Reverse Polish Notation, because it has no parentheses and no precedence rules to worry about. I scan the tokens left to right. Whenever I see a number, I push it onto the stack.
Whenever I see an operator, I pop the top two values off the stack, apply the operator to them, and push the result back. When I've processed all the tokens, the single value remaining on the stack is the answer. That's O of n time.
The detail I'm careful about is operand order for non-commutative operators like subtraction and division. The first value I pop is actually the right operand, and the second value I pop is the left operand, because the left one was pushed first and is deeper in the stack. So for subtraction I compute the second pop minus the first pop, not the other way around.
Getting that backwards is a classic bug. For infix expressions, the normal way we write math like three plus four times two, it's harder because I have to respect operator precedence, multiplication binding tighter than addition.
The two standard ways to handle that are to first convert the infix expression to postfix using Dijkstra's shunting-yard algorithm and then evaluate the postfix, or to use two stacks directly, one for operands and one for operators, applying higher-precedence operators before lower ones. So my answer is: one stack for postfix, and precedence handling via shunting-yard or two stacks for infix.
Stack Evaluate Expression Java
Direct Answer
Use a stack. For postfix (RPN): scan tokens, push numbers, and on an operator pop the top two operands, apply it, and push the result; the final stack value is the answer - O(n). For infix, either convert to postfix first (shunting-yard) or use two stacks (operands + operators) honoring operator precedence.
Deep Dive & Architecture
A postfix expression puts each operator after its operands, so a stack can evaluate it without parentheses or precedence rules. Push numbers as they appear. On an operator, pop the right operand first, then the left operand, apply the operator, and push the result.
Worked example: 2 3 4 * +
Push 2, 3, and 4. * pops right 4 and left 3, then pushes 12. + pops right 12 and left 2, then pushes 14. At the end, exactly one value remains, so the result is 14.
Operand order matters for subtraction and division. For 8 2 /, popping gives right 2 and left 8, so the calculation is 8 / 2, not 2 / 8.
For an ordinary infix expression such as 2 + 3 * 4, a second operator stack or a conversion to postfix is needed to handle precedence, associativity, and parentheses. Tokens should be parsed rather than assuming every number has one digit. Invalid input includes too few operands for an operator or more than one value left after all tokens are processed.
Each token is pushed or popped a constant number of times, so postfix evaluation is O(n) time and O(n) stack space in the worst case.
Code Example
int evalRPN(String[] tokens) {
Deque<Integer> st = new ArrayDeque<>();
for (String t : tokens) {
switch (t) {
case "+", "-", "*", "/" -> {
int b = st.pop(); // right operand (popped first)
int a = st.pop(); // left operand
st.push(switch (t) {
case "+" -> a + b; case "-" -> a - b;
case "*" -> a * b; default -> a / b;
});
}
default -> st.push(Integer.parseInt(t));
}
}
return st.pop();
}
// {"2","3","+","4","*"}: push2,push3,+ ->5, push4,* ->20 -> 20
Common Mistakes & Pitfalls
- Operand order: for
-//, the second pop is the left operand; swapping gives wrong results. - Infix without precedence: evaluating
3 + 4 * 2left to right ignores that*binds tighter. - Empty stack / malformed input: too few operands means an invalid expression.
- Integer division/overflow: be aware of truncation and large intermediate values.
Check your understanding
Answer these without looking back at the article.
- What is a stack and what are its core operations?
- What is a queue and how does it differ from a stack?
- How do you check for balanced parentheses using a stack?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.