Misconception: Students may think that assigning one array to point to another array makes a copy of that array, failing to make a distinction between shallow and deep copies.

Like(89 Likes)
  • Provide students with contrasting examples of array creation to help them see that assigning one array to point to another array doesn’t make a copy of that array. Use the below activity to help students develop and understanding of this common error.
  • Activity:
    • Provide students the following code:
      • Version 1: Point two arrays references to the same array.
        • int[] arrayX = new int[10];
          int[] arrayY = arrayX;

          arrayX[0] = 1000;
          System.out.println(arrayX[0]); // prints 1000
          System.out.println(arrayY[0]); // prints 1000

          arrayY[1] = 2000;
          System.out.println(arrayY[1]); // prints 2000
          System.out.println(arrayX[1]); // prints 2000

      • Version 2: Point two array references each to separate arrays.
        • int[] arrayX = {1, 1, 1, 1, 1, 1, 1};
          int[] arrayY = {2, 2, 2, 2, 2, 2, 2, 2, 2};

          arrayX[0] = 1000;
          System.out.println(arrayX[0]); // prints 1000
          System.out.println(arrayY[0]); // prints 2

          arrayY[1] = 2000;
          System.out.println(arrayY[1]); // prints 2000
          System.out.println(arrayX[1]); // prints 1

      • Additionally, the code in Version 1 and Version 2 provides the opportunity to talk about:
        • The fact array indexing starts at 0.
        • The fact that we can initialize an array with values:
          • int[] arrayX = {1, 1, 1, 1, 1, 1, 1};
          • int[] arrayY = {2, 2, 2, 2, 2, 2, 2, 2, 2};
        • The fact that arrays are given default values (null for Objects, 0 for ints, false for booleans etc.)
          • int[] arrayX = new int[10];
            System.out.println(arrayX[0]); // prints 0
External Source

Interview with Dan Leyzberg.

Other Tips By