Languages
[Edit]
EN

Java - create subarray of ints from another array

11 points
Created by:
JustMike
3488

In java there is couple of ways how to create subarray, the simples way I know with simple code example is presented here.

1. Java subarray with Arrays.copyOfRange

Syntax:

int[] copyOfRange(int[] original, int from, int to)

Code example:

int[] arr = {10, 20, 30, 40, 50, 60};
int[] subArr1 = Arrays.copyOfRange(arr, 0, 2);
int[] subArr2 = Arrays.copyOfRange(arr, 2, 6);

System.out.println(Arrays.toString(arr));     // [10, 20, 30, 40, 50, 60]
System.out.println(Arrays.toString(subArr1)); // [10, 20]
System.out.println(Arrays.toString(subArr2)); // [30, 40, 50, 60]

Output:

[10, 20, 30, 40, 50, 60]
[10, 20]
[30, 40, 50, 60]

Reference:

  1. Arrays.copyOfRange - java docs
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.