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.
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
Why Safe Handling Matters
The Golden Rule of Safe Access
Valid Index Range
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 | ArrayIndexOutOf |
StringIndexOutOf |
How to Apply Safe Handling
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.
Example 2: Checking Adjacent Pairs
Write a method that returns true if any two adjacent elements are equal.
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.
The Off-by-One Trap
Null vs Empty vs Single
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} \).
Common Mistakes to Avoid
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?