What a static array is
An array stores several values of the same type under one name. In Java, an array has a fixed length: you choose how many elements it holds when you create it, and that number never changes. This is why the arrays in this lesson are called static arrays, or fixed-size arrays. If you need a collection that grows, Java offers ArrayList, which is a different type.
Two facts define every Java array:
- All elements have the same type, such as
intorString. - The length is fixed at creation, and elements are numbered from
0tolength - 1.
Creating an array with a length
Use new, the element type and the length in square brackets:
String[] arrayOfStrings = new String[3];
int[] numbers = new int[20];
The first line creates an array of three String slots, and the second creates an array of twenty int slots. The brackets after the type in the declaration (String[], int[]) say "an array of this type", and the number goes after new.
The new array is never empty. Every slot gets the default value for its type:
| Element type | Default value |
|---|---|
int, long, short, byte | 0 |
double, float | 0.0 |
boolean | false |
char | the character with code 0 |
String and other objects | null |
So new int[20] holds twenty zeros, and new String[3] prints as [null, null, null] when passed to Arrays.toString. A null element means "no object yet": calling a method on it, such as arrayOfStrings[0].length(), throws a NullPointerException until you store a string there.
Creating and filling an array at once
When you already know the values, list them in braces, separated by commas:
String[] fruits = {"mango", "kiwi", "grapefruit"};
This is the array initializer. The compiler counts the values, so you do not write the length: fruits has length 3. The same array can be written with the longer form new String[]{"mango", "kiwi", "grapefruit"}. That longer form is required when the array is not part of a declaration. For example, nums = {1, 2, 3}; on its own line does not compile, while nums = new int[]{1, 2, 3}; does.
The exercise, step by step
- Create an
intarray of 20 elements namednumbers, withnew int[20]. The length is fixed at 20 and every element is 0. - Create a
Stringarray namedfruitswith an initializer in braces holding"mango","kiwi"and"grapefruit".
int[] numbers = new int[20];
String[] fruits = {"mango", "kiwi", "grapefruit"};
Checking the result:
System.out.println(numbers.length); // 20
System.out.println(numbers[19]); // 0
System.out.println(fruits.length); // 3
System.out.println(fruits[2]); // grapefruit
Reading, writing and the length
Use the index in square brackets to read or change an element. The first element is index 0 and the last is length - 1:
numbers[0] = 5;
System.out.println(numbers[0]); // 5
System.out.println(fruits[0]); // mango
The length is the field length, with no parentheses: numbers.length. Writing numbers.length() does not compile and gives cannot find symbol. (Strings use length() with parentheses, and lists use size(), which is a common source of mix-ups.)
To visit every element, use a loop:
for (String fruit : fruits) {
System.out.print(fruit + " ");
}
This prints mango kiwi grapefruit . To show the whole array at once, use Arrays.toString(fruits) from java.util, which gives [mango, kiwi, grapefruit]. Passing the array straight to println does not do this: it prints the array's type and an identity code, something like [Ljava.lang.String;@ followed by a number.
Why "static": the length cannot change
There is no way to add a 21st element to numbers. If you need more room, create a new, larger array and copy the old values into it. The helper Arrays.copyOf does this in one call:
int[] primes = {2, 3, 5};
int[] bigger = Arrays.copyOf(primes, 5); // [2, 3, 5, 0, 0]
The new slots get default values, and primes itself is unchanged. When you need a collection that grows and shrinks often, use an ArrayList.
Common mistakes
- Using an index outside the array. The valid indexes of
numbersare 0 to 19.numbers[20] = 1;throwsArrayIndexOutOfBoundsException: Index 20 out of bounds for length 20. Java checks every access, so it never silently reads memory beyond the array. - Thinking the first element is at index 1. It is at index 0.
- A negative length.
new int[-1]throws aNegativeArraySizeExceptionat run time. - Using the initializer after declaration. Braces alone only work in the declaration, as shown above.
- Treating
nullelements as strings. A freshnew String[3]holds threenullvalues, not three empty strings. - Copying with
=.int[] alias = primes;makes a second name for the same array, not a copy. Changingalias[0]also changesprimes[0]. UseArrays.copyOfto make an independent copy.
Key takeaways
- A static array has a fixed length and a single element type. Create it with
new Type[length]or with braces. - New arrays are filled with defaults: 0,
falseornull. - Indexes run from 0 to
length - 1, and the length is the fieldlength. - To change the size, create a new array and copy the data.
