What does the method copyOf(int[] original, int newLength) do in java?

Java 8Object Oriented ProgrammingProgramming

The copyOf (int[] original, int newLength) method of the java.util.Arrays class copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length. For all indices that are valid in both the original array and the copy, the two arrays will contain identical values. For any indices that are valid within the copy however not the original, the copy can contain zero. Such indices will exist if and only if the specified length is greater than that of the original array.

Example

import java.util.Arrays;

public class ArrayDemo {
   public static void main(String[] args) {
      int[] arr1 = new int[] {45, 32, 75};
      System.out.println("Printing 1st array:");

      for (int i = 0; i < arr1.length; i++) {
         System.out.println(arr1[i]);
      }
      int[] arr2 = Arrays.copyOf(arr1, 5);
      
      arr2[3] = 11;
      arr2[4] = 55;
      System.out.println("Printing new array:");

      for (int i = 0; i < arr2.length; i++) {
         System.out.println(arr2[i]);
      }
   }
}

Output

Printing 1st array:
45
32
75
Printing new array:
45
32
75
11
55
raja
Published on 16-Jan-2018 12:28:29
Advertisements