Skip to content
ExamSpine

Lesson 5.6 · Trace it

Trace: list changes (Java)

Java code4 rows to fill4 marks

Complete the trace table for this Java code. The code runs with ArrayList already imported. add puts a value at the end. remove(1) removes the value at index 1 and gives it back. set(0, 6) puts 6 at index 0. [4]

Line 1: ArrayList<Integer> nums =
Line 2, indented 1 level: new ArrayList<>();
Line 3: nums.add(5);
Line 4: nums.add(3);
Line 5: nums.add(8);
Line 6: nums.set(0, 6);
Line 7: nums.add(4);
Line 8: int x = nums.remove(1);
Line 9: int y = nums.get(1);
Line 10: int n = nums.size();
Line 11: System.out.println(x + y + n);

Fill in one row each time a line changes x, y or n, or prints something. 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. In the output column, write exactly what appears on screen, with no quotes around it.

Rowxynoutput
1
2
3
4