[Java] Ho to get a sub array from an array with start index and end index?
I want to create a sub array with start and end indexes from another array, how can I do this in Java?
1 Answer
3 years ago by Eleven
Using Array util method Arrays.copyOfRange
we can create a sub array. It takes originalArray, fromIndex, toIndex as inouts and return a new array. Following code shows how to use it
Note: toIndex is exclusive, i.e element at that index is not included.
import java.util.Arrays;
public class JavaArrays {
public static void main(String[] args) {
int[] numbers = { 45, 22, 67, 90, 47, 88 };
int fromIndex = 1;
int toIndex = 3;
int[] subArray = Arrays.copyOfRange(numbers, fromIndex, toIndex);
System.out.println("Subarray is: " + Arrays.toString(subArray));
}
}
Output:
Subarray is: [22, 67]
Try online here: https://onecompiler.com/java/3xmswryc9
3 years ago by Karthik Divi