Question 15
Back to Exercise
What is the output of the following Java program?
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!