CH8 – Copying Arrays

  1. Create a new class named CopyingArrays and add the following code.
import java.util.Arrays;
public class CopyingArrays{
  public static void main(String[] args){
    double[] a = {22.223, 33.1, 25.34, 11.34};
    double[] b = a;
    a[1] = 44.33;
    System.out.println(Arrays.toString(a));
    System.out.println(Arrays.toString(b));
  }
}
  1. Compile and run the program.
$ javac CopyingArrays.java 
$ java CopyingArrays
[22.223, 44.33, 25.34, 11.34]
[22.223, 44.33, 25.34, 11.34]
  1. Modify main so that it uses the Arrays.copyOf method.
import java.util.Arrays;
public class CopyingArrays{
  public static void main(String[] args){
    double[] a = {22.223, 33.1, 25.34, 11.34};
    double[] b = a;
    double[] c = Arrays.copyOf(a, 4);
    a[1] = 44.33;
    System.out.println(Arrays.toString(a));
    System.out.println(Arrays.toString(b));
    System.out.println(Arrays.toString(c));
  }
}
  1. Compile and run the program.
$ javac CopyingArrays.java 
$ java CopyingArrays
[22.223, 44.33, 25.34, 11.34]
[22.223, 44.33, 25.34, 11.34]
[22.223, 33.1, 25.34, 11.34]
  1. Find Arrays in the Java online documentation and review the method copyOf. The link is here.