How many objects will be created for this code?
class Main {
int num;
public static void gacemarks(Main m)
{
m.num += 10;
}
public static void main(String[] args) {
Main m1 = new Main();
Main m2 = m1;
Main m3 = new Main();
m2.num = 60;
gacemarks(m2);
System.out.println(m2);
}
}
The answer is 2. But I got 3. m1 will be created, m2 refers to the same object m3 is created newly and after the call, the m object is generated.
newstatement (orclone()method, but that's another story) is called.m1andm2refer to oneMainobject.m3refers to anotherMainobject. That's 2Mainobjects total.System.out.println(m2.num)aftergacemarks(m2);. You should get 70 then becausemis a reference to the object that is refered to bym2. (I assume thatSystem.out.println(m2)doesn't show that because you didn't overridetoString()).