OneBite.Dev - Coding blog in a bite size

extract a sub-array from an array in java

Code snippet on how to extract a sub-array from an array in java

  int[] arr = {1, 2, 3, 4, 5};
  int[] sub = Arrays.copyOfRange(arr, 0, 3);

This code will create a new array called “sub” which will contain a sub-array extracted from a larger array called “arr”. The “arr” array contains the numbers 1, 2, 3, 4, and 5. The Arrays.copyOfRange() method is used to copy a portion of this larger array, from index 0 to index 3, which is determined by the two arguments passed in to the method: 0 and 3. This will create an array which contains the numbers 1, 2, and 3, and it will be stored in the new “sub” array.

java