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…
Question
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)- A87% (33)
- B8% (3)
- C3% (1)
- D3% (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 - nonewmeans no new instance. - C (3): Counts the three variable names (
obj1,obj2,obj3) as if each were a distinct object;obj3 = nullholds no object at all, andobj1/obj2share one. - D (4): May also count the
obj4parameter ingraceMarks, 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
Community Discussion
No community discussion yet for this question.