Postfix notation (also called Reverse Polish Notation or RPN) places every operator after its operands. For example, the infix expression (6 - (2 + 3)) * (3 + 8/2) becomes the postfix expression 623+-382/+*. Evaluating postfix expressions is straightforward using a stack — no parentheses or precedence rules are needed.
This post implements a postfix evaluator in Java using an integer stack. The program accepts a postfix string as input and prints the computed result.
Algorithm
- Scan the postfix expression left to right, one character at a time.
- If the character is a digit, push its integer value onto the stack.
- If the character is an operator, pop the top two values, apply the operator, and push the result.
- After scanning the full expression, the single remaining value on the stack is the answer.
Java Program: Postfix Expression Evaluator
package postfixeval;
import java.io.*;
// Integer stack for storing intermediate operand values
class OperandStack {
int size;
int item[];
int top;
public OperandStack() {
size = 100;
item = new int[size];
top = -1; // -1 means the stack is empty
}
// Pushes a value onto the stack
public void push(int element) {
if (top == (size - 1)) {
System.out.println("Stack Overflow");
} else {
top++;
item[top] = element;
}
}
// Pops and returns the top value
public int pop() {
if (top == -1) {
System.out.println("Stack is empty - cannot pop");
return -1;
} else {
int value = item[top];
top--;
return value;
}
}
// Returns the top value without removing it
public int peek() {
if (top == -1) {
System.out.println("Stack is empty - cannot peek");
return -1;
} else {
return item[top];
}
}
}
// Evaluates a postfix (Reverse Polish Notation) expression
class PostfixExpressionEvaluator {
OperandStack stack = new OperandStack();
String postfixExpression;
public PostfixExpressionEvaluator(String expression) {
postfixExpression = expression;
}
// Returns true if the character is a single-digit operand
public boolean isOperand(char ch) {
return (ch >= '0' && ch <= '9');
}
// Scans the postfix expression and returns its evaluated integer result
public int evaluate() {
char[] characters = postfixExpression.toCharArray();
int index = 0;
int rightOperand, leftOperand;
while (index < characters.length) {
if (isOperand(characters[index])) {
// Convert character digit to its integer value and push
stack.push(characters[index] - '0');
} else {
// Pop two operands: rightOperand was pushed last (is on top)
rightOperand = stack.pop();
leftOperand = stack.pop();
switch (characters[index]) {
case '+':
stack.push(rightOperand + leftOperand);
break;
case '-':
stack.push(leftOperand - rightOperand); // order matters
break;
case '*':
stack.push(rightOperand * leftOperand);
break;
case '/':
stack.push(leftOperand / rightOperand); // order matters
break;
case '%':
stack.push(leftOperand % rightOperand);
break;
}
}
index++;
}
return stack.pop(); // Final result is the only value left on stack
}
}
public class PostfixEvaluatorMain {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter postfix expression:");
String expression = reader.readLine();
PostfixExpressionEvaluator evaluator = new PostfixExpressionEvaluator(expression);
System.out.println("Result: " + evaluator.evaluate());
}
}
How the Code Works
- OperandStack — A fixed-size array-backed integer stack. Supports
push(),pop(), andpeek(). - PostfixExpressionEvaluator — Accepts the postfix string in its constructor. The
evaluate()method converts it to a char array and processes each character. - Digit detection —
isOperand()checks if a character is in'0'–'9'. The expressionch - '0'converts a char digit to its numeric int value. - Operator handling — For
-and/, operand order matters:leftOperand op rightOperand(the left was pushed first, so it sits deeper in the stack). - Final result — After processing the entire expression, a single value remains on the stack — the answer.
Sample Output
Enter postfix expression:
623+-382/+*
Result: 7
Step-by-Step Trace
Tracing 623+-382/+*:
| Char | Action | Stack after step |
|---|---|---|
| 6 | Push 6 | [6] |
| 2 | Push 2 | [6, 2] |
| 3 | Push 3 | [6, 2, 3] |
| + | Pop 3, 2 → 2+3=5, push 5 | [6, 5] |
| – | Pop 5, 6 → 6−5=1, push 1 | [1] |
| 3 | Push 3 | [1, 3] |
| 8 | Push 8 | [1, 3, 8] |
| 2 | Push 2 | [1, 3, 8, 2] |
| / | Pop 2, 8 → 8/2=4, push 4 | [1, 3, 4] |
| + | Pop 4, 3 → 3+4=7, push 7 | [1, 7] |
| * | Pop 7, 1 → 1*7=7, push 7 | [7] |
| End | Pop final answer | → 7 |
See Also
- Evaluating Postfix Expression with Java — Alternate postfix evaluator implementation
- Java Program to Convert Infix Notation to PostFix Notation — How to produce the postfix input this evaluator consumes
- Implementation of Stack in Java — Array-based stack used as the evaluation engine
Conclusion
Postfix evaluation using a stack is one of the most elegant applications of the stack data structure. A single linear pass through the expression — with no backtracking and no precedence lookups — yields the correct result. This technique forms the core of many expression parsers, compilers, and calculators in production software.