Create Subarray from Another Array in Java



Use Arrays.copyOfRange() method to get a subarray.

Example

import java.util.Arrays;
public class Tester {
   public static void main(String[] args) {
      int[] array = new int[] {1, 2, 3, 4, 5};
      int[] subArray = Arrays.copyOfRange(array, 0, 2);
      System.out.println("Array: ");
      for(int i = 0; i < array.length; i++) {
         System.out.print(array[i] + " ");
      }
      System.out.println("\nSub array: ");
      for(int i = 0; i < subArray.length; i++) {
         System.out.print(subArray[i] + " ");
      }
   }
}

Output

Array:
1 2 3 4 5
Sub array:
1 2
Updated on: 2020-02-24T10:42:51+05:30

17K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements