Free Java Tutorials >> Table of contents >> Arrays

1. Array Declarations

Declaring an Array

We learned about variables already, such as int x = 5;, where x stores one number. An array is a variable that can store more than just one value. The syntax for an array is like so:

public class MyProgram {
    public static void main(String[] args) {
        //Let's create an array with the values 10,20,30,and 42
		int[] x = {10,20,30,42}; //Read "int array x equals the array of 10,20,30,42"

		//Another way to declare an array with initial values:
		int[] x = new int[]{1,2,3,4,5};

		//Let's create another array, y, with 5 zero's:
		int[] y = new int[5];    //also works for other types like double[] y = new double[5];
    }
}

As you can see in the above example, there are three types of Java array declarations:

  • Declaring the array with initial values. TYPE[] varname = {VAL1,VAL2,VAL3}; This declaration must be used as a statement on its own line
  • Declare the array equal to an array expression. TYPE[] vartwo = new TYPE[]{VAL1,VAL2,VAL3}. This has an advantage in that the right hand side can be used as part of a larger expression. In other words "new TYPE[]{X,Y,Z}" is an array expression in the same way that (1+2) is an int expression.
  • Declare an array equal to an empty array expression. TYPE[] varthree = new TYPE[initial_size]. Unlike C and C++, Java sets each item in the array to its default value. For numeric primitives (byte, short, int, long, float, double), the default value is zero. For char, the default value is the "null character", which is equal to (char)0. For booleans, the default value is false. Finally, for Objects such as strings, the default value is "null". We will learn more about null later.

Because Java initializes arrays with values, creating new arrays can take a lot of time. Unlike C and C++, creating an array of size 1000 will cause Java to initialize 1000 elements.

Java arrays cannot be resized. To resize an array, you must create another array of a different size and copy the elements over to the new array. We will learn about the resizeable List class in a later section.

2. Indexing and Elements

The first item in array x is x[0]

Here we print the first number of array x:

public class MyProgram {
    public static void main(String[] args) {
        int[] x = {42,43,44,45};
		System.out.println(x[0]); //prints 42

		System.out.println(x[1]); //prints 43
		System.out.println(x[2]); //prints 44
		System.out.println(x[3]); //prints 45
		
		//You cannot do System.out.println(x[4]); 
    }
}

We say x[0] is the first element. The index, or position, of the first element is 0. Java is a zero-indexed language like C and C++. Thus, if an array has 4 items, the first element is index 0 and the last element is index 3.

Assigning values in an array

Just as printing x[0] outputs the first value. We can change the first value with x[0] = NEW_VALUE:

public class MyProgram {
    public static void main(String[] args) {
		int[] z = {123,234,345,456};
		System.out.println(z[1]); //prints 234
		z[1] = 42; //assigns z[1] to 42
		System.out.println(z[1]); //prints 42
    }
}

Array Length

The length of an array x is x.length, which is of type int. For example:

public class MyProgram {
    public static void main(String[] args) {
		int[] a = {10,20,30};
		System.out.println(a.length);     //3, because there are 3 items
		System.out.println(a[a.length-1]); //prints 30, the last item. same as a[3-1] or a[2] in this case
    }
}

As you can see the last element of an array x is always x[x.length-1].

3. Array Loops, and ArrayIndexOutOfBoundsException

Printing all values in an array

If an array has 4 items, then you need to print elements 0 to 3. Thus the for loop starts a variable at 0, and stops the variable before it researches the array length:

public class MyProgram {
    public static void main(String[] args) {
		int[] b = {123,234,345,456};
		for(int i = 0; i < b.length ; i++) { //i counts 0,1,2,3
			System.out.println(b[i]); //prints 123 when i is 0, 234 when is is 1, etc
		}
    }
}

Printing all the values backwards

An adept programmer should memorize the syntax for looping through an array forwards as well as backwards:

public class MyProgram {
    public static void main(String[] args) {
		int[] c = {123,234,345,456};
		for(int i = c.length - 1; i >= 0 ; i--) { //i counts 3,2,1,0
			System.out.println(c[i]); 
		}
    }
}

For backwards iteration, you need to always start at length - 1 and continue down to 0.

ArrayIndexOutOfBoundsException

An error occurs if you try to read or write to a position of an array before 0 or beyond the length-1: ArrayIndexOutOfBoundsException . Here's an example program that crashes:

public class MyProgram {
    public static void main(String[] args) {
		int[] z = {123,234,345,456};
		System.out.println(z[4]); //Crashes with ArrayIndexOutOfBoundsException
    }
}

To avoid these kind of errors, write a loop over 10 items as for(int i=0;i<array.length;i++) rather than for(int i=0;i<10;i++). This way, if you change the array size later, your program will adapt to handle the new size correctly.

An example: square every value in an array

We want to multiply each value in an array by itself:

public class MyProgram {
    public static void main(String[] args) {
		int[] b = {1,2,3,4,5};
		for(int i = 0; i < b.length ; i++) { //i counts 0,1,2,3
			b[i] *= b[i]; //square b[i]
		}
		
		//Now let's print the array
		for(int i = 0; i < b.length ; i++) { 
			System.out.println(b[i]); 
		}
    }
}

Previous: Loop Algorithms

Next: Array Algorithms