Skip to content
ExamSpine

Lesson 5.16 · Trace it

Trace: queue moves (Java)

Java code15 rows to fill3 marks

Complete the trace table for this Java code. The code runs with ArrayList already imported. queue is an ArrayList used as a queue: its first value is the front and its last value is the back. add adds a value at the back, and remove(0) takes the front value off and gives it back. Write the queue in square brackets, front first, as Java prints an ArrayList. Then answer the question below the table. [3]

Line 1: ArrayList<Integer> queue =
Line 2, indented 1 level: new ArrayList<>();
Line 3: queue.add(3);
Line 4: queue.add(8);
Line 5: int x = queue.remove(0);
Line 6: queue.add(5);
Line 7: queue.add(x + 4);
Line 8: int total = 0;
Line 9: while (queue.size() > 0) {
Line 10, indented 1 level: int front = queue.remove(0);
Line 11, indented 1 level: if (front < 6) {
Line 12, indented 2 levels: queue.add(front + 4);
Line 13, indented 1 level: } else {
Line 14, indented 2 levels: total = total + front;
Line 15, indented 1 level: }
Line 16: }

Fill in one row each time a line changes queue, 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.

Rowqueuextotal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15