Skip to content

Java Arrays

An array is a basic data structure that is a container that can hold a fixed number of elements of the same type. The size of an array is determined at creation and cannot be changed afterward.

Declaring Arrays

Declaring an array variable does not create an array in memory; it only tells the compiler that this variable will refer to an array of a specific type.

Syntax:

java
dataType[] arrayName;   // Recommended way
// or
dataType arrayName[];   // C/C++ style, but not recommended

Example:

java
// Declare an array that can hold integers
int[] scores;

// Declare an array that can hold strings
String[] names;

Creating and Initializing Arrays

After declaring an array, you need to use the new keyword to create the array and specify its size.

1. Create and Specify Size

After creating an array, its elements are automatically initialized to default values (0 for numbers, false for booleans, null for reference types).

java
// Create an array that can store 10 integers
int[] scores = new int[10];

// Create an array that can store 5 strings
String[] names = new String[5];

// Access elements and assign values
scores[0] = 95; // Array indexing starts at 0
scores[1] = 88;

names[0] = "Alice";

2. Create and Initialize Directly

You can create and initialize an array at the same time by providing an initializer list using curly braces {}. The compiler automatically determines the array size based on the number of elements.

java
// Create and initialize an integer array
int[] numbers = {10, 20, 30, 40, 50};

// Create and initialize a string array
String[] fruits = {"Apple", "Banana", "Orange"};

Accessing Array Elements

You can access or modify any element in an array through its index. Array indexing starts at 0, and the maximum index is array length - 1.

java
int[] numbers = {10, 20, 30};

// Access the first element (index 0)
int firstNumber = numbers[0]; // firstNumber value is 10

// Modify the third element (index 2)
numbers[2] = 35;

// Attempting to access a non-existent index will cause an exception
// System.out.println(numbers[3]); // This throws ArrayIndexOutOfBoundsException

Array length Property

Every array has a length property (note: it's not a method) that indicates the number of elements the array can hold.

java
String[] cars = {"Volvo", "BMW", "Ford"};
System.out.println("Array length is: " + cars.length); // Output: 3

Iterating Over Arrays

Iterating over arrays is a common operation, usually done using loops.

Using for Loop

java
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.length; i++) {
    System.out.println("Element " + i + ": " + numbers[i]);
}

Using Enhanced for Loop (For-Each)

This is a more concise and recommended way to iterate, and it's less error-prone.

java
String[] fruits = {"Apple", "Banana", "Orange"};
for (String fruit : fruits) {
    System.out.println(fruit);
}

Multi-dimensional Arrays

Java also supports multi-dimensional arrays, which are essentially "arrays of arrays". The most common is the two-dimensional array, which can be thought of as a table or matrix.

java
// Declare and initialize a 3x4 two-dimensional array
int[][] matrix = {
    {1, 2, 3, 4},
    {5, 6, 7, 8},
    {9, 10, 11, 12}
};

// Access the element at the second row, third column (index [1][2])
System.out.println(matrix[1][2]); // Output: 7

// Iterate over a two-dimensional array
for (int i = 0; i < matrix.length; i++) { // Iterate rows
    for (int j = 0; j < matrix[i].length; j++) { // Iterate columns
        System.out.print(matrix[i][j] + "\t");
    }
    System.out.println();
}

java.util.Arrays Utility Class

Java provides an Arrays utility class that contains many static methods for manipulating arrays.

  • Arrays.toString(array): Returns a string representation of the array contents, ideal for printing arrays.
  • Arrays.sort(array): Sorts the array in ascending order.
  • Arrays.fill(array, value): Fills all elements of the array with the specified value.
  • Arrays.equals(array1, array2): Compares whether the contents of two arrays are exactly equal.
  • Arrays.binarySearch(array, key): Performs a binary search on a sorted array.
java
import java.util.Arrays;

public class ArraysUtilExample {
    public static void main(String[] args) {
        int[] numbers = {5, 2, 8, 1, 9};

        // Print array
        System.out.println("Original array: " + Arrays.toString(numbers));

        // Sort array
        Arrays.sort(numbers);
        System.out.println("Sorted array: " + Arrays.toString(numbers));

        // Search for element
        int index = Arrays.binarySearch(numbers, 8);
        System.out.println("Index of element 8 is: " + index);
    }
}

Content is for learning and research only.