Java Arrays Explained
Array Basics
What Is an Array?
Think about a row of mailboxes in an apartment building. Each box has a number, and inside each box is a collection of mail. An array is a lot like that row of mailboxes. It’s a data structure that holds a collection of items, all of the same type, stored one after another.
For example, you can have an array of integers to store the daily high temperatures for a week, or an array of strings to hold the names of students in a class. The key rule is that all items in a single array must be the same data type. You can't mix numbers and text in the same array, just like you wouldn't store packages in a slot meant only for letters.
An array is a container that holds a fixed number of values of a single type.
Why Use Arrays?
Arrays are useful because they keep related data organized in one place. Instead of creating separate variables for each student's grade, you can store all the grades in a single array. This makes your code cleaner and easier to manage.
One of the biggest advantages of arrays is how they store data in memory. The elements of an array are placed in a continuous block of memory, side by side. This contiguous layout is like having books on a shelf right next to each other. Because the computer knows exactly where the array starts and how big each element is, it can jump directly to any item in the collection very quickly.
This direct access makes arrays very efficient for retrieving data, especially when you know which item you're looking for.
Zero-Based Indexing
To access a specific element in an array, you use its index. Think of the index as the mailbox number. In Java, and many other programming languages, arrays are zero-indexed. This means the first element is at index 0, the second element is at index 1, the third at index 2, and so on.
The index of the last element in an array is always one less than the total number of elements.
index
noun
A number that identifies the position of a specific element within an array.
This might feel strange at first, but it’s a fundamental concept in programming. If you have an array with 5 elements, their indices will be 0, 1, 2, 3, and 4.
Understanding this counting system is the first step to working effectively with arrays. You'll soon see how to create and use them to handle collections of data.