Languages
[Edit]
EN

Java - create subarray of ints from another array

11 points
Created by:
Lia-Perez
505

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
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join