Lesson 18 +10 XP

Java Arrays

Java Arrays

An array stores many values of the same type in a single variable. Instead of declaring 10 separate variables, you store 10 values in one array.

Declaring an array

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

The [] marks the type as an array. The values are listed inside curly braces.

Accessing elements

Array indexes start at 0. Use the index inside square brackets:

System.out.println(cars[0]); // Volvo

Changing an element

cars[0] = "Opel";
System.out.println(cars[0]); // Opel

Array length

Use length (no parentheses, it is a property):

System.out.println(cars.length); // 4

Loop through an array

for (int i = 0; i < cars.length; i++) {
  System.out.println(cars[i]);
}

Or use the for each loop:

for (String i : cars) {
  System.out.println(i);
}

TL;DR

  • Arrays hold many values of one type.
  • Indexes start at 0.
  • length gives the number of elements.
  • Use for or for each loops to read every element.