Languages
[Edit]
EN

Java - copy sub-array

8 points
Created by:
Payne
654

In this short article, we would like to show how to copy sub-array in Java.

Quick solution:

int[] subarray = Arrays.copyOfRange(array, from, to);

 

Practical example

In this section, you can find embedded function that lets to copy array part. Function accepts array, start and end indexes.

import java.util.Arrays;

class Program {

    public static void main(String[] args) {
        
        int[] array = new int[] {1, 2, 3, 4, 5, 6};
        int[] subarray = Arrays.copyOfRange(array, 1, 4);

        System.out.println(Arrays.toString(subarray));
    }
}

Output:

[2, 3, 4]

Note: Arrays.copyOfRange() was introduced in Java 1.6.

 

Alternative solution

Example Program.java file:

public class Program {

    public static void main(String[] args) {
        
        int[] array = new int[] {1, 2, 3, 4, 5, 6};
        int[] subarray = ArrayUtils.copyArray(array, 1, 4);

        System.out.println(Arrays.toString(subarray));
    }
}

Output:

[2, 3, 4]

 

Example ArrayUtils.java file:

import java.util.Arrays;
import java.lang.IllegalArgumentException;

public class ArrayUtils {
    
    public static int[] copyArray(int[] array, int start, int end) {
        if (start > end) {
            throw new IllegalArgumentException("The start index cannot be greater than the end index.");
        }
        int[] result = new int[end - start];
        System.arraycopy(array, start, result, 0, result.length);
        return result;
    }
}

 

Alternative titles

  1. Java - clone sub-array
  2. Java - get sub-array
  3. Java - extract sub-array
  4. Java - copy subarray
  5. Java - clone subarray
  6. Java - get subarray
  7. Java - extract subarray
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