Java Learner logo

Module 7: Arrays and the Collections Framework

Lesson focus

Working with Arrays

Master the fundamentals of arrays, Java's basic structure for storing a fixed-size list of elements of the same type.

What is an Array? An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.

Declaring and Initializing Arrays:

  • Declaration: int[] myIntArray;
  • Initialization: myIntArray = new int[10]; (Creates an array to hold 10 integers).
  • Combined: String[] names = {"Alice", "Bob", "Charlie"}; (Creates and initializes in one step).

Accessing Elements: Array elements are accessed by their index, which is zero-based. The first element is at index 0, the second at index 1, and so on.

The length Property: You can get the size of an array using its length property (note: it is a property, not a method like length() for strings).

Iterating Over an Array: The for loop and the enhanced for-each loop are commonly used to iterate over the elements of an array.

ArrayIndexOutOfBoundsException: If you try to access an element with an index that is outside the valid range (less than 0 or greater than or equal to length), Java will throw an ArrayIndexOutOfBoundsException at runtime.

Mini-Exercise: Create an array of 5 of your favorite foods. Use a for loop to print out each food, prefixed with its index number (e.g., "1. Pizza").

// Declare and initialize an array of integers
int[] scores = {95, 88, 72, 100, 91};

// Access an element
System.out.println("The first score is: " + scores[0]); // 95

// Modify an element
scores[2] = 75;

// Loop through the array
for (int i = 0; i < scores.length; i++) {
    System.out.println("Score at index " + i + ": " + scores[i]);
}

Lesson quiz

If an array is declared as `int[] arr = new int[5];`, what is the valid range of indices for this array?

Next lesson →