Search code examples
javaarraysreferenceprimitive

Why do these two cases show different results for Array elements in Java?


Here, the value of Array arr elements do not change after changing values of a and b.

int a=10, b=20;
int[] arr = {a,b};
a = 20;
b = 10;
System.out.println("a = " + a); // a=20
System.out.println("b = " + b); // b=10
System.out.println(Arrays.toString(arr)); // prints [10, 20]

Here, intArr2 elements change value once you change value of IntArr elements.

int[] intArr = {10,12};
int[] intArr2 = intArr;
intArr[1] = 1000;
System.out.println("intArr2[1]: " + intArr2[1]); // prints 1000

And here, it doesn't change the value of str Array elements:

        String word1="abc";
        String word2="def";
        String[] str = {word1, word2};
        word1 = str[1];
        word2 = str[0];
        System.out.println("word1 = " + word1); //def
        System.out.println("word2 = " + word2); //abc
        System.out.println(Arrays.toString(str)); // prints [abc, def]

Can someone please explain this?


Solution

  • In first case, values of a & b are assigned to array arr. So after assigned any change in a, b doesn't reflect to arr.

    In second case intArr2 is using the reference of intArr, so any change in any one of these array should reflect both, in fact the location is unique.

    Does it make sense to you?