Java Arrays: Sorting, the Arrays Class, Multidimensional and Ragged Arrays
Sort and search arrays with java.util.Arrays, draw raffle winners without repeats, generate random numbers the modern way, build tables with two-dimensional arrays, and understand Java's arrays of arrays: deepToString, swapping rows, and ragged (triangular) arrays.
kvi5hnuCode Sprout team member10 min readOn this page
The previous article covered creating, accessing and copying one-dimensional arrays. This one finishes the topic and the fundamentals part of the course:
- Sorting and searching with the
java.util.Arraysclass, plus its other utility methods. - A complete program that draws raffle winners at random, and how to generate random numbers.
- Multidimensional arrays for tables.
- Ragged arrays, which show what Java's multidimensional arrays really are.
Sorting an Array
To sort an array of numbers into ascending order, call Arrays.sort:
int[] a = new int[10000];
...
Arrays.sort(a);
The array is sorted in place: its elements are rearranged, and nothing is returned.
- For primitive arrays,
sortuses a tuned dual-pivot quicksort, which is very fast on typical data. - For object arrays (
String[]and others), it uses TimSort, a merge sort variant that is stable: equal elements keep their original relative order. Arrays.parallelSortsplits large arrays across several CPU cores. It's worth it for arrays with hundreds of thousands of elements or more.
Strings sort by their compareTo order, so uppercase letters come before lowercase. Pass String.CASE_INSENSITIVE_ORDER (a comparator; comparators are covered in the interfaces part) to ignore case. You can also sort just part of an array with Arrays.sort(a, from, to).
Searching a sorted array
Arrays.binarySearch(a, value) finds a value in a sorted array in about log₂(n) steps: about 20 comparisons for a million elements. It returns the index if found. Otherwise it returns a negative number, -(insertionPoint) - 1, where insertionPoint is the index at which the value would have to be inserted to keep the array sorted. On an unsorted array, the result is meaningless.
import java.util.Arrays;
public class Solution {
public static void main(String[] args) {
int[] a = { 42, 7, 19, 3, 25, 7 };
Arrays.sort(a);
System.out.println(Arrays.toString(a));
System.out.println(Arrays.binarySearch(a, 19) + " " + Arrays.binarySearch(a, 20));
String[] words = { "pear", "apple", "Banana", "cherry" };
Arrays.sort(words);
System.out.println(Arrays.toString(words));
Arrays.sort(words, String.CASE_INSENSITIVE_ORDER);
System.out.println(Arrays.toString(words));
int[] part = { 9, 8, 7, 6, 5, 4 };
Arrays.sort(part, 1, 4);
System.out.println(Arrays.toString(part));
int[] squares = new int[6];
Arrays.setAll(squares, i -> i * i);
System.out.println(Arrays.toString(squares));
System.out.println(Arrays.stream(squares).sum() + " " + Arrays.stream(squares).max().getAsInt());
System.out.println(Arrays.equals(new int[] {1, 2}, new int[] {1, 2}) + " "
+ Arrays.compare(new int[] {1, 2}, new int[] {1, 3}) + " "
+ Arrays.mismatch(new int[] {1, 2, 3}, new int[] {1, 5, 3}));
}
}
[3, 7, 7, 19, 25, 42]
3 -5
[Banana, apple, cherry, pear]
[apple, Banana, cherry, pear]
[9, 6, 7, 8, 5, 4]
[0, 1, 4, 9, 16, 25]
55 25
true -1 1
binarySearch(a, 20) returns −5: 20 would be inserted at index 4, and −4 − 1 = −5.
The Arrays Class at a Glance
java.util.Arrays contains only static helper methods. Most are overloaded for every primitive type and for objects.
| Method | Purpose |
|---|---|
toString(a) 5 | "[2, 3, 5]" |
deepToString(a) 5 | the same for multidimensional arrays |
copyOf(a, length) 6 / copyOfRange(a, from, to) 6 | copy, padding with defaults if longer |
sort(a) / sort(a, from, to) / sort(a, comparator) | sort in place |
parallelSort(a) 8 | multi-core sort for large arrays |
binarySearch(a, v) | search a sorted array |
fill(a, v) / fill(a, from, to, v) | set elements to one value |
setAll(a, i -> …) 8 | compute each element from its index |
equals(a, b) / deepEquals(a, b) | compare contents (one level / nested) |
compare(a, b) 9 | lexicographic comparison: negative, 0, positive |
mismatch(a, b) 9 | first index where they differ, or −1 |
hashCode(a) / deepHashCode(a) | content-based hash codes |
asList(…) | a fixed-size List view of an object array |
stream(a) 8 | a stream for sum, max, filter, … (streams are covered later) |
setAll takes a lambda expression, i -> i * i, read as "for index i, the value is i * i". Lambdas get their own article in the interfaces part.
Example: Drawing Raffle Winners
Here's a task where arrays shine: a raffle sold tickets numbered 1 to 30, and five different tickets must win. No ticket may be drawn twice. You could draw random numbers and redraw on a duplicate, but there's a neater approach:
- Put every ticket number in an array
tickets. - Choose a random position
rin the part of the array that's still in play (0 to n − 1), and recordtickets[r]as a winner. - Copy the last ticket still in play over slot
r, then shrinknby one. The winning ticket has left the active range, and every ticket not yet drawn is still inside it.

import java.util.Arrays;
import java.util.Random;
public class Solution {
public static void main(String[] args) {
int winnersWanted = 5;
int n = 30;
Random rng = new Random(42); // fixed seed: the same draw on every run
int[] tickets = new int[n];
for (int i = 0; i < tickets.length; i++) {
tickets[i] = i + 1;
}
int[] winners = new int[winnersWanted];
for (int i = 0; i < winners.length; i++) {
int r = rng.nextInt(n); // a position that's still in play
winners[i] = tickets[r];
tickets[r] = tickets[n - 1]; // fill the gap with the last ticket in play
n--;
}
Arrays.sort(winners);
System.out.println("Winning tickets: " + Arrays.toString(winners));
}
}
Winning tickets: [1, 10, 18, 21, 30]
Sorting the winners at the end is only for a tidier printout; the draw itself doesn't need it.
This "pick a random index, swap in the last element" step is the heart of the Fisher–Yates shuffle, the standard algorithm for shuffling. Collections.shuffle uses it.
Random numbers in Java
| Tool | Notes |
|---|---|
Math.random() | a double in [0, 1). For an int in 0 … n − 1: (int) (Math.random() * n). Simple, but awkward for integers |
new Random() / new Random(seed) | nextInt(n) gives 0 … n − 1; nextInt(lo, hi) (Java 17) gives lo … hi − 1; also nextDouble, nextBoolean, nextGaussian |
RandomGenerator.getDefault() (Java 17) | the modern interface for all generators (java.util.random), with several algorithms to choose from |
ThreadLocalRandom.current() | best for concurrent programs: no contention between threads |
new SecureRandom() | cryptographically strong: use it for passwords, tokens and keys |
A seed makes the sequence reproducible: new Random(42) produces the same numbers every run, which is great for tests and for the example above. Without a seed, each run differs. Never use Random or Math.random for anything security-related; use SecureRandom.
Multidimensional Arrays
Multidimensional arrays use more than one index. They suit tables, grids, matrices and game boards.
Suppose you want to track how tall a seedling gets over several weeks under different weekly growth rates. Each row is a week and each column is a rate:
10% 15% 20% 25% 30%
20.00 20.00 20.00 20.00 20.00
22.00 23.00 24.00 25.00 26.00
24.20 26.45 28.80 31.25 33.80
...
Store it in a two-dimensional array, with one row per week and one column per rate:
double[][] heights = new double[WEEKS][RATES];
If you know the values, use nested initializers, without new:
int[][] loShu = {
{4, 9, 2},
{3, 5, 7},
{8, 1, 6}
};
Access elements with two pairs of brackets: heights[i][j] is row i, column j. The number of rows is heights.length; the number of columns in row i is heights[i].length.
public class Solution {
public static void main(String[] args) {
final int RATES = 5;
final int WEEKS = 6;
double[] growth = new double[RATES];
for (int j = 0; j < growth.length; j++) {
growth[j] = 0.10 + 0.05 * j; // 10%, 15%, ..., 30%
}
double[][] heights = new double[WEEKS][RATES];
for (int j = 0; j < heights[0].length; j++) {
heights[0][j] = 20.0; // every seedling starts at 20 cm
}
for (int i = 1; i < heights.length; i++) {
for (int j = 0; j < heights[i].length; j++) {
heights[i][j] = heights[i - 1][j] * (1 + growth[j]);
}
}
for (double g : growth) {
System.out.printf("%9.0f%%", 100 * g);
}
System.out.println();
for (double[] week : heights) {
for (double h : week) {
System.out.printf("%10.2f", h);
}
System.out.println();
}
}
}
10% 15% 20% 25% 30%
20.00 20.00 20.00 20.00 20.00
22.00 23.00 24.00 25.00 26.00
24.20 26.45 28.80 31.25 33.80
26.62 30.42 34.56 39.06 43.94
29.28 34.98 41.47 48.83 57.12
32.21 40.23 49.77 61.04 74.26
Looping and printing
A for-each loop over a 2D array visits the rows, which are themselves arrays. To visit every element, nest two loops:
for (double[] row : heights) {
for (double value : row) {
// do something with value
}
}
For a quick look at the contents, Arrays.deepToString formats nested arrays. Plain Arrays.toString would only show the row references:
System.out.println(Arrays.deepToString(loShu));
// [[4, 9, 2], [3, 5, 7], [8, 1, 6]]
Arrays of Arrays
Here's the subtle part: Java has no true multidimensional arrays, only one-dimensional ones. A "two-dimensional" array is an array whose elements are arrays.
![heights refers to an outer array of 4 elements; each element refers to a separate row array of 3 doubles; heights[1] is a row and heights[1][2] one element of it](https://code-sprout-content.laxmi.solutions/asset/2026/11/pzxa2s37e4xhf23k.png)
heightshas typedouble[][]: an array ofdouble[].heights[i]is thei-th row, an ordinarydouble[].heights[i][j]is elementjof that row.
Since the rows are separate objects, you can do things that are impossible with a C-style block of memory. For example, you can swap two rows by swapping references, without copying any numbers:
double[] temp = heights[i];
heights[i] = heights[i + 1];
heights[i + 1] = temp;
Ragged Arrays
The row lengths aren't part of the type either, so the rows of a 2D array can have different lengths. Such an array is called ragged (or jagged).
A natural fit is Pascal's triangle. Row n holds the binomial coefficients "n choose k" for k from 0 to n, so row 0 has one entry, row 1 has two, and so on: row n needs n + 1 slots. Every entry inside a row is the sum of the two entries just above it:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
To build it, allocate the outer array without a row length, then give each row its own array of the right size:
int[][] pascal = new int[ROWS][];
for (int n = 0; n < ROWS; n++) {
pascal[n] = new int[n + 1];
}

public class Solution {
public static void main(String[] args) {
final int ROWS = 7;
int[][] pascal = new int[ROWS][];
for (int n = 0; n < ROWS; n++) {
pascal[n] = new int[n + 1];
pascal[n][0] = 1; // first entry of every row
pascal[n][n] = 1; // last entry of every row
for (int k = 1; k < n; k++) {
pascal[n][k] = pascal[n - 1][k - 1] + pascal[n - 1][k];
}
}
for (int[] row : pascal) {
for (int entry : row) {
System.out.printf("%4d", entry);
}
System.out.println();
}
}
}
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
Notice that the printing loop walks each row by its own length, never a fixed column count, and the building loop stops at n, the last index of that row. That's the habit to keep with any 2D array.
Zero-length dimensions
A dimension can be zero:
new int[3][0]has three rows, each of length 0.new int[0][3]has no rows. The row length is irrelevant because no rows are allocated, sonew int[0][3],new int[0][4]andnew int[0][]all produce the same thing.
And new int[2][] creates an outer array whose two rows are still null until you assign them.
Common questions
Why is Arrays.sort stable for objects but not for primitives?
Stability means equal elements keep their order. That matters only when equal elements can be told apart, which is possible for objects (two Persons with the same age) but not for primitives (one 5 is like any other). So primitive sorting can use the faster dual-pivot quicksort, while object sorting uses the stable TimSort.
How do I sort an int[] in descending order?
Arrays.sort has no comparator version for primitive arrays. Sort ascending and then reverse the array with a loop. Alternatively, box the values: Integer[] boxed = ...; Arrays.sort(boxed, Comparator.reverseOrder());. With streams: IntStream.of(a).boxed().sorted(Comparator.reverseOrder()).mapToInt(Integer::intValue).toArray().
Which random number API should I use?
For simple programs, Math.random(), new Random() or ThreadLocalRandom.current() all work. Since Java 17, RandomGenerator.getDefault() and named algorithms (RandomGenerator.of("L64X128MixRandom")) give better statistical quality. Use SecureRandom for anything secret, such as tokens and passwords.
Is a 2D array stored as one block of memory?
No. new int[1000][1000] creates 1001 separate objects: one outer array plus 1000 row arrays. Iterating row by row (a[i][j] with j in the inner loop) is cache-friendly. Iterating column by column jumps between rows and can be much slower for large arrays.
How do I print a 2D array as a table?
Arrays.deepToString(grid) is fine for debugging. For aligned output, loop over the rows and use printf with a fixed width, for example "%5d", and a println() after each row.
Summary
Arrays.sortsorts in place: dual-pivot quicksort for primitives, stable TimSort for objects.parallelSorthelps for very large arrays.Arrays.binarySearchworks only on sorted arrays; a negative result encodes the insertion point.Arraysalso offersfill,setAll,equals,compare,mismatch,copyOf,toString,deepToStringandstream.- To draw distinct random values, pick a random index and move the last element into its place (the Fisher–Yates step).
- Use
Random/RandomGenerator(seed it for reproducible results),ThreadLocalRandomfor concurrency, andSecureRandomfor security. - A 2D array
T[][]is an array of arrays:a[i]is a row,a[i][j]an element. Loop toa[i].lengthfor each row. - Rows are independent objects, so they can be swapped, shared, or have different lengths (ragged arrays):
new int[n][]and then allocate each row. - Use
Arrays.deepToStringandArrays.deepEqualsfor nested arrays. Copying the outer array is shallow.
That completes the fundamentals of the language. In the next part, you'll start building your own objects and classes.
Practice Questions
Arrays.binarySearch returns -3 for a value in a sorted array. What does that mean?
The value isn't in the array. It would be inserted at index -(-3) - 1 = 2 to keep the array sorted.
How many elements does new int[4][5] contain, and what is a[3].length?
4 rows × 5 columns = 20 int elements (in 4 row arrays, plus the outer array of 4 references). a[3].length is 5.
Write code that sums all elements of a possibly ragged int[][] grid.
int sum = 0;
for (int[] row : grid) {
for (int value : row) {
sum += value;
}
}
Nested for-each loops work for any row lengths.
Why does int r = (int) Math.random() * n; always give 0?
The cast binds more tightly than *: (int) Math.random() truncates a value in [0, 1) to 0, and 0 × n is 0. Write (int) (Math.random() * n), or better, generator.nextInt(n).
After int[][] copy = grid.clone(); copy[0][0] = 99;, does grid[0][0] change?
Yes. clone copies only the outer array of row references; both arrays share the same row objects. For an independent copy, clone each row: for (int i = 0; i < grid.length; i++) copy[i] = grid[i].clone();.
Create a ragged array where row i has i + 1 stars, and print it as a triangle.
char[][] tri = new char[4][];
for (int i = 0; i < tri.length; i++) {
tri[i] = new char[i + 1];
Arrays.fill(tri[i], '*');
}
for (char[] row : tri) {
System.out.println(new String(row));
}
Previous: Java Arrays: Declaring, Initializing, for-each Loops and Copying
Related reading

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.