No history yet

Array Basics

Organizing Your Data

Imagine you have a list of ten scores from a recent game. You could create ten separate variables, score1, score2, score3, and so on. But what if you had a hundred scores? Or a thousand? This approach quickly becomes messy.

This is where arrays come in. An array is a data structure that holds a fixed number of values of a single type. Think of it like an egg carton. It's designed to hold a specific number of eggs (its fixed size), and you wouldn't mix eggs with apples inside it (its single type).

This structure is fundamental in programming. It gives you one name for a whole collection of items, keeping related data neatly organized.

Why Bother With Arrays?

The main advantage of an array is its efficiency. All the elements in an array are stored together in memory, one right after another. This is called a contiguous memory location. Because the computer knows where the array starts and that each element is the same size, it can jump directly to any item in the list without checking the ones before it.

It’s like a row of numbered parking spots. If you want to find spot #5, you don't have to check spots #1, #2, #3, and #4. You can calculate its exact location and go straight there. This makes accessing data in an array incredibly fast.

Because array elements are stored side-by-side, retrieving any specific one is almost instantaneous.

However, this structure comes with a trade-off. When you create an array, you have to decide its size, and you can't change it later. If you set up an array for 10 scores, it will always have exactly 10 slots. If you suddenly need to store an 11th score, you can't just add another slot. You'd have to create a brand new, larger array and copy everything over.

Counting from Zero

One of the most important rules to remember in Java is that arrays are zero-indexed. This means the first element is at position 0, the second is at position 1, the third at position 2, and so on. The position number is called the index.

So, for an array with 10 elements, the valid indexes are 0 through 9. It might feel strange at first, but this convention is common across many programming languages.

Why start at zero? Think of the index as an offset, or the number of steps you need to take from the starting point of the array. To get to the first element, you take zero steps. To get to the second, you take one step. This way of thinking makes memory calculations simpler and more efficient for the computer.

Quiz Questions 1/4

What is the primary advantage of storing data in an array?

Quiz Questions 2/4

If an array is declared to hold 25 elements, what is the index of the final element?