Tutorials

The Java Tutorial: Arrays

We've already covered primitive data types in Java. Now, let's delve into arrays, a fundamental aspect of Java programming.

Key Takeaways

  • Arrays are fixed-size collections of elements of the same type.
  • Zero-based indexing is used to access array elements.
  • Use java.util.Arrays for common operations like sorting and searching.

What is an array in Java?

An array is a container object that holds a fixed number of values of a single type. Once set, an array's size remains constant throughout its lifecycle.

Basic example of an array in Java

public class MyClass {
    public static void main(String[] args) {
        char[] myArray = new char[5];
        myArray[0] = 'a';
        myArray[1] = 'b';
        myArray[2] = 'c';
        myArray[3] = 'd';
        myArray[4] = 'e';
        System.out.println(myArray[3]);
        // prints d
    }
}

Creating Arrays

In this example, myArray is declared with a size of 5 characters, specifying both the type char and the size [5]. Alternatively, you can initialize an array directly with values:

char[] myArray = {'a', 'b', 'c', 'd', 'e'};

Assigning elements to an array

The first element in myArray is set using:

myArray[0] = 'a';

Remember, arrays are zero-indexed. To access the 4th element, you use:

myArray[3];
// returns 'd'

Why is the first element 0 and not 1?

Arrays start at index 0, not 1. Zero-based indexing means the index is an offset from the start of the array.

Multidimensional arrays in Java

Java supports arrays within arrays, or multidimensional arrays:

public class MyClass {
    public static void main(String[] args) {
        char[][] myArray = {
            {'a', 'b', 'c', 'd'},
            {'e', 'f', 'g'}
        };

        System.out.println(myArray[1][2]);
        // prints g
    }
}

This example shows a two-dimensional array accessed using myArray[1][2], which retrieves the third element of the second array.

Using the java.util.Arrays class

The java.util.Arrays class provides many utilities for array operations like sorting and searching. Here are some commonly used methods:

Copy an array

import java.util.Arrays;
public class MyClass {
    public static void main(String[] args) {
        char[] myArray = {'a', 'b', 'c', 'd'};
        char[] copyArray = Arrays.copyOfRange(myArray, 1, 3);

        System.out.print(copyArray);
        // prints bc
    }
}

The Arrays.copyOfRange() method creates a new array from a specified range. It's preferred over System.arraycopy() as it constructs the new array internally.

Search an array

Java's binary search allows efficient searching for a specific value:

import java.util.Arrays;
public class MyClass {
    public static void main(String[] args) {
        char[] myArray = {'a', 'b', 'c', 'd'};
        int position = Arrays.binarySearch(myArray, 'c');

        System.out.println(position);
        // prints 2
    }
}

Arrays.binarySearch() returns the index of the element you're searching for. You can also limit the search range by specifying start and end indexes.

Compare array equality

Verify if two arrays are equal using Arrays.equals():

import java.util.Arrays;
public class MyClass {
    public static void main(String[] args) {
        char[] array1 = {'a', 'b', 'c', 'd'};
        char[] array2 = {'a', 'b', 'c', 'd'};
        char[] array3 = {'a', 'c', 'b', 'd'};

        System.out.println(Arrays.equals(array1, array2));
        // prints true
        System.out.println(Arrays.equals(array1, array3));
        // prints false
    }
}

Arrays are considered equal if they have the same elements in the same order.

Sorting an array

Sort arrays effortlessly using Arrays.sort():

import java.util.Arrays;
public class MyClass {
    public static void main(String[] args) {
        int[] myArray = {33, 55, 23, 64, 2};
        Arrays.sort(myArray);

        System.out.println(myArray[0]);
        // prints 2
    }
}

After sorting, myArray is in ascending order. You can also sort strings and customize sorting with comparators.

FAQ

Can arrays in Java hold different data types?

No, arrays in Java are type-specific, meaning all elements must be of the same data type.

What happens if I try to access an array element out of bounds?

Java will throw an ArrayIndexOutOfBoundsException if you try to access an index that doesn’t exist.

How can I initialize a large array efficiently?

You can use array initialization with an array literal to declare and initialize arrays in one line, or use a loop to set values dynamically if needed.

Is it possible to resize an array?

No, arrays have fixed sizes. For dynamic resizing, consider using an ArrayList.

Mastering the tech interviewWhat everyone is doing wrong in tech interviews