Copy the range of Long Array to another array in Java
Declaration :
1 |
public static long[] copyOfRange(long[] original, int from, int to) |
Explanation :
Purpose | The java.util.Arrays.copyOfRange(long[] 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 0L 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 a long array long[] arr1 = new long[] { 100, 200, 300 }; // 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 a new array with length 0 to 6 long[] arr2 = Arrays.copyOfRange(arr1, 0, 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 |
First array: 100 200 300 New array: 100 200 300 0 0 0 |