Postfix notation (also called Reverse Polish Notation or RPN) is a mathematical notation where every operator follows all of its operands. For example, the infix expression 3 + 4 becomes 3 4 + in postfix. This eliminates the need for parentheses and operator precedence rules, making it ideal for stack-based evaluation.
In this post, we implement a Java program that evaluates a postfix expression using a stack. The program reads the expression as a string and produces the integer result.
How the Evaluation Works
The algorithm scans the postfix expression character by character:
- If the character is a digit (operand), push it onto the stack.
- If the character is an operator (
+,-,*,/,%), pop two operands from the stack, apply the operator, and push the result back. - At the end of the expression, the stack contains exactly one value — the final result.
Java Program to Evaluate Postfix Expression
import java.io.*;
// Stack to hold integer operands during evaluation
class OperandStack {
int size;
int item[];
int top;
public OperandStack() {
size = 100;
item = new int[size];
top = -1; // -1 means stack is empty
}
// Push an integer value onto the stack
public void push(int ele) {
if (top == (size - 1)) {
System.out.println("Stack Overflow");
} else {
top++;
item[top] = ele;
}
}
// Pop and return the top value from the stack
public int pop() {
if (top == -1) {
System.out.println("Stack is empty - cannot pop");
return -1;
} else {
int x = item[top];
top--;
return x;
}
}
// Peek at 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 PostfixEvaluator {
OperandStack stack = new OperandStack();
String postfixExpression;
public PostfixEvaluator(String expression) {
postfixExpression = expression;
}
// Returns true if the character is a single-digit operand
public boolean isOperand(char ch) {
return (ch >= '0' && ch <= '9');
}
// Evaluates the postfix expression and returns the integer result
public int evaluate() {
char[] chars = postfixExpression.toCharArray();
int i = 0, operandA, operandB;
while (i < chars.length) {
if (isOperand(chars[i])) {
// Convert char digit to its integer value and push
stack.push(chars[i] - '0');
} else {
// Pop two operands; 'a' was pushed last (top), 'b' was below it
operandA = stack.pop();
operandB = stack.pop();
switch (chars[i]) {
case '+':
stack.push(operandA + operandB);
break;
case '-':
stack.push(operandB - operandA); // b - a to maintain order
break;
case '*':
stack.push(operandA * operandB);
break;
case '/':
stack.push(operandB / operandA); // b / a to maintain order
break;
case '%':
stack.push(operandB % operandA);
break;
}
}
i++;
}
return stack.pop(); // The final result remains on the stack
}
}
public class PostfixEval {
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();
PostfixEvaluator evaluator = new PostfixEvaluator(expression);
System.out.println("Result: " + evaluator.evaluate());
}
}
How the Code Works
- OperandStack class — A simple integer stack that supports
push(),pop(), andpeek(). It uses a fixed-size array of 100 elements. - PostfixEvaluator class — Takes a postfix string in its constructor and exposes an
evaluate()method. - Character scan — The expression is converted to a
char[]and scanned left to right. - Digit detection —
isOperand()checks if the character falls in'0'to'9'. The digit is converted to its integer value viach - '0'before pushing. - Operator handling — For
-and/, the order matters:operandB op operandAbecauseoperandAwas the last pushed (i.e., it was the right-hand operand in the original expression). - Final result — After the full scan, the single remaining value on the stack is the answer.
Sample Output
Enter postfix expression:
623+-382/+*
Result: 7
Output Explanation
Let’s trace the evaluation of 623+-382/+* step by step:
| Step | Character | Action | Stack (top →) |
|---|---|---|---|
| 1 | 6 | Push 6 | [6] |
| 2 | 2 | Push 2 | [6, 2] |
| 3 | 3 | Push 3 | [6, 2, 3] |
| 4 | + | Pop 3, 2 → 2+3=5, push 5 | [6, 5] |
| 5 | – | Pop 5, 6 → 6-5=1, push 1 | [1] |
| 6 | 3 | Push 3 | [1, 3] |
| 7 | 8 | Push 8 | [1, 3, 8] |
| 8 | 2 | Push 2 | [1, 3, 8, 2] |
| 9 | / | Pop 2, 8 → 8/2=4, push 4 | [1, 3, 4] |
| 10 | + | Pop 4, 3 → 3+4=7, push 7 | [1, 7] |
| 11 | * | Pop 7, 1 → 1*7=7, push 7 | [7] |
| 12 | End | Pop final result | → 7 |
See Also
- Java Program to Evaluate PostFix Expressions — An alternate implementation of the same concept
- Java Program to Convert Infix Notation to PostFix Notation — How to generate postfix input for this evaluator
- Implementation of Stack in Java — The core data structure used in this post
- Implementation of Stack using Linked List in Java — Stack backed by a linked list instead of an array
Conclusion
Postfix evaluation using a stack is a clean and efficient algorithm. By eliminating the need for parentheses and precedence parsing, it simplifies expression evaluation to a single linear scan of the input. This approach is the basis for how many calculators and virtual machines (like the JVM itself) internally evaluate expressions. Try extending this program to handle multi-digit numbers or floating-point operands as a further exercise.