Java
Programming
Array
Subarray
Coding Tutorial

How to create a sub array from another array in Java?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Creating a subarray from an existing array in Java can be an essential operation in many programming scenarios, such as data processing, algorithm implementation, or simple manipulation of array contents. Java does not directly provide a built-in method in the Arrays class for extracting subarrays, but there are efficient ways to accomplish this using available Java utilities or custom methods. Here, we will explore some of the common methods and practices to achieve this in Java.

Method 1: Using System.arraycopy

One of the fastest ways to create a subarray in Java is by using the System.arraycopy method. This method is native (implemented in native code), making it very efficient for copying arrays.

Example:

java
1public class SubArray {
2    public static void main(String[] args) {
3        int[] originalArray = {1, 2, 3, 4, 5, 6};
4        int startIndex = 2; // start from index 2
5        int length = 3; // length of the subarray
6
7        int[] subArray = new int[length];
8        System.arraycopy(originalArray, startIndex, subArray, 0, length);
9
10        for (int num : subArray) {
11            System.out.print(num + " "); // Output: 3 4 5
12        }
13    }
14}
15

In this code, System.arraycopy takes five parameters:

  1. The source array (originalArray)
  2. The starting position in the source array (startIndex)
  3. The destination array (subArray)
  4. The starting position in the destination data
  5. The number of array elements to be copied (length)

Method 2: Using Arrays.copyOfRange

Another convenient and more readable method is using Arrays.copyOfRange(). This method is part of the Arrays utility class in Java and provides a straightforward way to copy a range of an array.

Example:

java
1import java.util.Arrays;
2
3public class SubArray {
4    public static void main(String[] args) {
5        int[] originalArray = {1, 2, 3, 4, 5, 6};
6        int startIndex = 2;
7        int endIndex = 5; // up to, but not including, index 5
8
9        int[] subArray = Arrays.copyOfRange(originalArray, startIndex, endIndex);
10
11        for (int num : subArray) {
12            System.out.print(num + " "); // Output: 3 4 5
13        }
14    }
15}

The Arrays.copyOfRange method is particularly useful because it is very readable and reduces the risk of errors associated with array indexing and copying, although it might not be as fast as System.arraycopy.

Method 3: Manual Copy Using a Loop

A more traditional approach might involve manually copying elements from the original array to the new subarray using a for-loop. This method gives you full control over the copying process.

Example:

java
1public class SubArray {
2    public static void main(String[] args) {
3        int[] originalArray = {1, 2, 3, 4, 5, 6};
4        int startIndex = 2;
5        int length = 3;
6
7        int[] subArray = new int[length];
8        for (int i = startIndex; i < startIndex + length; i++) {
9            subArray[i - startIndex] = originalArray[i];
10        }
11
12        for (int num : subArray) {
13            System.out.print(num + " "); // Output: 3 4 5
14        }
15    }
16}

Summary Table

The table below summarizes the methods discussed for creating subarrays in Java:

MethodDescriptionEfficiency
System.arraycopyNative method, fast and efficient for copying arrays.Very High
Arrays.copyOfRangeSimple and readable, part of Java utilities.High
Manual Loop CopyComplete control with manual element copying.Medium

Conclusion

Creating subarrays in Java can be done using a variety of methods depending on the scenario and specific requirements in terms of readability, speed, and control. Whether you need high performance or simple code readability, Java provides suitable options to handle array manipulations effectively. Each method has its own use cases, and choosing the right one depends on the context and specific needs of your application.


Course illustration
Course illustration

All Rights Reserved.