CSCD210

Array declaration and creation

Skillcscd210-array-declaration-and-creationTextbookBJP Ch 7

In Java the variable declaration and the array object are two separate things. int[] xs; says "I want a name xs that can refer to an int[] someday"; the array does not yet exist. To bring an array object into being, write new int[5] (which constructs a 5-slot array) or use an initializer list {1, 2, 3} (which constructs and fills in one expression). After construction, every slot is auto-initialized to the type's zero-equivalent. This concept walks through the four pieces students must keep separate: the type, the new-with-size form, the literal initializer form, and the per-type defaults.

new with size

Student can write a new-with-size construction for any primitive or reference element type, using a literal or variable 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.

Type and bracket syntax

Student can write a Java array variable declaration with the brackets in the modern position and explain why int xs[] is discouraged.

The Java type for an array of int is written int[], read aloud as "int array." The brackets are part of the type, not the variable, and they go between the element type and the variable name: int[] xs. Java also accepts the legacy C-style placement int xs[] for backward compatibility, but the modern Java style, which Dr. Steiner expects, puts the brackets with the type.

The reason for preferring int[] xs is that it keeps the type information in one place. When you read int[] xs, you immediately know the type is int[]. When you read int xs[], you have to scan past the variable name to find the brackets, and the convention scales badly to multi-variable declarations: int xs[], ys would declare xs as int[] but ys as just int, a footgun. int[] xs, ys declares both as int[].

final int[] xs = new int[5];     // preferred: brackets with the type
final int ys[] = new int[5];     // legacy: works, but discouraged
final int[] a, b;                // both a and b are int[]
final int c[], d;                // c is int[], d is int: surprise!

In other languages

  • C: brackets are always after the variable: int xs[5];. Java's legacy form is the C form.
  • Python: no static array type; you build list or numpy.ndarray with constructor calls.
  • Kotlin: the type is IntArray (or Array<Int>); no bracket syntax at all.

Array initializer list

Student can write an initializer-list declaration for an array of known contents and explain that new is unnecessary in this form.

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

Student can state the auto-initialized default value for any primitive or reference array element type and predict the runtime behavior of accessing a null slot.

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.