01 / 21

Handling Empty &
Boundary Cases

Learn to write robust Java code that safely handles empty arrays, empty strings, and dangerous boundary indices: the skills that separate reliable programs from runtime crashes.

AP Computer Science A

What Are Empty & Boundary Cases?

When you write a method that processes an array or string, the empty case is when the input has zero elements (length \( = 0 \)). A boundary case is when you access index \( 0 \) (the first element) or index \( n - 1 \) (the last element), where \( n \) is the length.

Visualizing the Danger Zones

int[] arr = {10, 20, 30, 40, 50}; 10 20 30 40 50 [0] [1] [2] [3] [4] BOUNDARY BOUNDARY [-1] CRASH [5] CRASH int[] empty = {}; length = 0 ANY index access = CRASH

Why Safe Handling Matters

✕ Runtime Crashes
Accessing arr[arr.length] or arr[-1] throws an exception and kills your program immediately.
★ Edge Cases in Exams
AP CS A graders specifically test with empty arrays and single-element inputs. Unprotected code = lost points.
✓ Professional Habit
Real-world Java code handles nulls and empties before any processing. It is a hallmark of quality engineering.

The Golden Rule of Safe Access

// The defensive pattern: if (arr != null && arr.length > 0) { // Safe to access arr[0], arr[arr.length - 1], etc. int first = arr[0]; int last = arr[arr.length - 1]; }

Valid Index Range

-1 0 1 ... n-1 n VALID RANGE OUT OF BOUNDS OUT OF BOUNDS
Valid: \( 0 \le \text{index} < \text{array.length} \)

Arrays vs Strings: Key Differences

Arrays Strings
Get length \( \text{arr.length} \) (field) \( \text{str.length()} \) (method)
Access element \( \text{arr}[i] \) \( \text{str.charAt}(i) \)
Empty check \( \text{arr.length} == 0 \) \( \text{str.isEmpty()} \)
Can be null? Yes Yes
Exception type ArrayIndexOutOfBoundsException StringIndexOutOfBoundsException

How to Apply Safe Handling

1
Check for null first. If the array or string reference could be null, guard with if (arr != null).
2
Check for empty. Verify \( \text{length} > 0 \) (or !isEmpty()) before any element access.
3
Validate indices in loops. Ensure loop bounds use \( < \text{length} \) (not \( \le \text{length} \)) and start at 0.
4
Guard neighbor access. If accessing arr[i - 1] or arr[i + 1], verify those indices are also in range.
5
Return a safe default. For empty input, return 0, -1, "", or an empty array: whatever makes sense for the method contract.

Example 1: Finding the Maximum

Write a method that returns the maximum value in an integer array, or Integer.MIN_VALUE if the array is empty.

public static int findMax(int[] arr) { // Step 1 & 2: Guard empty/null if (arr == null || arr.length == 0) { return Integer.MIN_VALUE; } // Step 3: Safe loop bounds int max = arr[0]; // Safe: length > 0 for (int i = 1; i < arr.length; i++) { if (arr[i] > max) { max = arr[i]; } } return max; }

Example 2: Checking Adjacent Pairs

Write a method that returns true if any two adjacent elements are equal.

public static boolean hasAdjacentDuplicates(int[] arr) { // Need at least 2 elements for a pair if (arr == null || arr.length < 2) { return false; } // Loop stops at length - 1 (not length!) for (int i = 0; i < arr.length - 1; i++) { if (arr[i] == arr[i + 1]) { return true; } } return false; }

Example 3: String First & Last

Write a method that returns a string made of the first and last characters, or an empty string if the input is too short.

public static String firstAndLast(String str) { // Guard: null or empty if (str == null || str.isEmpty()) { return ""; } // Single char: first == last if (str.length() == 1) { return str + str; } // Safe: length >= 2 return "" + str.charAt(0) + str.charAt(str.length() - 1); }

The Off-by-One Trap

✓ CORRECT
for (int i = 0; i \( < \) arr.length; i++)
i=0 i=1 i=2 i=3 i=4 STOP ✕ INCORRECT (off-by-one)
for (int i = 0; i \( \le \) arr.length; i++)
i=0 i=1 i=2 i=3 i=4 i=5 CRASH!

Null vs Empty vs Single

null No object exists {} or "" Object exists, 0 elements {42} or "a" 1 element: [0] only NullPointerException
if you call \( \text{.length} \)
IndexOutOfBounds if you access any index Watch neighbors! arr[i-1] or arr[i+1] crashes Guard order: null → empty → single → general

Tricky: substring() Boundaries

Java's substring(start, end) uses a half-open range: it includes start but excludes end. The valid range is \( 0 \le \text{start} \le \text{end} \le \text{length} \).

String s = "Hello"; // length = 5 s.substring(0, 5); // "Hello" ✓ (end == length is OK!) s.substring(0, 0); // "" ✓ (empty substring) s.substring(5, 5); // "" ✓ (start == end == length) s.substring(0, 6); // CRASH ✕ (end > length) s.substring(3, 1); // CRASH ✕ (start > end)

Common Mistakes to Avoid

✕ Using <= in loops
Writing \( i \le \text{arr.length} \) instead of \( i < \text{arr.length} \). The last valid index is \( \text{length} - 1 \), not \( \text{length} \).
✕ Forgetting null check
Checking \( \text{arr.length} == 0 \) without first checking \( \text{arr} \neq \text{null} \). Null arrays have no \( \text{.length} \) field.
✕ Neighbor without guard
Accessing \( \text{arr}[i + 1] \) or \( \text{arr}[i - 1] \) inside a standard loop without adjusting the loop bounds to stay in range.
✕ length vs length()
Using \( \text{str.length} \) (no parentheses) for a String, or \( \text{arr.length()} \) for an array. Arrays use a field, Strings use a method.

Summary Cheat Sheet

Scenario Guard Code Safe Default
Empty array \( \text{arr.length} == 0 \) return 0 or -1
Null array \( \text{arr} == \text{null} \) return 0 or -1
Empty string \( \text{str.isEmpty()} \) return ""
First element \( \text{length} > 0 \) \( \text{arr}[0] \)
Last element \( \text{length} > 0 \) \( \text{arr}[\text{length} - 1] \)
Neighbor arr[i+1] \( i < \text{length} - 1 \) Adjust loop bound
substring(a, b) \( 0 \le a \le b \le \text{length} \) return ""

Question 1 of 5

What happens when you execute int[] arr = {}; System.out.println(arr[0]);?

Question 2 of 5

Which guard clause correctly prevents a crash when finding the last element of a possibly-null String array?

Question 3 of 5

Given int[] data = {5, 10, 15};, what is the value of \( \text{data}[\text{data.length} - 1] \)?

Question 4 of 5

A loop compares adjacent elements: for (int i = 0; i < arr.length; i++) { if (arr[i] == arr[i + 1]) ... }. What is the problem?

Question 5 of 5

What does "Hello".substring(2, 2) return?