Consider the following java code:
JavaScript
x
class Person {
String name;
int age;
}
Person p1 = new Person();
Person p2 = new Person();
Person p3 = p2;
p3 = p1;
How many total objects and reference variables are created here? Is name
created even though it was never instantiated? 2 Objects are created but are there 3 or 5 reference variables?
Advertisement
Answer
2 objects are initialised, p1
and p2
.
String name
will default to null
but has a reference, so 2 references, one per instantiation of Person
.
int
is a primitive and will default to 0, nothing objecty going on here.
p3
is a reference.
The last line is assignment, nothing created here.
The answer is 5.