Course contentsShow
← Computer Science
Lesson 235 of 2,8726. Arrays and Basic CollectionsFree lesson

Array Length and Bounds

Understanding array size limits and avoiding out-of-bounds errors when accessing elements.

Array Length and Bounds

You'll learn how to safely determine an array's size and avoid accessing elements that don't exist.

Understanding Array Length

Every array has a fixed number of elements, called its length or size. Knowing this number is crucial because arrays don't grow or shrink—they're created with a specific capacity and stay that way.

Think of an array like a row of numbered mailboxes in an apartment building. If there are 5 mailboxes numbered 0 through 4, trying to put mail in mailbox 7 doesn't make sense—it doesn't exist!

Valid Index Range

Remember from array indexing that positions start at 0, not 1. So if your array has a length of 5, the valid indices are:

  • First element: index 0
  • Last element: index 4 (which is length minus 1)

This is critical: the last valid index is always length - 1.

Out-of-Bounds Errors

Accessing an index outside the valid range causes an out-of-bounds error. This happens when you try to read or write using an index that's negative or greater than or equal to the array's length.

For example, with an array of length 5:

  • Index -1: out of bounds (too low)
  • Index 5: out of bounds (too high—remember, valid range is 0–4)

These errors can crash your program or cause unpredictable behavior, making them dangerous bugs to have.

Checking Bounds

Always ensure your index is valid before accessing an array:

  • Index must be >= 0
  • Index must be < length

When using loops with arrays, make sure your loop condition respects these boundaries.

Key Takeaway: Arrays have a fixed length, valid indices run from 0 to length - 1, and accessing anything outside this range causes out-of-bounds errors that you must prevent.