Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array assignment and reference in Java

public class Test {
    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 5};
        int[] b = a;
        int[] c = {6, 7, 8};
        a = c;
        for(int i = 0; i < a.length; i ++)
            System.out.print(a[i] + " ");
        System.out.print("\n");
        for(int i = 0; i < b.length; i ++) 
            System.out.print(b[i] + " ");
        System.out.print("\n");
    }
}

I have initialized array a and assigning reference of a to new array b. Now I initialized a new array c and passed its reference to array a. Since array b is reference to array a, b should have new values that are in c but b is having old values of a. What is the reason behind it? Output is given below -

Output -

6 7 8 
1 2 3 4 5
like image 631
Anuj Gupta Avatar asked Jan 04 '23 20:01

Anuj Gupta


2 Answers

Don't be irritated by the name 'list'. The images are taken from a python visualization, but the principle is the same in Java

Array a is assigned with a new array:

Assigning a

Array b is assigned to the instance behind a:

Assigning b

Array c is assigned with a new array:

Assigning c

And finally a is assigned to the instance behind c, b was not re-assigned and still keeps a reference to the old a:

Re-Assigning a

Images taken from a visualization on pythontutor.com

like image 124
Felix Avatar answered Jan 14 '23 13:01

Felix


When you assigned value of a to b, it means b is referring to same space allocated to array a. This means b will pick up any changes made to the array a, but if any changes made to the variable a. If a is made to refer to new array, b will still refer the old a reference.

b = a;  // b basically referring to memory used by array a
a = c;  // reference pointed by a has changed, but b is still referring the old array a
like image 33
Nipun Avatar answered Jan 14 '23 12:01

Nipun