Java Collection Tutorial - Java Arrays.copyOf(int[] original, int newLength)








Syntax

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

public static int[] copyOf(int[] original,  int newLength)

Example

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

//from   w w w . j a  v a  2s.c o  m

import java.util.Arrays;

public class Main {

  public static void main(String[] args) {

    // intializing an array arr1
    int[] arr1 = new int[] {1, 2, 3};


    System.out.println(Arrays.toString(arr1));

    // copying array arr1 to arr2 with newlength as 5
    int[] arr2 = Arrays.copyOf(arr1, 5);
    arr2[3] = 4;
    arr2[4] = 5;   


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

The code above generates the following result.