Couple Questions in Java

Started by
1 comment, last by Fenrisulvur 14 years, 2 months ago
Hello everyone. I'm looking to better understand what's going on in a couple occassions, in Java. Thanks in advance. 1.

Object[] a = new Object[10];
Object[] b = a; //ok, what happens here.  does all of 'a' get copied into 'b' or is 'b' a reference of 'a' and whatever I do to 'b' will be done to 'a'?

2.

Object[] a = new Object[10];

for (int i = 0; i < 10; i++) {
    a = new Object();
}

a = new Object[2]; //is all the previous data going to be removed from memory here?  What about if I set the array to null instead, then will it be removed from memory?

Advertisement
That's about right. However for #2 if you set 'a' to anything else including null then it will be garbage collected provided there is no other references to it (ex. #1 won't be garbage collected if 'a' is set to something else since 'b' is still referencing the original memory).
1. a and b now refer to the same array. Also keep in mind that every element in a new array of objects is null until you put things in it - put an object in a[0] and the exact same object will be waiting for you in b[0].

2. Yeah, all the previous data is lost, and will be GC'd in due course. Assigning null would have the same effect, since either way you are no longer keeping any reference to the objects.

This topic is closed to new replies.

Advertisement