previous | start | next

Assigning one Array to Another

Assigning one array to another doesn't create a copy array.

It just makes both variables reference the one and only array.

To make a copy of an array requires 2 steps:

public static void main(String[] args)
  {
    int[] a = {1,2,3};
    int[] b;
    int[] c;

    // Assign a to b; Still only one array
    b = a;


    // Create a copy of a
    // step (1)
    c = new int[a.length];

    // step (2)
    for(int i = 0; i < a.length; i++) {
      c[i] = a[i];
    }
  }


previous | start | next