JB Header

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 -
  • 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 only ints, and a String[] only Strings.
  • An object: in Java an array is an object, created on the heap, with a length field. Its elements sit next to each other in memory, so reading any element by its index is very fast.
Declaring and creating arrays Creating an array has two parts - declaring a variable of an array type, and creating the array object with 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 int expression, such as new int[count], and can be 0. A negative size throws a NegativeArraySizeException.
Default values of array elements When an array is created with 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);
  }
}
 OUTPUT of the above code
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
Explanation of the code
  • Numeric elements default to 0, boolean elements to false, and char elements to the character with code 0.
  • Elements of any reference type, such as String, default to null. Calling a method on one - names[0].length() - would throw a NullPointerException.
  • Arrays.toString() turns an array into readable text. Printing the array directly with println(counts) prints something like [I@1b6d3586 instead - 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.
  • length is a field, not a method - names.length, with no parentheses.
Initializing arrays with values When you know the values in advance, an array initializer - values in braces - creates the array, sets its length and fills it in one step.
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));
  }
}
 OUTPUT of the above code
[2, 3, 5, 7, 11] has length 5
[Mon, Tue, Wed]
[1, 4, 9, 16]
printAll: [Tom, Harry]
[2, 4, 6, 8, 10]
Note - The short form {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.
Accessing and changing elements An element is read or changed with its index in square brackets - 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
  }
}
 OUTPUT of the above code
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)
The exception message names the bad index and the array's length - 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}));
  }
}
 OUTPUT of the above code
original: [99, 2, 3]
original: [99, 2, 3]
copy    : [99, 42, 3]
original == alias : true
original == copy  : false
equal contents    : true
Explanation of the code Summary In this tutorial we first saw that an array is a fixed-size, zero-indexed sequence of values of one type, stored as an object. We then declared and created arrays with 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.