Codiqo

Learn Java · lesson 26 of 61 · about 7 minutes

Creating Arrays

List today's showings: store several values of one type in an array, and read them by index.

What you'll learn

  • Create arrays with values or a size
  • Read and change items
  • Use the length field

Today's showings

Space Pirates is on three times today, and the desk should list the showings and let the customer pick one. Three separate variables would work until the cinema adds a fourth showing. A String[] called times holds them all in order, times.length says how many there are, and a typed showing number picks one out, as long as it's checked first: an index that's too big stops the program.

A fixed row of values

  • int[] scores = {70, 85, 90}; creates an array with values
  • int[] counts = new int[5]; creates five ints, all starting at 0
  • scores[0] is the first item; scores.length is how many (no brackets: it's a field, not a method)

An array's size never changes. Using a bad index throws ArrayIndexOutOfBoundsException.

Reading and changing items

public class Main {
    public static void main(String[] args) {
        int[] scores = {70, 85, 90, 62};
        System.out.println(scores[0] + " " + scores[scores.length - 1] + " (" + scores.length + ")");
        scores[1] = 88;
        System.out.println("Second is now " + scores[1]);

        String[] islands = new String[2];
        islands[0] = "Bytecode Bay";
        System.out.println(islands[0] + ", " + islands[1]);
    }
}

Output

70 62 (4)
Second is now 88
Bytecode Bay, null

Tip

New arrays are filled with defaults: 0 for numbers, false for booleans and null for objects like String.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.