Concepts / Default Values of Variables

Default Values of Variables

An array can be initialized by listing its values, separated by commas, between a pair of braces, and its length is the number of items in that list.

  • Programming

A Fresh Set of Values Later?

Once you have written an array declaration that lists its values, it is tempting to assume the same brace-enclosed list can be used anywhere in a program to give an array a fresh set of values. The belief feels natural, because the list looks like a general way of filling an array. Before you accept it, test it. The answer depends on exactly where in a program the braces appear.

What do you think happens?

Suppose a has already been declared as an int array. Will this line compile in Java: a = {4, 8, 15};

  • Yes, it compiles

  • No, the compiler rejects it

Reveal answer
Answer:

No, the compiler rejects it.

The braces list form is recognized only in a declaration statement. The values 4, 8, and 15 are perfectly reasonable on their own, so the problem is entirely the position of the braces in the statement, not the values.

Listing Values Between Braces

An array holds several elements rather than a single value, so initializing an array variable means supplying those elements at once. The first form the source introduces lists the values, separated by commas, and encloses the whole list between a pair of braces. The list is attached to the declaration itself, so the array variable is created and filled in one statement.

Code walkthrough
int[] smallPrimes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};
  1. 1
    The declaration creates an array of int and gives it the name smallPrimes.
  2. 2
    The values 2 through 29 between the braces are the first ten primes, and they are placed into the array in the order listed.
  3. 3
    No length is written anywhere in the statement. The length comes from counting the items in the list.
  • int[] names the element type and marks the variable as an array of int
  • smallPrimes is the name of the array variable
  • The braces enclose the list of values that will fill the array
  • The statement is read as a single action: it names the array, sets its element type, and provides the values
a[0]4a[1]8a[2]15
When int[] a = {4, 8, 15} runs, which value sits at index 0, 1, and 2, and how does the list map onto those positions?

Read the diagram from left to right. The first listed value, 4, lands at index 0, because counting starts at zero. The second value, 8, lands at index 1, and 15 lands at index 2. Each position in the array holds exactly the value that appears at the matching place in the list.

How the Number of Items Sets the Length

The source explains that a declaration like the smallPrimes statement creates an array of int with length 10, filled with the values in the list. The length is not written anywhere in the statement. It is determined by counting the items between the braces. If you add or remove a value inside the braces, the length changes with it.

Worked example

Finding the length and last index of a braces list

Given int[] a = {4, 8, 15};, what is the length of a, and what is the index of its last element?

  1. 1
    Count the listed items

    The braces contain 4, 8, and 15, so there are three items.

  2. 2
    Set the length

    The length of the array equals the number of items, so a has length 3.

  3. 3
    Find the last index

    Indexing starts at zero, so the final index is always length minus one. Here that is 3 minus 1, which gives index 2, holding 15.

Result

The length is 3, and the last index is 2, which holds the value 15.

Why Braces Fail in an Assignment

The restriction is the central point of the braces syntax. The source states that this syntax cannot be used in an assignment statement. It can only be used in a declaration statement, at the moment the array variable is declared. The list form is therefore a way of creating and filling an array at once, not a general way of replacing the contents of one that already exists.

java
Output
The second line does not compile. The compiler rejects the braces list because it is not in a declaration.
Notes on the code
  • Line 1 is a declaration. The braces list is recognized here.
  • Line 2 is an assignment to an array variable that already exists. The braces list is not recognized here.

Creating an Array with the new Operator

The source describes a second way to initialize an array variable: give it an array created with the new operator. Unlike the braces form, this approach can also be used in assignment statements. You specify the element type and the size, and Java creates an array of that size. The source notes that when an array is created this way, all of its elements have their default value.

java
Notes on the code
  • new int[5] creates an array of five int elements
  • new String[100] creates an array of 100 String elements
  • Neither line lists values, so every element starts at its default
a[0]0a[1]0a[2]0a[3]0a[4]0
After new int[5] runs, what does each of the five slots hold before any values are assigned?

In Java, the default for an int element is 0, so every slot in the diagram holds 0 until you store something else there. The source does not list defaults in this passage, but the same idea applies to other element types. The default for a String element is null. A freshly created nameList therefore holds 100 null references until you store strings into it.

Key point

Because the new form can appear in an assignment, it is the form you use when an array must be created with a size and filled later, or when its contents must be replaced later in the program.

Mistakes with the Two Initialization Forms

  • Common mistake

    Using the braces list in an assignment to replace an array's contents

    What it looks like
    a = {4, 8, 15};
    Why it fails

    The braces list syntax is recognized only in a declaration statement, so the compiler rejects it here.

    Do this instead

    Use the new operator in the assignment, for example a = new int[]{4, 8, 15};, or declare a new array with the list.

  • Common mistake

    Assuming a new array has the values you intended to store

    What it looks like
    int[] a = new int[5]; then reading a[0] expecting a value you never assigned
    Why it fails

    When an array is created with new, all of its elements have their default value, not the values you have in mind.

    Do this instead

    Store the values you need into each element, or check that the defaults are what the program expects.

  • Common mistake

    Thinking the length is written in the braces form

    What it looks like

    Believing int[] smallPrimes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}; has a separate length number

    Why it fails

    The length is not written anywhere in the statement. It comes from counting the items in the list.

    Do this instead

    Count the listed items to find the length, and remember the final index is always length minus one.

Choosing a Form for the Situation

The source offers a decision rule. Choose the braces list when the values are known at declaration time. Choose the new operator when the array must be created with a size and filled later. Read the comparison as a decision aid. The two forms differ in where they may appear, in how their length is set, and in what their contents are before you act on them.

Where it worksDeclaration onlyWhere it worksDeclaration or assignmentLengthCount of listed itemsLengthSize given to newContentsThe listed valuesContentsDefaults until stored
Given a situation, should you list known values in braces or create an array with new and fill it later, and what does each choice imply for the array's length and contents?
SituationForm to useWhy
Values are known when the array is declaredBraces listThe list states the values directly in the declaration
Array needs a size now and values filled laternew operatorThe new operator takes a type and size and can appear in assignment
Array contents must be replaced later in the programnew operator in an assignmentThe braces list is not allowed in assignment

Choosing between the braces list and the new operator

Tracing Array Setup by Hand

MEDIUM

For each line below, decide whether it is legal Java and, if it is, state the length of the array and what its elements hold before any further assignment: (1) int[] a = {4, 8, 15}; (2) int[] b = new int[5]; (3) int[] c; c = {7, 9}; (4) String[] names = new String[3];

Hints
  • Ask first whether the braces appear in a declaration or an assignment.
  • For the length, count the listed items, or read the number given to new.
  • For new, remember that every element starts at its default value, which is 0 for int and null for String.

Key Takeaways

  • An array can be initialized by listing its values, separated by commas, between braces, and its length is the number of items in that list.
  • The braces list syntax can only be used in a declaration statement; it cannot be used in an assignment statement.
  • The new operator creates an array of a given type and size, can be used in assignment, and gives every element its default value, such as 0 for int and null for String.
  • Choose the braces list when the values are known at declaration time, and the new operator when the array must be created with a size and filled later.