# Java Postfix Calculator

## What is Postfix expression

Postfix is a expression of Arithmetic Expressions in which the operands are placed before their operators. There are no precedence rules, no parentheses needed. It's much easier for us to calculate Postfix Expression by using stack.

## Steps of Evaluating Postfix [^1]

• Push operands onto the stack.

• On encountering an operator, pop the requisite

number of operands and push onto the stack the

result of applying the operator to those operands.

Steps Simulation

``````3 10 5 + *
-> 3
push 3
-> 10
push 10
-> 5
push 5
-> +
pop 5, 10
push 15
-> *
pop 15, 3
push 45
``````

Reverse Polish Notation Stack Example [^2]

### Implementing Steps

1. Copy the Stack code on Java Stack Implementation page.

2. Save the Stack code as Stack.java

3. Copy the following code and save as PostfixEvaluation.java

## Code Example

``````/******************************************************************************
*  Compilation:  javac PostfixEvaluation.java
*  Execution:    java PostfixEvaluation arg
*  Dependencies: Stack.java
*
*  Java Postfix expression Calculator.
*
*  % java PostfixEvaluation "3 10 5 + *"
*  45
*
******************************************************************************/
class PostfixEvaluation {
public static void main(String[] args) {
String[] strArr = args[0].split(" ");

System.out.println(calculator(strArr));
}

public static double calculator(String[] strArr) {
Stack<Double> operands = new Stack<Double>();

for(String str : strArr) {
if (str.trim().equals("")) {
continue;
}

switch (str) {
case "+":
case "-":
case "*":
case "/":
double right = operands.pop();
double left = operands.pop();
double value = 0;
switch(str) {
case "+":
value = left + right;
break;
case "-":
value = left - right;
break;
case "*":
value = left * right;
break;
case "/":
value = left / right;
break;
default:
break;
}
operands.push(value);
break;
default:
operands.push(Double.parseDouble(str));
break;
}
}
return operands.pop();
}
}
``````

### Related Questions

4.3.15 Write a program EvaluatePostfix that takes a postfix expression from standard input, evaluates it, and prints the value. (Piping the output of your program from the previous exercise to this program gives equivalent behavior to Evaluate, in PROGRAM 4.3.5.)

[^1]: Robert Sedgewick, Kevin Wayne - Computer Science_ An Interdisciplinary Approach (2016) -P590. [^2]: File:Reverse Polish Notation Stack Example.jpg https://commons.wikimedia.org/wiki/File:Reverse_Polish_Notation_Stack_Example.jpg.