Hi guys~!

Consider the following code:

public void reset(int[] arr)
{
    for (int i=0;i<arr.length;i++)
    {
        arr[i]=0;
    }
}

I know that regardless of what the actual array is before this method is called it will not change afterward because the method cannot modify it since it is not a local field. My question is why: shouldn't the array still be modified because the array stored at the reference that arr points to is being modified within the method? I know that it isn't modified after this is run, but I want to understand why. Especially since the following DOES modify the array:

public int[] reset(int[] arr)
{
    int[] foo = arr;
    for (int i=0;i<arr.length;i++)
    {
        arr[i]=0;
    }
    return foo;
}

Recommended Answers

All 4 Replies

Have you actually tried the first example? You may be surprised.

Yes I tried it. Here is my code:

public class test
{
    public static void main(String[] args)
    {
        int[] arr = {1,2,3,4,5};
        for (int i:arr)
            System.out.println(i);
    }
    
    public static void reset(int[] arr)
    {
        for (int i=0;i<arr.length;i++)
        {
            arr[i]=0;
        }
    }
}

This outputs 1 2 3 4 5, not 0 0 0 0 0. Hence, the method does not appear to do anything. Why doesn't it?

Because you never called the reset method from within main.

public class ArrayReference {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] array = {1, 2, 3, 4, 5};
		setArray(array);
		for (Integer i: array) System.out.println(i);
	}
	
	public static void setArray(int[] array){
		array[0] = 6;
		array[1] = 7;
		array[2] = 8;
		array[3] = 9;
		array[4] = 10;
		
		array = new int[5];
		array[0] = 1;
		array[1] = 2;
		array[2] = 3;
		array[3] = 4;
		array[4] = 5;		
	}

}

What you have to consider is what your 'array' variable actually points to. Changing the contents of your 'array' variable from another method will change the contents of 'array' back in main(). But changing the reference of the 'array' variable from another method will not change the reference back in main. Hence lines 20-25 in my above code have no affect on 'array' back in main because on line 20 what 'array' referred to changed, but only for the method I'm currently in.

Oh wow I forgot to call the method... stupid me >.<

Tyvm BJSJC, that clarified it :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.