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








Syntax

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

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

Example

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

/*w  w  w.  jav a 2 s  . co m*/

import java.util.Arrays;

public class Main {

  public static void main(String[] args) {
    
    char[] arr1 = new char[] {'j', 'a', 'v'};

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

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

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

The code above generates the following result.