Question 19
Back to Exercise
What is the output of the following Java program?
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Map;
import java.util.function.Consumer;
public class Main {
public static void main(String[] args) {
Deque<Integer> stack = new ArrayDeque<>();
Map<String, Consumer<Deque<Integer>>> cmds = Map.of(
"dup", s -> s.push(s.peek()),
"add", s -> s.push(s.pop() + s.pop()),
"mul", s -> s.push(s.pop() * s.pop()),
"neg", s -> s.push(-s.pop()));
for (String tok : "3 4 add dup mul neg 2 add".split(" ")) {
Consumer<Deque<Integer>> c = cmds.get(tok);
if (c != null) c.accept(stack); else stack.push(Integer.parseInt(tok));
}
System.out.println(stack);
}
}
- A [-47] Correct
- B [47]
- C [-49, 2]
- D [-51]
Correct Answer: Option A
3 + 4 = 7, dup → 7 7, mul → 49, neg → −49, push 2, add → −47. Each command is a Consumer lambda.
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!