Assume the following Java code:
public class Item {
// Instance variables
Item next;
int i;
String s;
// Constructor
public Item(int x, String msg) { i = x; s = msg; next = null; }
// Other methods ...
}
public class ItemDemo {
public static void main(String argv[]) {
Item head = null, newitem = null, ptr = null;
// code appears in numbered fragments below ...
}
}
Assume the numbered code fragments below are executed in they order they appear.
Draw a diagram showing variables, values, objects, and references in memory after each code fragment executes.
If the code fragment contains a print or
println statement,
write what the statement prints.
Draw a variable as a box with the variable name as a label to the side and the value inside the box. Draw an object as a box containing instance variables. Draw references as arrows with a spot at the variable end and an arrowhead at the object end. Draw an X for the null reference.
head = new Item(1, "a");
Here is the diagram:
+--------------+
+-----+ | +-----+ |
head | o--+----->| next | X | |
+-----+ | +-----+ |
| +-----+ |
| i | 1 | |
| +-----+ |
| +-----+ |
| s | o--+-+---> "a"
| +-----+ |
+--------------+
newitem = new Item(2, "b");
newitem.next = head; head = newitem;
newitem = new Item(3, "c"); newitem.next = head; head = newitem; System.out.println(head.i + " " + head.next.i + " " + head.next.next.i);
ptr = head;
System.out.print("head -> " + ptr.i + ". " + ptr.s);
ptr = ptr.next;
if (ptr != null) {
System.out.print(" -> " + ptr.i + ". " + ptr.s);
ptr = ptr.next;
} else System.out.println(";");
if (ptr != null) {
System.out.print(" -> " + ptr.i + ". " + ptr.s);
ptr = ptr.next;
} else System.out.println(";");
if (ptr != null) {
System.out.print(" -> " + ptr.i + ". " + ptr.s);
ptr = ptr.next;
} else System.out.println(";");
ptr = head;
if (ptr != null && ptr.i != 2) {
ptr = ptr.next;
} else System.out.println(ptr.i + ". " + ptr.s);
if (ptr != null && ptr.i != 2) {
ptr = ptr.next;
} else System.out.println(ptr.i + ". " + ptr.s);
if (ptr != null && ptr.i != 2) {
ptr = ptr.next;
} else System.out.println(ptr.i + ". " + ptr.s);
while loop.
for loop.