0

I am quite confused as to why my Array is being changed when I do not change the actual variable. This is an example showing how I did the exact same thing to an array and an int but got different results.

import java.util.Arrays;
public class example
{
    public static void main(String[] args)
    {
        int[] arrayInMain = {1,2,3,6,8,4};
        System.out.println("Original Value: " + Arrays.toString(arrayInMain));
        arrayMethod(arrayInMain);
        System.out.println("After Method Value: " + Arrays.toString(arrayInMain));
        int intInMain = 0;
        System.out.println("Original Value: " + intInMain);
        intMethod(intInMain);
        System.out.println("After Method Value: " + intInMain);
    }
    private static void arrayMethod(int[] array)
    {       
        int[]b = array;
        b[1] = 99;//Why does this not just set the local array? The array outside of this method changes
    }
    private static void intMethod(int i)
    {
        int j = i;
        i = 99;//This works normally with only the value of j being changed
    }
}

The output was:

Original Value: [1, 2, 3, 6, 8, 4]
After Method Value: [1, 99, 3, 6, 8, 4]
Original Value: 0
After Method Value: 0

Why is this? Am I making a silly mistake or is this just how Java arrays work?

Thank you!

ReBuff
  • 37
  • 6

1 Answers1

1

Like @khelwood said, you are passing the reference to the array. By changing the reference, you also change the original in Java. What you can do to create an actual copy of your array you can use Arrays.copyOf()

int[] arrayCopy = Arrays.copyOf(yourArray, yourArray.length);
WJS
  • 36,363
  • 4
  • 24
  • 39
david072
  • 58
  • 2
  • 7