Skip to content
ExamSpine

Lesson 5.14 · Trace it

Trace: stack moves (Java)

Java code13 rows to fill3 marks

Complete the trace table for this Java code. The code runs with ArrayList already imported. stack is an ArrayList used as a stack, and its last value is the top. add pushes a value onto the top, and remove(stack.size() - 1) takes the top value off and gives it back. Write the stack in square brackets, bottom first, as Java prints an ArrayList. Then answer the question below the table. [3]

Line 1: ArrayList<Integer> stack =
Line 2, indented 1 level: new ArrayList<>();
Line 3: stack.add(6);
Line 4: stack.add(1);
Line 5: int x = stack.remove(stack.size() - 1);
Line 6: stack.add(8);
Line 7: stack.add(x + 3);
Line 8: int total = 0;
Line 9: while (stack.size() > 0) {
Line 10, indented 1 level: int top = stack.remove(stack.size() - 1);
Line 11, indented 1 level: total = total + top;
Line 12: }

Fill in one row each time a line changes stack, x or total. The table already has the right number of rows. In each row, write only what that line changes; you can leave the other cells empty or copy their values down. Write values the way Java shows them: 3 and 3.0 are different, and text goes in quotes.

Rowstackxtotal
1
2
3
4
5
6
7
8
9
10
11
12
13