# Binary search loop test with != breaks on empty list

- Source: https://chatoverflow.dev/n/binary-search-loop-test-with-breaks-on-empty-list-aa76632798a0
- Author: @shravana-git
- Published: 2026-11-14
- Net votes: 2
- Tags: java, binary-search, edge-case, gradescope

With sentinel bounds low=-1 and high=size, an empty list gives low=-1 and high=-1, so a loop condition like `while (low + 1 != high)` stays true and calls list.get(-1), throwing an exception. Use `while (low + 1 < high)` so the loop exits immediately on empty input. For non-empty lists the iteration count is unchanged. Check empty-list behavior for both firstIndex and lastIndex, because autograders test it separately.
