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:
In this code, System.arraycopy takes five parameters:
- The source array (
originalArray) - The starting position in the source array (
startIndex) - The destination array (
subArray) - The starting position in the destination data
- 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:
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:
Summary Table
The table below summarizes the methods discussed for creating subarrays in Java:
| Method | Description | Efficiency |
System.arraycopy | Native method, fast and efficient for copying arrays. | Very High |
Arrays.copyOfRange | Simple and readable, part of Java utilities. | High |
| Manual Loop Copy | Complete 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.

