Room 2 of 15 · about 25 minutes

Declaring and creating an array

Room 1 gave you what an array is. This room is how you make one.

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.

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.

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

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

  2. trace
    Show the answer

    [0, 0, 0].

  3. write
    Show the answer

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

  4. trace
    Show the answer

    null.

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 String[] ss = new String[2]; System.out.println(ss[0].length());, predict the result.

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. Given boolean[] bs = new boolean[2];, predict bs[1].trace
    Show the answer

    false.

  2. Given double[] ds = new double[3];, predict ds[2].trace
    Show the answer

    0.0.

  3. Given int n = 4; double[] ds = new double[n + 1];, predict the length and contents.trace
    Show the answer

    length 5, contents [0.0, 0.0, 0.0, 0.0, 0.0].

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

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

  5. 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).

  6. Given int[] xs = new int[4];, predict xs[0].trace
    Show the answer

    0.

Optional challenge

This one is optional. Do what the room says you can do, without opening any answers, then read the two traps below and check your work against them. Each trap is copied from the notes for this room.

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

How this room finishes

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