1

I got a question about the following piece of code.

class MemArr{
  int[] mem = {1,2};
}

public class Test{
  public static void main(String[] args){
    MemArr[] x = new MemArr[2];  //line 1  
    x[0] = new MemArr();         //line 2
    x[1] = null;                 //line 3  
                                 //line 4
  }
}

How many objects are created in total and how many objects are eligible for garbage collection when line 1 is reached?

I think, that at line 1, there were 5 objects created (1 array x, 2 objects of MemArr in the array x, 2 member variables of integer array for the objects of MemArr)

At line 2, two objects were created (one MemArr object and its member variable mem).

At line 3 when x[1] is set to null, I think that there were in total 4 objects which are eligible for the GC, but I am not very sure about this.

2 Answers 2

2
MemArr[] x = new MemArr[2];

This creates a new MemArr array of 2 elements but it doesn't initialize any of the 2 elements. After that declaration, x[0] and x[1] are both null: the array was instantiated but not its content.

x[0] = new MemArr();

This really assigns a new MemArr to the first element of the array. So it creates one MemArr and another array for the internal int[] mem that it contains.

x[1] = null;

This line doesn't do anything; the value was already null, as said before.

Sign up to request clarification or add additional context in comments.

Comments

1

The first line creates a single array object of 2 elements. Both elements are null by default, so no MemArr objects are created.

The second line creates one MemArr object and one internal array object inside that object.

The third line doesn't create any object. In fact, it makes no difference since x[1] is already null.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.