TheAlgorithms/Java · error · IllegalArgumentException
Input array must not be null
Error message
Input array must not be null
What it means
Thrown by ShuffleArray.shuffle when the input int[] arr is null. shuffle performs an in-place Fisher–Yates shuffle indexing arr.length-1 down to 1, so a null array would NPE inside the loop. The guard rejects null explicitly with a clear message. An empty or single-element array is allowed (the loop simply does nothing).
Source
Thrown at src/main/java/com/thealgorithms/misc/ShuffleArray.java:32
*
* This class provides a static method to shuffle an array in place.
*
* @author Rashi Dashore (https://github.com/rashi07dashore)
*/
public final class ShuffleArray {
private ShuffleArray() {
}
/**
* Shuffles the provided array in-place using the Fisher–Yates algorithm.
*
* @param arr the array to shuffle; must not be {@code null}
* @throws IllegalArgumentException if the input array is {@code null}
*/
public static void shuffle(int[] arr) {
if (arr == null) {
throw new IllegalArgumentException("Input array must not be null");
}
Random random = new Random();
for (int i = arr.length - 1; i > 0; i--) {
int j = random.nextInt(i + 1);
swap(arr, i, j);
}
}
/**
* Swaps two elements in an array.
*
* @param arr the array
* @param i index of first element
* @param j index of second element
*/
private static void swap(int[] arr, int i, int j) {
if (i != j) {View on GitHub (pinned to fdfb9a395b)
Solutions
- Ensure the array is non-null before shuffling (instantiate to an empty array if empty).
- Fix upstream methods to return empty arrays rather than null.
- Add a null guard at the call site that skips shuffling for null.
Example fix
// before int[] deck = loadDeck(); // may be null ShuffleArray.shuffle(deck); // after int[] deck = loadDeck(); if (deck == null) deck = new int[0]; if (deck.length > 1) ShuffleArray.shuffle(deck);
Defensive patterns
Strategy: validation
Validate before calling
Objects.requireNonNull(arr, "arr"); if (arr.length > 1) ShuffleArray.shuffle(arr);
Type guard
static boolean isShuffleable(int[] a) {
return a != null && a.length > 1;
} Prevention
- Have array-returning helpers return empty arrays, not null.
- Skip shuffling for arrays of length 0 or 1 (no-op).
When it happens
Trigger: Calling ShuffleArray.shuffle(null), or passing an int[] variable that was never assigned / returned null from a loader. Common when shuffling a list converted via stream().mapToInt(...).toArray() on an empty/null source that yielded null.
Common situations: Uninitialized array field, a helper that returns null on empty input instead of an empty array, or a refactor that dropped the assignment.
Related errors
- Invalid input
- Array cannot be null
- Cannot insert null into the heap.
- Cannot insert null element
- Cannot add null element to the list
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/bdacd9b863452ffb.
Report an issue: GitHub.