×

java · level 1 · unit 6 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

An keeps many values together in one box.

An array is like an egg box: one box with a row of slots. Put the items between curly brackets, split by commas: String[] pets = {"cat", "dog"};. The square brackets mean many strings, not one.

Every must be the same type, so an int[] holds whole numbers only. pets.length tells you how many items there are. Unlike strings, arrays have no brackets after length.

To show every item at once, borrow with import java.util.Arrays; at the top. Remember String[] args in the frame? That is an array too.

import java.util.Arrays;
public class Main {
    public static void main(String[] args) {
        String[] pets = {"cat", "dog", "goldfish"};
        int[] ages = {3, 5, 1};
        System.out.println(pets.length);
        System.out.println(Arrays.toString(pets));
        System.out.println(Arrays.toString(ages));
    }
}

Printing an array without Arrays.toString shows a strange code instead of the items.