Java Arrays Tutorial: Declare, Create and Initialize
Introduction
A program which works with the marks of 30 students should not need 30 separate variables. An array holds many values of the same type under one name, each at a numbered position. This tutorial explains Java arrays - how to declare, create and initialize them. We will start with what an array is and how it is stored. We will then declare and create arrays, look at the default values of their elements, and initialize them with values. Next we will read and change elements by index, go through arrays with loops, and see what happens when an index is out of range. Lastly, we will see that array variables are references, and what that means when you copy them.
(Note - Looping through arrays uses the for loopClick to read tutorial: Java for Loop Tutorial with Examples and the enhanced for loopClick to read tutorial: Java Enhanced for Loop (for-each) with Examples.) What is an array? An array is a fixed-size, ordered sequence of elements which all have the same type. Its key properties are -
Default values of array elements
When an array is created with
OUTPUT of the above code
Explanation of the code
OUTPUT of the above code
Note - The short form
Accessing and changing elements
An element is read or changed with its index in square brackets -
OUTPUT of the above code
The exception message names the bad index and the array's length -
OUTPUT of the above code
Explanation of the code
(Note - Looping through arrays uses the for loopClick to read tutorial: Java for Loop Tutorial with Examples and the enhanced for loopClick to read tutorial: Java Enhanced for Loop (for-each) with Examples.) What is an array? An array is a fixed-size, ordered sequence of elements which all have the same type. Its key properties are -
- Indexed from 0: the first element is at index 0, and the last is at index
length - 1. - Fixed length: the size is set when the array is created, and cannot change. For a list which grows and shrinks, use
ArrayList. - One type: an
int[]holds onlyints, and aString[]onlyStrings. - An object: in Java an array is an object, created on the heap, with a
lengthfield. Its elements sit next to each other in memory, so reading any element by its index is very fast.
new and a size.
Declaring and creating arrays
int[] marks; // declares a variable that can refer to an int array
marks = new int[5]; // creates an array of 5 ints, and stores a reference to it
double[] prices = new double[3]; // declare and create in one statement
String[] names = new String[4];
int scores[] = new int[5]; // C-style brackets after the name: allowed, but not recommended
- The type
int[]is read as "int array". Putting the brackets after the type, not the name, keeps all the type information together, and is the standard Java style. - The size can be any
intexpression, such asnew int[count], and can be 0. A negative size throws aNegativeArraySizeException.
new, every element is automatically set to its type's default value - unlike local variables, array elements never hold "nothing".
Default values of array elements
//ArrayDefaults.java
import java.util.Arrays;
public class ArrayDefaults {
public static void main(String[] args) {
int[] counts = new int[3];
double[] prices = new double[3];
boolean[] flags = new boolean[3];
char[] letters = new char[3];
String[] names = new String[3];
System.out.println("int[] : " + Arrays.toString(counts));
System.out.println("double[] : " + Arrays.toString(prices));
System.out.println("boolean[] : " + Arrays.toString(flags));
System.out.println("char[] : " + (int) letters[0] + " (the character with code 0)");
System.out.println("String[] : " + Arrays.toString(names));
System.out.println("length : " + names.length);
}
}
int[] : [0, 0, 0] double[] : [0.0, 0.0, 0.0] boolean[] : [false, false, false] char[] : 0 (the character with code 0) String[] : [null, null, null] length : 3
- Numeric elements default to 0,
booleanelements tofalse, andcharelements to the character with code 0. - Elements of any reference type, such as
String, default tonull. Calling a method on one -names[0].length()- would throw aNullPointerException. Arrays.toString()turns an array into readable text. Printing the array directly withprintln(counts)prints something like[I@1b6d3586instead - the array's type and hash code. More on this class in the Arrays class tutorialClick to read tutorial: Java Arrays Class: sort, binarySearch, fill, copyOf.lengthis a field, not a method -names.length, with no parentheses.
Initializing arrays with values
//ArrayInit.java
import java.util.Arrays;
public class ArrayInit {
public static void main(String[] args) {
int[] primes = {2, 3, 5, 7, 11};
String[] days = {"Mon", "Tue", "Wed"};
System.out.println(Arrays.toString(primes) + " has length " + primes.length);
System.out.println(Arrays.toString(days));
int[] squares;
squares = new int[] {1, 4, 9, 16}; // later initialization needs new int[]
System.out.println(Arrays.toString(squares));
printAll(new String[] {"Tom", "Harry"}); // an anonymous array passed to a method
int[] evens = new int[5];
for (int i = 0; i < evens.length; i++) {
evens[i] = (i + 1) * 2; // filling with a loop
}
System.out.println(Arrays.toString(evens));
}
static void printAll(String[] values) {
System.out.println("printAll: " + Arrays.toString(values));
}
}
[2, 3, 5, 7, 11] has length 5 [Mon, Tue, Wed] [1, 4, 9, 16] printAll: [Tom, Harry] [2, 4, 6, 8, 10]
{1, 2, 3} is allowed only in a declaration. Everywhere else - assigning to an existing variable, or passing to a method - write new int[] {1, 2, 3}. Do not give a size together with an initializer: new int[3] {1, 2, 3} does not compile.
marks[2]. Java checks every index at runtime, and an index below 0 or at length or above throws an ArrayIndexOutOfBoundsException.
Reading, changing and looping over elements
//ArrayAccess.java
public class ArrayAccess {
public static void main(String[] args) {
int[] marks = {72, 85, 90, 64, 88};
System.out.println("First: " + marks[0] + ", last: " + marks[marks.length - 1]);
marks[3] = 70; // change an element
marks[0] += 5; // update an element
for (int i = 0; i < marks.length; i++) {
System.out.println("marks[" + i + "] = " + marks[i]);
}
int sum = 0;
for (int m : marks) {
sum += m;
}
System.out.println("Average: " + (double) sum / marks.length);
System.out.println(marks[5]); // one past the end
}
}
First: 72, last: 88 marks[0] = 77 marks[1] = 85 marks[2] = 90 marks[3] = 70 marks[4] = 88 Average: 82.0 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5 at ArrayAccess.main(ArrayAccess.java:19)
Index 5 out of bounds for length 5. Valid indexes for this array are 0 to 4. This check is one of Java's safety features: in some languages, reading past the end of an array silently returns whatever happens to be in memory.
Array variables are references
An array variable does not contain the array - it holds a reference to the array object. Assigning one array variable to another copies the reference, not the elements, so both variables then refer to the same array.
Assigning an array variable copies the reference
//ArrayReferences.java
import java.util.Arrays;
public class ArrayReferences {
public static void main(String[] args) {
int[] original = {1, 2, 3};
int[] alias = original; // same array, two names
alias[0] = 99;
System.out.println("original: " + Arrays.toString(original));
int[] copy = original.clone(); // a new array with the same elements
copy[1] = 42;
System.out.println("original: " + Arrays.toString(original));
System.out.println("copy : " + Arrays.toString(copy));
System.out.println("original == alias : " + (original == alias));
System.out.println("original == copy : " + (original == copy));
System.out.println("equal contents : " + Arrays.equals(new int[] {1, 2}, new int[] {1, 2}));
}
}
original: [99, 2, 3] original: [99, 2, 3] copy : [99, 42, 3] original == alias : true original == copy : false equal contents : true
- Changing
alias[0]changedoriginal[0]too, because there is only one array. clone()created a separate array, so changingcopyleftoriginalalone.==compares references - whether two variables point to the same array. To compare the contents of two arrays, useArrays.equals().- The same applies when an array is passed to a method: the method receives a copy of the reference, so it can change the caller's array. See Is Java pass-by-value or pass-by-reference?Click to read tutorial: Is Java Pass-by-Value or Pass-by-Reference?
new, and saw the default values of their elements. Next we initialized arrays with values, using initializers, new int[] {...} and loops. We then read and changed elements by index, looped over them, and met the ArrayIndexOutOfBoundsException. Lastly, we saw that array variables hold references, so assignment shares an array while clone() copies it. In the next tutorial, we will look at arrays of arrays - multi-dimensional and jagged arraysClick to read tutorial: Multi-Dimensional and Jagged Arrays in Java.Java Fundamentals Tutorials
Java break, continue and Labeled Loops ExplainedClick to read tutorial: Java break, continue and Labeled Loops Explained Multi-Dimensional and Jagged Arrays in JavaClick to read tutorial: Multi-Dimensional and Jagged Arrays in Java Java Arrays Class: sort, binarySearch, fill, copyOfClick to read tutorial: Java Arrays Class: sort, binarySearch, fill, copyOf Common Java Array Programs with ExamplesClick to read tutorial: Common Java Array Programs with Examples What is Java? History, Features, Editions and UsesClick to read tutorial: What is Java? History, Features, Editions and Uses
Java break, continue and Labeled Loops ExplainedClick to read tutorial: Java break, continue and Labeled Loops Explained Multi-Dimensional and Jagged Arrays in JavaClick to read tutorial: Multi-Dimensional and Jagged Arrays in Java Java Arrays Class: sort, binarySearch, fill, copyOfClick to read tutorial: Java Arrays Class: sort, binarySearch, fill, copyOf Common Java Array Programs with ExamplesClick to read tutorial: Common Java Array Programs with Examples What is Java? History, Features, Editions and UsesClick to read tutorial: What is Java? History, Features, Editions and Uses