Java Arrays.copyOf(T[] original, int newLength)

Syntax

Arrays.copyOf(T[] original, int newLength) has the following syntax.

public static <T> T[] copyOf(T[] original,  int newLength)

Example

In the following code shows how to use Arrays.copyOf(T[] original, int newLength) method.


/*from   w  w  w  .j  av  a2 s.  c o  m*/

import java.util.Arrays;

public class Main {

   public static void main(String[] args) {

      short[] arr1 = new short[]{1, 10, 25};


      System.out.println(Arrays.toString(arr1));
      
      // copying array arr1 to arr2 with newlength as 5 as Object
      Object arr2 = Arrays.copyOf(arr1, 5);

      // cast arr2 as short in order to be printable
      short[] arr3 = (short[]) arr2;


      System.out.println(Arrays.toString(arr3));
   }
}

The code above generates the following result.