How to create a 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("
Sub 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: 24-Feb-2020

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements