21
public class TestingArray {

    public static void main(String[] args) {

        int iCheck = 10;
        int j = iCheck;
        j = 11;
        System.err.println("value of iCheck "+iCheck);

        int[] val1 = {1,2,9,4,5,6,7};
        int[] val2 = val1;
        val2[0] = 200;
        System.err.println("Array Value "+val1[0]);
    }
}

Output:

value of iCheck 10
Array Value 200

From the above code, I found that if any array val2 is being assigned to another array val1 and if we change any value of val2 array, the result is as well reflected for the array val1 while the same scenario is not with variable assignment. Why?

4 Answers 4

39

The following statement makes val2 refer to the same array as val1:

int[] val2 = val1;

If you want to make a copy, you could use val1.clone() or Arrays.copyOf():

int[] val2 = Arrays.copyOf(val1, val1.length);

Objects (including instances of collection classes, String, Integer etc) work in a similar manner, in that assigning one variable to another simply copies the reference, making both variables refer to the same object. If the object in question is mutable, then subsequent modifications made to its contents via one of the variables will also be visible through the other.

Primitive types (int, double etc) behave differently: there are no references involved and assignment makes a copy of the value.

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

Comments

4

Simply put, "val1" and "val2" are pointers to the actual array. You're assigning val2 to point to the same array as val1. Therefore, change one, and the other sees the same change. To have it truly be a copy, you'd have to clone the array instead of assigning.

Comments

4

Because arrays in Java are objects, i.e. passed by reference.

Comments

1

Because you assign a reference of val1 to val2, so they both point to the same object in the memory.

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.