How many objects are being created in this code snippet

Nemaly Praveen :

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.

Tim Biegeleisen :

In the context of your code, the only two objects I see being explicitly created are the lines in which the new operator appears:

Main m1 = new Main();
Main m3 = new Main();

Here is a breakdown of which is happening in each line:

Main m1 = new Main();     // create new Main object 'm1'
Main m2 = m1;             // assign 'm2' to reference 'm1' (no new object)
Main m3 = new Main();     // create new Main object 'm3'
m2.num = 60;              // assign a field in 'm2' (no new object)
gacemarks(m2);            // repeatedly increment the 'm2.num' field (no new object)
System.out.println(m2);   // print 'm2' (no new object)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=116470&siteId=1