Arrays in Java

20 exercises

About Arrays

In Java, data structures that can hold zero or more elements are known as collections. An array is a collection that has a fixed size and whose elements must all be of the same type. Elements can be assigned to an array or retrieved from it using an index. Java arrays use zero-based indexing: the first element's index is 0, the second element's index is 1, etc.

Here is the standard syntax for initializing an array:

type[] variableName = new type[size];

The type is the type of elements in the array which can be a primitive type (eg. int) or a class (eg. String).

The size is the number of elements this array will hold (which cannot be changed later). After array creation, the elements are initialized to their default values (typically 0, false or null).

// Declare array with explicit size (size is 2)
int[] twoInts = new int[2];

Arrays can also be defined using a shortcut notation that allows you to both create the array and set its value:

// Two equivalent ways to declare and initialize an array (size is 3)
int[] threeIntsV1 = new int[] { 4, 9, 7 };
int[] threeIntsV2 = { 4, 9, 7 };

As the compiler can now tell how many elements the array will have, the length can be omitted.

Array elements can be assigned and accessed using a bracketed index notation:

// Assign second element by index
twoInts[1] = 8;

// Retrieve the second element by index and assign to the int element
int secondElement = twoInts[1];

Accessing an index that is outside of the valid indexes for the array results in an IndexOutOfBoundsException.

Arrays can be manipulated by either calling an array instance's methods or properties, or by using the static methods defined in the Arrays class (typically only used in generic code). The most commonly used property for arrays is its length which can be accessed like this:

int arrayLength = someArray.length;

Java also provides a helpful utility class java.util.Arrays that has a lot of useful array-related methods (eg. Arrays.equals).

Java also supports multi-dimensional arrays like int[][] arr = new int[3][4]; which can be very useful.

The fact that an array is also a collection means that, besides accessing values by index, you can iterate over all its values using a for-each loop:

char[] vowels = { 'a', 'e', 'i', 'o', 'u' };

for(char vowel: vowels) {
    // Output the vowel

// => aeiou

If you want more control over which values to iterate over, a for loop can be used:

char[] vowels = { 'a', 'e', 'i', 'o', 'u' };

for (int i = 0; i < 3; i++) {
    // Output the vowel

// => aei
Edit via GitHub The link opens in a new window or tab

Learn Arrays

Practicing is locked

Unlock 18 more exercises to practice Arrays