Sub topic 2
Declaring, Creating, and Initializing Arrays
An array is a fixed-size sequence of values of the same type. Each value is called an element. For example, an array can hold the scores 80, 90, and 100 together instead of requiring three separate variables.
In Java, working with an array begins with three related steps:
- Declare a variable that can refer to an array.
- Create the array.
- Initialize its elements with values.
You can perform these steps separately or combine them in one line. This chapter assumes you know basic Java variables, types, and how to run a Java program.
Declare an array variable
A declaration introduces a variable and states its type. Here is a declaration for an array of integers:
int[] scores;
Read int[] as “array of integers.” The brackets are part of the array type. The name scores is the variable name.
This declaration does not create an array. It only says that scores can refer to an int array. A variable holds a reference, which is how the program can find the array.
For comparison, int score declares one integer variable, while int[] scores declares a variable for an array of integers.
Java also accepts int scores[], but placing the brackets with the type, as in int[] scores, makes the array type easier to see.
Create an array with a size
To create an array, use new, the element type, and a size in brackets:
new int[3]
This creates an array with three int elements. The size is also called the array’s length. Once created, an array’s length cannot change.
You can assign the new array to the variable you declared:
scores = new int[3];
An assignment gives a value to a variable. In this case, scores now refers to the new array.
You can combine declaration and creation:
int[] scores = new int[3];
Java gives every element a starting value when it creates the array. For an int array, that value is 0. You can then replace those zeros with the values you want.
Worked example: Set up scores
The following program declares an array variable, creates an array, and puts three scores into it.
Save it as ArraySetup.java:
public class ArraySetup {
public static void main(String[] args) {
int[] scores;
scores = new int[3];
scores[0] = 80;
scores[1] = 90;
scores[2] = 100;
System.out.println("Number of scores: " + scores.length);
System.out.println("First score: " + scores[0]);
System.out.println("Second score: " + scores[1]);
System.out.println("Third score: " + scores[2]);
}
}Compile and run it from the same directory:
javac ArraySetup.java
java ArraySetupThe program prints a count of 3, followed by the scores 80, 90, and 100.
The brackets in scores[0] select an element. The number inside is an index, which is a position in the array. Java starts numbering positions at 0, so the first position is 0.
The expression scores.length gives the number of elements. In this example, new int[3] creates three elements, and the three assignments replace their starting zeros.
Initialize with a list of values
When you already know the values, you can create and fill an array in one declaration:
int[] scores = {80, 90, 100};
The braces contain an array initializer: a list of starting element values. Commas separate the values. Java creates the array with a length that matches the number of values, so this array has length 3.
The values appear in the order you write them. The first element is 80, the second is 90, and the third is 100.
You can use an array initializer with other types too:
String[] names = {"Ada", "Lin"};creates an array of two strings.boolean[] flags = {true, false};creates an array of two boolean values.double[] prices = {1.5, 2.75};creates an array of two decimal numbers.
A string is text, and a boolean value is either true or false. The declared element type controls which values the array can hold. For example, an int array cannot hold the decimal value 1.5.
Use the explicit form after declaration
The short brace form works in an array variable declaration. If you have already declared the variable, include new and the array type:
int[] scores;
scores = new int[] {80, 90, 100};
The second line creates an array and assigns it to scores. Java counts the values to determine the length.
The form scores = {80, 90, 100}; is not valid as a separate assignment. Use new int[] in that case.
Do not put a size between the brackets when you supply a list of values. For example, new int[3] {80, 90, 100} is not valid Java. The list already determines the size.
Compare the creation forms
| Form | What it creates |
|---|---|
| `new int[3]` | Three `int` elements, each starting at `0` |
| `{80, 90, 100}` in a declaration | Three `int` elements with the listed values |
| `new int[] {80, 90, 100}` | Three `int` elements with the listed values |
| `new int[0]` | An array with no elements |
A size and a value list can look similar but mean different things. new int[3] creates three elements. By contrast, new int[] {3} creates one element, whose value is 3.
An array can have length 0. It is still an array, but it has no elements. You can create one with new int[0] or with an empty initializer, as in int[] values = {};.
Choose a size while the program runs
The size does not have to be a number written directly inside the brackets. It can come from an integer variable:
int count = 2;
int[] planned = new int[count];
Java uses the value of count at the time it creates the array. Changing count later does not change the array’s length.
The following program shows several creation forms. Save it as ArrayForms.java:
public class ArrayForms {
public static void main(String[] args) {
int[] threeZeros = new int[3];
int[] oneValue = {3};
int[] empty = {};
int[] scores;
scores = new int[] {80, 90, 100};
int count = 2;
int[] planned = new int[count];
count = 4;
System.out.println("threeZeros length: " + threeZeros.length);
System.out.println("oneValue length: " + oneValue.length);
System.out.println("empty length: " + empty.length);
System.out.println("scores length: " + scores.length);
System.out.println("planned length: " + planned.length);
System.out.println("count: " + count);
}
}Run it with:
javac ArrayForms.java
java ArrayFormsThe lengths printed are 3, 1, 0, 3, and 2. The final value of count is 4, but planned still has length 2.
A size must not be negative. A negative size causes a NegativeArraySizeException when the program runs. The size must also be an integer expression Java accepts for an array size; for example, a double value cannot be used directly.
Common mistakes
- Declaring without creating:
int[] scores;does not make an array. Create one before trying to use it. - Confusing a size with a value:
new int[3]means three elements, not one element containing3. - Using the short initializer in a later assignment: After
int[] scores;, usescores = new int[] {80, 90, 100};. - Trying to change an existing length: You can assign a new array to a variable, but that creates a different array. It does not resize the original.
- Mixing incompatible types: The values in an initializer must be suitable for the declared element type.
Exercise
What are the length and first value of int[] items = {7, 8, 9};?
Show answer
The length is 3, and the first value is 7.
Exercise
After int[] items;, how can you create an array containing 4 and 5 and assign it to items?
Show answer
Write items = new int[] {4, 5};.
Exercise
A program creates int[] values = new int[2];. How many elements does it have, and what are their starting values?
Show answer
It has two elements. Both start at 0.