Array assignment and reference in Java

前端 未结 5 1484
误落风尘
误落风尘 2020-12-11 08:24
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;
         


        
5条回答
  •  被撕碎了的回忆
    2020-12-11 08:59

    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
    

提交回复
热议问题