How to create a subarray from another array in Java

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 06-Feb-2018 11:01:01
Advertisements