AI Hints
Home›Java Tutorial›What an Array Is, Creating Arrays and Looping Over Arrays
Java · Lesson 47 of 120

Creating Arrays

Values or new.

⏱ 2 min read▶ Video at 58:53🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

There are two ways to create an array. List the values straight away, or ask for a number of empty boxes, and fill them later.

  • List the values
  • Or ask for empty boxes
  • Fill them later

Two ways

Curly braces create an array from values. New double, four, creates four empty boxes. Empty boxes aren't really empty. Numbers start at zero, booleans at false, and strings at null. Run it. Tue, and three days. The second price is still zero. And the other arrays start with false, and null.

Main.javajava
public class Main {
    public static void main(String[] args) {
        String[] days = {"Mon", "Tue", "Wed"};
        double[] prices = new double[4];
        boolean[] seen = new boolean[2];
        String[] names = new String[2];
        prices[0] = 2.5;
        System.out.println(days[1] + " " + days.length);
        System.out.println(prices[0] + " " + prices[1]);
        System.out.println(seen[0] + " " + names[0]);
    }
}
Output
Tue 3
2.5 0.0
false null

The size is fixed

This array has three boxes, numbered zero to two. Then we try to use box three. Run it. Array index out of bounds exception. There is no box three. The program crashes, at line seven.

Main.javajava
public class Main {
    public static void main(String[] args) {
        int[] cups = new int[3];
        cups[0] = 4;
        cups[1] = 7;
        cups[2] = 2;
        cups[3] = 9;
        System.out.println("Done");
    }
}
Output
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of
bounds for length 3
    at Main.main(Main.java:7)

Default values

When you create an array with new, every box gets a default value. It depends on the type.

TypeStarts as
int, long, double0 or 0.0
booleanfalse
charan empty character
String, objectsnull

Summary

Create an array with values in braces, or with new and a size. The size can't change, and the last index is length minus one. Next, looping over arrays.

Key takeaways
  • { values }
  • new int[3]
  • Last index = length - 1
Next up: Looping Over Arrays — visit every box