- 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)); } }
- 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]
- 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)); } }
- 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]
- Find Arrays in the Java online documentation and review the method copyOf. The link is here.