From 091ef2235d0917814f07b746e37593e9b688ea4f Mon Sep 17 00:00:00 2001 From: Senrian <47714364+Senrian@users.noreply.github.com> Date: Wed, 1 Apr 2026 08:34:02 +0800 Subject: [PATCH] fix(BinarySearch): add null key check to prevent NPE Issue #7356: Add null check for the search value to prevent potential NullPointerException. --- .../java/com/thealgorithms/searches/BinarySearch.java | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/thealgorithms/searches/BinarySearch.java b/src/main/java/com/thealgorithms/searches/BinarySearch.java index 7a5361b280ea..ca873fc6eafa 100644 --- a/src/main/java/com/thealgorithms/searches/BinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/BinarySearch.java @@ -58,11 +58,18 @@ class BinarySearch implements SearchAlgorithm { */ @Override public > int find(T[] array, T key) { - // Handle edge case: empty array + // Handle edge case: null or empty array if (array == null || array.length == 0) { return -1; } + // Handle edge case: null key + // Searching for null in an array of Comparables is undefined behavior + // Return -1 to indicate not found rather than throwing NPE + if (key == null) { + return -1; + } + // Delegate to the core search implementation return search(array, key, 0, array.length - 1); }