-2

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?

trincot
  • 317,000
  • 35
  • 244
  • 286
Seth
  • 3
  • 2
  • in the first case, you define the array based upon the values of a and b. But their correlation ends there. – Andrea Dec 13 '19 at 16:27
  • See also: [Is Java pass-by-value or pass-by-reference](https://stackoverflow.com/q/40480/3419894). Once you understand that concept (and realise that arrays are *always* objects, never primitives) you should be in a good place to be able to answer this question for yourself. – JonK Dec 13 '19 at 16:29

2 Answers2

0

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?

User_67128
  • 1,230
  • 8
  • 21
  • Then, what about in this case: – Seth Dec 13 '19 at 16:38
  • @Seth If you read through the question I linked you should be able to arrive at the answer to both questions yourself – JonK Dec 13 '19 at 16:42
  • As JonK said, you can see this one as well, https://stackoverflow.com/questions/3297867/difference-between-string-object-and-string-literal – User_67128 Dec 13 '19 at 16:58
-1

Every object, has 2 things that can make it be distinguished.

  • Its Value
  • Its address

one is having a value(intArr) and the other is having address (intArr2)

pred
  • 29
  • 7