TheAlgorithms/Java · error · IllegalArgumentException
Array cannot be null
Error message
Array cannot be null
What it means
Thrown by SentinelLinearSearch.find(T[], T) when array == null. The sentinel technique writes a sentinel into the last array slot, which dereferences the array reference, so a null array would cause a NullPointerException. The guard converts it into a clear IllegalArgumentException.
Source
Thrown at src/main/java/com/thealgorithms/searches/SentinelLinearSearch.java:49
*
* @author TheAlgorithms Contributors
* @see LinearSearch
* @see SearchAlgorithm
*/
public class SentinelLinearSearch implements SearchAlgorithm {
/**
* Performs sentinel linear search on the given array.
*
* @param array the array to search in
* @param key the element to search for
* @param <T> the type of elements in the array, must be Comparable
* @return the index of the first occurrence of the key, or -1 if not found
* @throws IllegalArgumentException if the array is null
*/
@Override
public <T extends Comparable<T>> int find(T[] array, T key) {
if (array == null) {
throw new IllegalArgumentException("Array cannot be null");
}
if (array.length == 0) {
return -1;
}
if (key == null) {
return findNull(array);
}
// Store the last element
T lastElement = array[array.length - 1];
// Place the sentinel (search key) at the end
array[array.length - 1] = key;
int i = 0;
// Search without bound checking since sentinel guarantees we'll find the keyView on GitHub (pinned to fdfb9a395b)
Solutions
- Null-check the array before calling find() and return -1 or an empty result.
- Initialize fields to empty arrays rather than null.
- Use Optional or @NonNull annotations to make nullability explicit at the type level.
Example fix
// before int idx = new SentinelLinearSearch().find(arr, key); // after if (arr == null) return -1; int idx = new SentinelLinearSearch().find(arr, key);
Defensive patterns
Strategy: validation
Validate before calling
if (array == null) return -1;
Type guard
public static <T> boolean isSearchable(T[] array) { return array != null; } Prevention
- Initialize array fields to empty arrays, not null.
- Null-check at the API boundary before delegating to SentinelLinearSearch.
- Use @NonNull annotations and static analysis to catch null propagation.
When it happens
Trigger: Calling find(null, key); passing a field that was never initialized; receiving null from a loader or Map.get() and forwarding it.
Common situations: Optional fields left null; data sources that return null instead of an empty array; legacy code using null as a sentinel for 'no data'.
Related errors
- Key must not be null.
- The input array cannot be null
- Input array must not be null.
- IPv4 address is empty.
- Input cannot be null or empty
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/5256061e3604a9dc.
Report an issue: GitHub.