Evaluating Postfix Expression with Java

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:

  1. If the character is a digit (operand), push it onto the stack.
  2. If the character is an operator (+, -, *, /, %), pop two operands from the stack, apply the operator, and push the result back.
  3. 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

  1. OperandStack class — A simple integer stack that supports push(), pop(), and peek(). It uses a fixed-size array of 100 elements.
  2. PostfixEvaluator class — Takes a postfix string in its constructor and exposes an evaluate() method.
  3. Character scan — The expression is converted to a char[] and scanned left to right.
  4. Digit detection — isOperand() checks if the character falls in '0' to '9'. The digit is converted to its integer value via ch - '0' before pushing.
  5. Operator handling — For - and /, the order matters: operandB op operandA because operandA was the last pushed (i.e., it was the right-hand operand in the original expression).
  6. 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:

StepCharacterActionStack (top →)
16Push 6[6]
22Push 2[6, 2]
33Push 3[6, 2, 3]
4+Pop 3, 2 → 2+3=5, push 5[6, 5]
5Pop 5, 6 → 6-5=1, push 1[1]
63Push 3[1, 3]
78Push 8[1, 3, 8]
82Push 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]
12EndPop final result→ 7

See Also

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.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.