- Create a new class named ArrayLength and add the following code.
public class ArrayLength{ public static void main(String[] args){ double[] a = {1.0,2.0,3.0,4.0}; double[] b = new double[a.length]; for (int i = 0; i < a.length;i++){ b[i] = a[i]; } for(int j = 0; j < b.length;j++){ System.out.println("a[" + j + "]=" + a[j] + " b[" + j + "]=" + b[j]); } } }
- Compile and run the program.
$ javac ArrayLength.java $ java ArrayLength a[0]=1.0 b[0]=1.0 a[1]=2.0 b[1]=2.0 a[2]=3.0 b[2]=3.0 a[3]=4.0 b[3]=4.0
- Add the following two lines to the end of main.
double[] c = Arrays.copyOf(a, a.length); System.out.println(Arrays.toString(c));
- Import java.util.Arrays at the top of the class.
import java.util.Arrays;
- Compile and run the program.
$ javac ArrayLength.java $ java ArrayLength a[0]=1.0 b[0]=1.0 a[1]=2.0 b[1]=2.0 a[2]=3.0 b[2]=3.0 a[3]=4.0 b[3]=4.0 [1.0, 2.0, 3.0, 4.0]
The complete class should appear as follows.
import java.util.Arrays; public class ArrayLength{ public static void main(String[] args){ double[] a = {1.0,2.0,3.0,4.0}; double[] b = new double[a.length]; for (int i = 0; i < a.length;i++){ b[i] = a[i]; } for(int j = 0; j < b.length;j++){ System.out.println("a[" + j + "]=" + a[j] + " b[" + j + "]=" + b[j]); } double[] c = Arrays.copyOf(a, a.length); System.out.println(Arrays.toString(c)); } }