Skip to content
ExamSpine

Lesson 8.1 · Trace it

Trace: two objects (Java)

Java code3 rows to fill3 marks

Complete the trace table for this Java code. Jar is a class. a and b are objects made from it, and sweets is an attribute that each of them keeps. Then answer the question below the table. [3]

Line 1: class Jar {
Line 2, indented 1 level: int sweets;
Line 3: }
Line 4:
Line 5: public class Main {
Line 6, indented 1 level: public static void main(String[] args) {
Line 7, indented 2 levels: Jar a = new Jar();
Line 8, indented 2 levels: a.sweets = 4;
Line 9, indented 2 levels: Jar b = new Jar();
Line 10, indented 2 levels: b.sweets = 9;
Line 11, indented 2 levels: a.sweets = a.sweets + 3;
Line 12, indented 2 levels: b.sweets = b.sweets - a.sweets;
Line 13, indented 2 levels: int x = a.sweets;
Line 14, indented 2 levels: a.sweets = 0;
Line 15, indented 2 levels: int y = b.sweets + a.sweets;
Line 16, indented 2 levels: System.out.println(x + y);
Line 17, indented 1 level: }
Line 18: }

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

Rowxyoutput
1
2
3