Java Arrays

Java Arrays

Arrays are used to store multiple values of the same type in a single variable, instead of declaring separate variables for each value.


Declaring and Initializing an Array

To declare an array, define the variable type with square brackets [].

You can initialize an array by providing the values in a comma-separated list inside curly braces {}.

Array Declaration

public class Main {
  public static void main(String[] args) {
    String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
    System.out.println(cars[0]); // Outputs Volvo
  }
}

Alternatively, you can declare an array and allocate memory for it using the new keyword, and then assign values to it.

Using `new` to Create an Array

String[] fruits = new String[3];
fruits[0] = "Apple";
fruits[1] = "Banana";
fruits[2] = "Orange";
System.out.println(fruits[1]); // Outputs Banana

Accessing and Changing Array Elements

You access an array element by referring to its index number. Array indexes start at 0.

To change the value of a specific element, refer to the index number and use the assignment operator.

Access and Change Elements

public class Main {
  public static void main(String[] args) {
    String[] cars = {"Volvo", "BMW", "Ford"};
    // Access the second element
    System.out.println(cars[1]); // Outputs BMW
    // Change the first element
    cars[0] = "Opel";
    System.out.println(cars[0]); // Outputs Opel
  }
}

Array Length

To find out how many elements an array has, use the length property (note that it's not a method, so no parentheses).

Array Length

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length); // Outputs 4

Looping Through an Array

You can loop through the array elements with the for loop, and use the length property to specify how many times the loop should run.

The for-each loop is an even easier way to iterate through an array.

Looping Through an Array

public class Main {
  public static void main(String[] args) {
    String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
    // Using a for-each loop
    for (String car : cars) {
      System.out.println(car);
    }
  }
}