Java Arrays: A Comprehensive Guide from Declaration to Operations

Chapter 6: Arrays in Java

6.1 Overview of Arrays

An array is a collection of elements of the same data type, stored in a contiguous memory location.

6.2 Creating and Using One-Dimensional Arrays

A one-dimensional array represents a linear sequence of elements of the same type.

Declaring a One-Dimensional Array

Array indices start at 0.

  • Declaration followed by memory allocation:

    • arrayElementType arrayName[];
    • arrayElementType[] arrayName;

    After declaration, memory must be allocated using the new operator, specifying the length of the array.

    arrayName = new arrayElementType[numberOfElements];
    
  • Declaration with immediate memory allocation:

    • arrayElementType arrayName[] = new arrayElementType[numberOfElements];
    • arrayElementType[] arrayName = new arrayElementType[numberOfElements];

Initializing a One-Dimensional Array

  • Default initialization: After memory allocation, all elements are set to their default value (e.g., 0 for numeric types).
  • Inline initialization during creation:
    int arr[] = new int[]{1, 2, 3, 4};
    
  • Shorthand initialization (omitting new):
    int arr[] = {1, 2, 3, 4};
    

Once defined, the length of an array cannot be changed.

Using a One-Dimensional Array

Arrays are typically traversed using loops.

public class ArrayExample1 {
    public static void main(String[] args) {
        // Declaration with memory allocation
        int arr[];
        int[] arr1;
        arr = new int[3];
        arr1 = new int[4];

        // Declaration and allocation in one step
        int arr2[] = new int[5];

        // Initialization
        int[] arr3 = new int[6];
        System.out.println(arr3[0]); // prints 0

        int arr4[] = {1, 2, 3, 4};

        // Traversal using for loop
        for (int i = 0; i < arr4.length; i++) {
            System.out.println(arr4[i]);
        }

        // Traversal using enhanced for loop (for-each)
        for (int i : arr4) {
            System.out.println(i);
        }
    }
}

6.3 Creating and Using Two-Dimensional Arrays

Declaring a Two-Dimensional Array

  • Declaration followed by memory allocation:

    • arrayElementType arrayName[][];
    • arrayElementType[][] arrayName;

    Memory for the higher dimension can be allocated in two ways:

    • Direct allocation for each dimension: a = new int[2][4];
    • Separate allocation per dimension:
      a = new int[2][];
      a[0] = new int[2];
      a[1] = new int[3];
      
  • Declaration with immediate memory allocation: Similar syntax to one-dimensional arrays but with two bracket pairs.

Initializing a Two-Dimensional Array

int arr[][] = {{1, 2, 3}, {4, 5, 6}};

Using a Two-Dimensional Array

public class ArrayExample2 {
    public static void main(String[] args) {
        int arr[][] = {{1, 2, 3}, {4, 5}};
        
        // Using standard for loop
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                System.out.println(arr[i][j]);
            }
        }

        // Using enhanced for loop
        for (int[] row : arr) {
            for (int value : row) {
                System.out.println(value);
            }
        }
    }
}

6.4 Basic Operations on Arrays

These operations require the java.util.Arrays class.

import java.util.Arrays;

Traversing an Array

As shown earlier, two common methods are:

  • Standard for loop
  • Enhanced for loop (for-each)

Filling and Replacing Array Elements

  • Arrays.fill(int[] a, int value): Fills the entire array a with the specified value.

  • Arrays.fill(int[] a, int fromIndex, int toIndex, int value): Fills elements from index fromIndex (inclusive) to toIndex (exclusive) with the given value.

Sorting an Array

Arrays.sort() sorts the array in ascending order. For String arrays, it sorts lexicographically.

Copying an Array

  • Arrays.copyOf(arr, int newLength): Copies the array, truncating or padding with default values if necessary.

  • Arrays.copyOfRange(arr, int fromIndex, int toIndex): Copies a range of the array from fromIndex to toIndex.

Searching in an Array

Arrays.binarySearch() uses a binary search algorithm. The array must be sorted before using this method.

  • Arrays.binarySearch(Object[] a, Object key): Searches for key in array a and returns its index. If not found, returns a negative value.

  • Arrays.binarySearch(Object[] a, int fromIndex, int toIndex, Object key): Searches within a specified range.

Example Demonstrating Basic Array Operations

import java.util.Arrays;

public class ArrayOperationsExample {
    public static void main(String[] args) {
        // Fill and replace elements
        int arr[] = {1, 2, 3, 4, 5};
        Arrays.fill(arr, 5);
        for (int i : arr) {
            System.out.print(i);
        }
        System.out.println();

        Arrays.fill(arr, 2, 3, 1); // index 2 inclusive, index 3 exclusive
        for (int i : arr) {
            System.out.print(i);
        }
        System.out.println();

        // Sort the array
        Arrays.sort(arr);
        for (int i : arr) {
            System.out.print(i);
        }
        System.out.println();

        // Copy array with length extension
        int newArr[] = Arrays.copyOf(arr, 10);
        for (int i : newArr) {
            System.out.print(i);
        }
        System.out.println();

        // Copy a range of the array
        int newArr1[] = Arrays.copyOfRange(arr, 0, 3);
        for (int i : newArr1) {
            System.out.print(i);
        }
        System.out.println();

        // Search for an element (binary search requires sorted array)
        System.out.println("Index of 1: " + Arrays.binarySearch(arr, 1));
        System.out.println("Index of 5: " + Arrays.binarySearch(arr, 5));
    }
}

Note: The binarySearch method returns the index of the first found occurrence, which may vary if duplicates exist.

Tags: java Arrays programming Tutorial

Posted on Sun, 04 Oct 2026 16:48:34 +0000 by sl1m