Search⌘ K
AI Features

Working with Arrays

Explore how to effectively use Java arrays to manage large sets of related data. Understand array declaration, initialization, memory storage, and safe access. Master iteration techniques using standard and enhanced for loops and learn to work with multidimensional and jagged arrays to handle complex data structures efficiently.

We have spent much of our time managing data using individual variables. While this works well for simple values, it becomes unmanageable when we need to track large sets of related information, such as the daily temperatures for a year or the pixels in an image.

In this lesson, we’ll work through how Java arrays are structured and how to use them effectively in code. We’ll look at how arrays are stored in memory and introduce the enhanced for loop for iterating over them.

Declaring and initializing arrays

An array is a container object that holds a fixed number of values of a single type. Once we create an array, its length is established and cannot be changed.

In Java, we declare an array variable by specifying the type followed by square brackets []. While Java allows the brackets to be placed after the variable name (e.g., int numbers[]), the preferred convention is to place them after the type (e.g., int[] numbers). This clearly indicates that the variable is an “array of integers.”

We allocate memory for the array using the new keyword, specifying how many elements it can hold. Alternatively, if we already know the values, we can use an array initializer to create and populate the array in a single ...

Java 25
public class ArrayCreation {
public static void main(String[] args) {
// Option 1: Allocate memory for 5 integers
// These are initialized to the default value (0 for int)
int[] scores = new int[5];
// Option 2: Initialize with specific values
// The size is automatically determined (length is 4)
String[] colors = { "Red", "Green", "Blue", "Yellow" };
System.out.println("Scores length: " + scores.length);
System.out.println("First color: " + colors[0]);
}
}
    ...