Copy the range of Character Array to another array in Java
Declaration :
1 |
public static char[] copyOfRange(char[] original, int from, int to) |
Explanation :
Purpose | The java.util.Arrays.copyOfRange(char[] original int from int to) method copies the specified range of the specified array into a new array.The final index of the range (to) which must be greater than or equal to from may be greater than original.length in which case ‘\u000’ is placed in all elements of the copy whose index is greater than or equal to original.length - from. The length of the returned array will be to - from. |
Parameters | original ===> This is the array from which a range is to to be copied. |
from ===> This is the initial index of the range to be copied inclusive. | |
to ===> This is the final index of the range to be copied exclusive. | |
Return Value | This method returns a new array containing the specified range from the original array truncated or padded with null characters to obtain the required length. |
Exception | ArrayIndexOutOfBoundsException — If from < 0 or from > original.length() ,IllegalArgumentException — If if from > to. ,NullPointerException — If original is null. |
Java Program : Example
Below example will explain java.util.Arrays.copyOfRange() 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 |
package com.c4learn; import java.util.Arrays; public class ArrayDemo { public static void main(String[] args) { // Initialize a Character Array char[] arr1 = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' }; // Print first array System.out.println("First array:"); for (int i = 0; i < arr1.length; i++) { System.out.println(arr1[i]); } // Copy array elements to the new array with range 2 to 6 char[] arr2 = Arrays.copyOfRange(arr1, 2, 6); // 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 12 13 14 |
First array: a b c d e f g h New array: c d e f |