nerdexam
Oracle

1Z0-808 · Question #26

Given: ``java public class MarkList { int num; public static void graceMarks(MarkList obj4) { obj4.num += 10; } public static void main(String[] args) { MarkList obj1 = new MarkList(); MarkList obj2…

The correct answer is A. 1. Only one MarkList instance exists because new MarkList() appears exactly once in the entire program - on the line MarkList obj1 = new MarkList();. The subsequent assignments obj2 = obj1 and passing obj2 to graceMarks do not create new objects; they merely create additional…

Java Basics

Question

Given:
public class MarkList {
 int num;
 public static void graceMarks(MarkList obj4) {
 obj4.num += 10;
 }
 public static void main(String[] args) {
 MarkList obj1 = new MarkList();
 MarkList obj2 = obj1;
 MarkList obj3 = null;
 obj2.num = 60;
 graceMarks(obj2);
 }
}
How many MarkList instances are created in memory at runtime?

Options

  • A1
  • B2
  • C3
  • D4

How the community answered

(38 responses)
  • A
    87% (33)
  • B
    8% (3)
  • C
    3% (1)
  • D
    3% (1)

Explanation

Only one MarkList instance exists because new MarkList() appears exactly once in the entire program - on the line MarkList obj1 = new MarkList();. The subsequent assignments obj2 = obj1 and passing obj2 to graceMarks do not create new objects; they merely create additional references pointing to that same single heap object, so changes via obj2 or obj4 all affect the same num field.

Why the distractors fail:

  • B (2): Conflates obj2 = obj1 (reference copy) with object creation - no new means no new instance.
  • C (3): Counts the three variable names (obj1, obj2, obj3) as if each were a distinct object; obj3 = null holds no object at all, and obj1/obj2 share one.
  • D (4): May also count the obj4 parameter in graceMarks, but method parameters are just another reference - still the same lone object.

Memory tip: Count the new keywords - each new ClassName() is the only way to instantiate an object in Java, so the number of instances equals the number of new calls, regardless of how many reference variables point to them.

Topics

#object instantiation#reference variables#memory allocation

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice