Labs ICT
โญ Pro Login

Arrays

So far you have been storing single values โ€” one number, one string, one boolean. But what if you need to store a list of things? A hundred students' scores? All the items in a shopping cart? That is where arrays come in.

An array is like a row of lockers. Each locker has a number (the index), and each locker holds a value. You can store multiple values in one array and access them by their position.

Declaring and Initializing Arrays

There are two ways to create an array. You can create an empty array of a certain size, or you can create one with values already in it.

int[] numbers = new int[5];

String[] names = {"Alice", "Bob", "Charlie"};

The first line creates an array that can hold five integers, all starting at 0. The second line creates an array with three strings already in it.

Accessing Elements

Array indices start at 0. So the first element is at index 0, the second at index 1, and so on. To get or set a value, use the index in square brackets.

String[] names = {"Alice", "Bob", "Charlie"};

names[1] = "David";

System.out.println(names[0]);
System.out.println(names[1]);

This prints "Alice" and "David". We changed index 1 from "Bob" to "David".

Array Length

Every array has a length property that tells you how many elements it holds. Notice there are no parentheses โ€” it is a property, not a method.

String[] names = {"Alice", "Bob", "Charlie"};

System.out.println(names.length);

Looping Through Arrays with for-each

Java has a special loop called the enhanced for loop or for-each that makes looping through arrays much cleaner.

String[] names = {"Alice", "Bob", "Charlie"};

for (String name : names) {
  System.out.println(name);
}

The syntax reads like English: "for each name in names, print the name". No index variables, no length checks. Java handles everything.

Keep in mind that the for-each loop is read-only. You can look at each element, but you cannot change them. For that, you need the regular for loop with an index.

๐Ÿงช Quick Quiz

What is the index of the last element in an array of size 5?