tags:

views:

142

answers:

4

are these two the same things?

for(int i=0; i<array.length; i++){
array[i] = null;
}

and

array = null;
+6  A: 

No, the first one makes each element of the array null, the length of the array will still be array.length, the second will set the array variable to null.

John Boker
A: 

Not at all.

In the first case you're setting all the references in your array to null.

In the second case you're setting the very reference to the array itself to null.

Webinator
+6  A: 

A small snippet to show the difference:

// declare a array variable that can hold a reference.
String [] array;

// make it null, to indicate it does not refer anything.
array = null;

// at this point there is just a array var initialized to null but no actual array.

// now allocate an array.
array = new String[3];

// now make the individual array elements null..although they already are null.
for(int i=0;i<array.length;i++)
{
    array[i] = null;
}
// at this point we have a array variable, holding reference to an array, 
// whose individual elements are null.
codaddict
After the first statement `array = null;` your statement "...just a reference to a String..." is not quite correct. This really is a variable that can hold a reference but there is no reference.
Kevin Brock
@Kevin: Thanks :)
codaddict
+1 : Nice answer
Chankey Pathak
+2  A: 

No, it is not the same.

As a matter of fact, for the first snippet of code to run correctly, the array variable should be declared and initialized like this (for example)

Object[] array = new Object[5];

This creates an array of 5 elements with each element having a null value.

Once you have this, in the first example what you are doing is assigning a null value to each of the array[i] elements. array will not be null. So you should have something like this.

array ->

  • array[0] -> null
  • array[1] -> null
  • array[2] -> null
  • array[3] -> null
  • array[4] -> null

By doing array = null you are saying that the array no longer references that array of elements. Now you should have

array -> null

Lombo