LearnFrenzy
Sign in Take a free test

Data Structures in Java · Data Structures in Java Output Questions · Question 15

Evaluating a postfix expression with a stack Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 15 Back to Exercise

What is the output of the following Java program?

Main.java
import java.util.ArrayDeque;
import java.util.Deque;

public class Main {
    public static void main(String[] args) {
        String expr = "5 1 2 + 4 * + 3 -";
        Deque<Integer> st = new ArrayDeque<>();
        for (String tok : expr.split(" ")) {
            switch (tok) {
                case "+" -> st.push(st.pop() + st.pop());
                case "*" -> st.push(st.pop() * st.pop());
                case "-" -> { int b = st.pop(), a = st.pop(); st.push(a - b); }
                default -> st.push(Integer.parseInt(tok));
            }
        }
        System.out.println(st.pop() + " " + st.isEmpty());
    }
}
  • A 14 false
  • B 20 true
  • C 14 true Correct
  • D -14 true
Correct Answer: Option C

1 + 2 = 3, 3 × 4 = 12, 5 + 12 = 17, 17 − 3 = 14. For − the second pop is the left operand.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links