Reputation: 834
I'm studying for 1z0-803 Java certificate exam at the moment. We have to find out, how many instances of MarkList
are created in this application:
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;
obj2.num = 60;
graceMarks(obj2);
}
}
A friend of mine said that in this question the answer is two objects. I think it's only one (obj1
), though I may be wrong since I'm new with Java but have some experience with C#.
Upvotes: 3
Views: 2368
Reputation: 451
Forget about this question. This exam question has a typo if you randomly search online. Many websites mentioned obj3 but it wasn't there. Your friend might read from a source that contains a typo.
Upvotes: 1
Reputation: 21576
Only one instance of MarkList is created.
For to find out how many objects are created you can use this procedure:
new MarkList(...)
). You can use an IDE like eclipse to find all references.However thousands of other instances are created (in my Oracle JDK 1.8).
MarkList.class
is createdString[] args
is createdMarkList obj1
is createdThread.currentThread()
are created)Use a profiler, run your code and count the objects. But keep in mind, that that result will be quite dependent on your JVM implementation.
Upvotes: 7
Reputation: 2790
The answer is one object.
MarkList obj1 = new MarkList();
creates a new MarkList
object, MarkList obj2 = obj1;
only creates a reference to obj1
so both point to the exact same object.
All the other code is just boilerplate and does not create objects.
Upvotes: 9