Room 2 of 14 · about 40 minutes

Declaring an array and creating one

Room 1 said what an array is. This room is how you write one down and bring it into existence.

Tasks checked0 of 4 XP earned on this path0

What this room checks you can do

Student can write a new-with-size construction for any primitive or reference element type, using a literal or variable size.

Notes

new with size

The most general way to construct an array is new <type>[<size>]. The size is any integer expression: it can be a literal 5, a variable n, or an expression numStudents * 2. The runtime allocates a contiguous block large enough for that many elements, auto-initializes every slot to the type's zero-equivalent, which the rule for default values by type spells out, and returns a reference to the new object. The size is fixed at this moment and cannot change.

The bracket placement on each side is asymmetric and matters: on the left side, brackets are part of the type (no number inside); on the right side, brackets contain the size expression. Putting a number on the left or omitting it on the right is a compile error.

final int[] xs = new int[5];           // 5 ints, all zero
final int n = 10;
final double[] prices = new double[n]; // 10 doubles, all 0.0
final String[] names = new String[3];  // 3 String slots, all null
// final int[5] bad = new int[5];      // compile error: size on the type

In other languages

  • C: int xs[5]; (stack) or int xs = malloc(5 sizeof(int)); (heap). C does not zero-initialize unless you use calloc or initialize explicitly.
  • Python: xs = [0] * 5 builds a 5-element list pre-filled with zero (and you can append later).
  • Kotlin: IntArray(5) constructs a 5-slot int array, auto-initialized to 0.

Array initializer list

When you know the contents at the time of declaration, write them directly between curly braces: int[] xs = {1, 2, 3};. Java counts the values, allocates an exact-fit array, and fills it in. No new keyword is required: this is one of only two places in Java where an object is constructed without an explicit new (the other is a String literal like "hello").

The initializer-list form is read-only at the literal level (the expression {1, 2, 3} only appears in a declaration or as the right-hand side of new int[]{1, 2, 3}). After the assignment the array object is fully mutable just like any other; the elements can be reassigned with xs[i] = .... The initializer is a convenience for initial contents, not a contract that the array stays constant.

final int[] daysIn = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
final String[] names = {"Alice", "Bob", "Carol"};
// names[0] = "Alex";   // legal: only the *initialization* is the literal form

In other languages

  • Python: xs = [1, 2, 3] is the list literal: same shape, dynamic length.
  • C: int xs[] = {1, 2, 3}; (the C ancestor of this syntax). C also infers the length.
  • Kotlin: intArrayOf(1, 2, 3) builds an IntArray; no curly-brace literal.

Default values by type

When new int[5] runs, Java does not leave the slots full of garbage memory the way C's malloc does: every slot is auto-initialized to the element type's zero-equivalent. The defaults are: numeric primitives get 0 (or 0.0 for float/double), boolean gets false, char gets '\u0000' (the null character), and any reference type (String[], Point[], anything that is not a primitive) gets null.

The reference-type default has the most consequences. Constructing String[] names = new String[3] does not give you three empty strings; it gives you three null references, and any names[0].length() call will throw NullPointerException until you assign a real String into each slot. This is the two-step construction problem for arrays of objects, which classes and objects covers: construct the array, then construct each element.

final int[] xs = new int[3];           // [0, 0, 0]
final double[] ds = new double[2];     // [0.0, 0.0]
final boolean[] bs = new boolean[2];   // [false, false]
final String[] ss = new String[2];     // [null, null]: NOT ["", ""]
// ss[0].length();                     // NullPointerException

In other languages

  • C: int xs[5]; is not zero-initialized. Use calloc or explicit assignment to get zeros.
  • Python: [0] * 5 is the closest analog; everything is reference-typed so "default" is whatever you put in.
  • Kotlin: primitive IntArray(n) defaults to 0; reference Array<String?>(n) { null } defaults to whatever the lambda returns.

What this room assumes you already have

Tasks

Do each one, then check the box. Checking a box is you saying you did it. You can uncheck a box if you check it by accident.

  1. trace
    Show the answer

    [0, 0, 0].

  2. trace
    Show the answer

    no: it is a declaration only; the value of xs is null.

  3. trace
    Show the answer

    3 (Java counts the values).

  4. trace
    Show the answer

    0.

Self check

Type what you think the answer is. Getting it wrong costs nothing and you can try as many times as you want.

Given double[] ds = new double[3];, predict ds[2].

Practice, untimed

Open this whenever you want, before the tasks or after them. Nothing in this section is recorded and nothing here is timed.

  1. Construct an int[] of length numStudents (already declared) and store it in a new variable named scores.write
    Show the answer

    final int[] scores = new int[numStudents];.

  2. Given int xs[], ys;, predict the type of ys.trace
    Show the answer

    int (not int[]): only xs got the brackets.

  3. Declare a variable named prices of type double[], in the preferred Java style.write
    Show the answer

    final double[] prices; (or with a construction expression).

  4. Given int[] xs = {1, 2, 3};, predict the result of xs[1] = 99; followed by printing xs[1].trace
    Show the answer

    prints 99: the initializer sets initial contents only.

How this room finishes

This room is done when all 4 tasks are checked and the self check is answered.