How to create a sub array from another array in Java?

There are a few different ways to create a subarray from another array in Java:

  1. Using Arrays.copyOfRange:
int[] originalArray = {1, 2, 3, 4, 5};
int[] subArray = Arrays.copyOfRange(originalArray, 1, 4);
// subArray is now {2, 3, 4}
  1. Using System.arraycopy:
int[] originalArray = {1, 2, 3, 4, 5};
int[] subArray = new int[3];
System.arraycopy(originalArray, 1, subArray, 0, 3);
// subArray is now {2, 3, 4}
  1. Using a loop:
int[] originalArray = {1, 2, 3, 4, 5};
int[] subArray = new int[3];
for (int i = 0; i < 3; i++) {
    subArray[i] = originalArray[i + 1];
}
// subArray is now {2, 3, 4}
  1. Using List.subList:
int[] originalArray = {1, 2, 3, 4, 5};
List<Integer> originalList = IntStream.of(originalArray).boxed().collect(Collectors.toList());
List<Integer> subList = originalList.subList(1, 4);
// subList is now [2, 3, 4]