How to create a copy of Character Array in Java?
Declaration :
1 |
public static char[] copyOf(char[] original, int newLength) |
Explanation :
Purpose | The java.util.Arrays.copyOf(char[] original int newLength) method copies the specified array truncating or padding with null characters (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 in the copy but not the original the copy will contain ‘\u000’.Such indices will exist if and only if the specified length is greater than that of the original array. |
Parameters | original ===> This is the array to be copied. |
newLength ===> This is the length of the copy to be returned. | |
Return Value | This method returns a copy of the original array truncated or padded with null characters to obtain the specified length. |
Exception | NegativeArraySizeException — If newLength is negative. ,NullPointerException — If original is null. |
Java Program : Example
Below example will explain java.util.Arrays.copyOf() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
package com.c4learn; import java.util.Arrays; public class ArrayDemo { public static void main(String[] args) { // Intialize a character array arr1 char[] arr1 = new char[] { 'a', 'b', 'c' }; // Print the first array System.out.println("First array:"); for (int i = 0; i < arr1.length; i++) { System.out.println(arr1[i]); } // Copy array elements to new array with length 6 char[] arr2 = Arrays.copyOf(arr1, 6); arr2[3] = 'd'; arr2[4] = 'e'; arr2[5] = 'f'; // Print the new array System.out.println("New array:"); for (int i = 0; i < arr2.length; i++) { System.out.println(arr2[i]); } } } |
Output of Program :
1 2 3 4 5 6 7 8 9 10 11 |
First array: a b c New array: a b c d e f |