Copy the range of an Integer Array to another array in Java
Declaration :
1 |
public static int[] copyOfRange(int[] original, int from, int to) |
Explanation :
Purpose | The java.util.Arrays.copyOfRange(int[] 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 0 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 zeros to obtain the required length. |
Exception | ArrayIndexOutOfBoundsException — If from < 0 or from > original.length() ,IllegalArgumentException — 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 an Integer Array int[] arr1 = new int[] { 5, 10, 15, 20, 25, 30, 35, 40 }; // Print the array System.out.println("First array:"); for (int i = 0; i < arr1.length; i++) { System.out.println(arr1[i]); } // Copy the array elements to new array with length 1 to 6 int[] arr2 = Arrays.copyOfRange(arr1, 1, 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 15 |
First array: 5 10 15 20 25 30 35 40 New array: 10 15 20 25 30 |