To split an array in Java, choose the index where it should divide and copy each range with Arrays.copyOfRange(). To divide an array into several fixed-size chunks, repeat that operation in a loop. Java arrays have a fixed length, so splitting creates new arrays; it does not divide or resize the original.
The right approach depends on what you mean by “split”: you might want two arrays at a particular boundary, equal halves, or a sequence of smaller chunks. The examples below use standard Java arrays and work with object arrays as well as primitive arrays, with small syntax differences for primitive types.
What You’ll Need
- A Java development environment and a class in which to try the examples.
- An existing array, such as an
int[]orString[]. java.util.Arraysfor thecopyOfRangeexamples. Addimport java.util.Arrays;at the top of your file, or use the full namejava.util.Arrays.
Step-by-Step
- Choose the kind of split you need. Decide whether you are dividing the array once at a chosen position, making two halves, or producing chunks of a particular maximum size. Also decide what should happen if the array is empty or its length is not evenly divisible. Being explicit about these cases makes the code easier to use and prevents accidental data loss.
- Record the split boundary. Java array indexes start at zero. For an array of length
n, valid element indexes run from0throughn - 1, while a range boundary can be as large asn. If the first result should contain the first three items, use boundary3: the first range is from index zero up to, but not including, index three. The second range starts at index three. - Copy two ranges with
Arrays.copyOfRange(). This is usually the clearest option for a single split. Its start index is inclusive and its end index is exclusive, which means the element at the end index is not copied. Here is a complete example that divides an integer array after its third element:import java.util.Arrays; public class SplitExample { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40, 50, 60}; int splitAt = 3; int[] left = Arrays.copyOfRange(numbers, 0, splitAt); int[] right = Arrays.copyOfRange(numbers, splitAt, numbers.length); System.out.println(Arrays.toString(left)); System.out.println(Arrays.toString(right)); } }The output is
[10, 20, 30]followed by[40, 50, 60]. Both results are new arrays. Changing an element inleftdoes not change the corresponding position innumbers. For an object array, use the same pattern; for example, declareString[] leftand callArrays.copyOfRange(names, 0, splitAt). - Validate the boundary before copying. A safe boundary is between zero and the source array’s length, inclusive. For example, a split at zero creates an empty first array and a second array containing everything; a split at the length creates the reverse. If a boundary comes from user input or a calculation, check it before calling the method:
if (splitAt < 0 || splitAt > numbers.length) { throw new IllegalArgumentException("Split index is out of range"); }A negative start or a start beyond the source length is invalid. Do not depend on the method’s behavior to validate your application’s input. In particular, if the requested end is greater than the source length,
copyOfRangepads the result with default values, such as zero forint[]andnullfor a reference array. That may compile and run while giving you a result you did not intend. - Split into equal halves when that is the goal. Calculate the midpoint with
array.length / 2, then use it as the boundary. If the length is odd, integer division rounds down, so the first half will have one fewer element than the second. For example, an array of five items splits into ranges of two and three. If you want the extra item in the first half instead, use(array.length + 1) / 2as the boundary. Choose the rule deliberately and document it if other code relies on the sizes. - Make fixed-size chunks with a loop. For chunks of maximum size
chunkSize, start at zero and advance by that size until the array is consumed. Limit each chunk’s end to the source length so the final chunk can be shorter:import java.util.ArrayList; import java.util.Arrays; import java.util.List; int[] values = {1, 2, 3, 4, 5, 6, 7}; int chunkSize = 3; List<int[]> chunks = new ArrayList<>(); if (chunkSize <= 0) { throw new IllegalArgumentException("Chunk size must be positive"); } for (int start = 0; start < values.length; start += chunkSize) { int end = Math.min(start + chunkSize, values.length); chunks.add(Arrays.copyOfRange(values, start, end)); }Here,
chunkscontains arrays of lengths three, three, and one. An empty input produces an empty list because the loop does not run. This example uses a list because the number of chunks depends on the input length; a Java array itself cannot grow to hold an unknown number of results. - Check the results and preserve the original if needed. Print the pieces with
Arrays.toString(), or compare their lengths and contents in a test. For a split into two parts, the result lengths should add up to the source length. Also confirm that reading the pieces in order reproduces every original value. The copy-based examples leave the original array intact, so you can use it again or compare it with the results.
Common Mistakes
Including the boundary item twice or skipping it. With copyOfRange, the end is exclusive. For adjacent ranges, the first ends at splitAt and the second starts at splitAt. Do not subtract one from the first range’s end or add one to the second range’s start; either change can omit an item or leave a gap.
Using the last element index as the end. The last valid index is length - 1, but the end boundary for a range containing the whole array is length. For example, the complete range is 0 to array.length, not 0 to array.length - 1.
Assuming the original array is resized. A Java array’s length cannot change after creation. A split creates separate arrays; it does not remove the copied values from the original. If you need a variable number of pieces, use a collection such as List<int[]> to hold the resulting arrays.
Ignoring an uneven final chunk. A length that is not a multiple of the chunk size leaves a remainder. Use Math.min(start + chunkSize, array.length) for the final end, rather than assuming every chunk has the requested size.
Tips
Keep boundaries as half-open ranges: start inclusive, end exclusive. This convention matches Java’s array and collection APIs and makes neighboring ranges easy to connect. If you split an array of length n at k, the two result lengths are k and n - k. That simple check catches many mistakes.
Use Arrays.copyOfRange() when you want independent arrays and readable code. If you only need to process a portion of the original without allocating a copy, pass the original array together with start and end indexes to a method instead. That can reduce memory use, but the method must respect the range and the original array remains shared.
For very large arrays, remember that each copy uses additional memory proportional to the copied elements. Avoid repeatedly splitting an array inside a loop if you can process its ranges directly. For object arrays, the array is copied but the referenced objects are not cloned: both the original and copied arrays still point to the same objects.
Troubleshooting
If Java reports ArrayIndexOutOfBoundsException, inspect the start and end values immediately before the copy. Make sure the start is not negative or greater than the source length, and that the end is not less than the start. For a normal split, ensure 0 <= splitAt && splitAt <= array.length. If the boundary is calculated from a count, confirm that the count uses the same meaning as the boundary: a count of three corresponds to an exclusive end of three.
If the result contains extra zeros or nulls, look for an end index greater than the source length. Arrays.copyOfRange() pads that extra portion with the type’s default value. Correct the calculation or reject the invalid range instead of treating the padded result as a successful split.
If the last chunk is empty or you see an endless loop, check the loop update and chunk size. The loop should advance by a positive number, and chunkSize must be greater than zero. A zero chunk size never moves the start index; a negative size moves it in the wrong direction. If elements appear missing, print each chunk’s start and end and verify that each new start equals the preceding end.
If a test says the original changed after editing a copied primitive array, double-check which array is being updated. Primitive array copies hold separate values. For an object array, however, changing a field on an object accessed through either array can be visible through both, because only the array structure was copied, not the objects themselves.
Frequently Asked Questions
Can I split an array without changing the original?
Yes. Arrays.copyOfRange() returns new arrays and leaves the source array’s elements in place. For object arrays, the references are copied, not the objects themselves.
How do I split an array into two equal parts?
Use int mid = array.length / 2;, then copy ranges from zero to mid and from mid to array.length. If the length is odd, the second part gets the extra element. Use (array.length + 1) / 2 if the first part should get it instead.
What happens if the array length is odd?
Nothing special happens automatically; your chosen boundary determines which part gets the leftover element. For chunks, the final chunk is shorter than the others unless you add a separate rule to distribute the remainder.
Can I use Arrays.copyOfRange() with a primitive array?
Yes. Java provides overloads for primitive arrays such as int[], long[], and char[], as well as for object arrays. The returned array has the same component type as the input.
How do I split an array into chunks of the same size?
Loop over start indexes in increments of the desired chunk size and set each end to the smaller of start + chunkSize and the array length. The last chunk may be shorter when the input length is not divisible by the chunk size.
Can I split an array into views instead of copies?
Java arrays do not provide built-in slice views. You can pass the original array and a start/end pair to your own method to process a range without copying. If you specifically need a view abstraction, consider a suitable collection or buffer type for your data and operations.
Related
- How to Group Rows in JMP
- How to Subtotal Data in Excel and Summarize Groups
- C++ Split String Into Array: Practical Methods
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- How to Zoom In Excel Using the KeyboardIn Excel for Microsoft 365 on Windows, press Alt+W, then Q to open the Zoom dialog. Choose a…
- Excel Text Split: Stop at the First DelimiterYes. In Microsoft 365, use TEXTBEFORE to return the text before the first delimiter and TEXTAFTER to keep…
- JavaScript split(): How to Use It and Avoid PitfallsIn JavaScript, use the string method split() to divide a string into an array, using a separator such…
- Enum in Programming: Meaning, Uses, and ExamplesAn enum in programming is a type that defines a named set of related values, such as the…
- Outlook Scheduling Poll: Add Meeting Times to EmailYes. In new Outlook for Windows, start a message, add the people you want to meet with, then…
- Excel Conditional Formatting Color Scales ExplainedExcel’s conditional formatting color scales let you shade cells with a gradient based on their values, so the…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.