What is an Array?

An array is a collection of elements of the same data type stored in contiguous memory locations. Think of it as a row of boxes, where each box can hold a value. Arrays are one of the most fundamental data structures in programming and are essential for storing and managing multiple values efficiently.

📊

Why Use Arrays?

  • Store multiple values in a single variable
  • Access elements quickly using index numbers
  • Organize related data together
  • Efficient memory usage
🔑

Key Characteristics

  • Fixed Size: Once created, size cannot change
  • Same Type: All elements must be the same data type
  • Zero-Indexed: First element is at index 0
  • Contiguous: Elements stored in adjacent memory

Understanding Index Numbers

An index is a number that represents the position of an element in an array. In Java, array indexing starts at 0, which means the first element is at index 0, the second at index 1, and so on.

Visual Representation of Array Indexing

Example: int[] numbers = {10, 20, 30, 40, 50};

10
Index 0
20
Index 1
30
Index 2
40
Index 3
50
Index 4

⚠️ Important Index Rules

  • First index is always 0
  • Last index is always array.length - 1
  • Accessing an invalid index causes ArrayIndexOutOfBoundsException

1D Arrays (One-Dimensional Arrays)

A one-dimensional array is like a single row of elements. It's the simplest form of an array and is used to store a list of values.

Creating a 1D Array

There are three main ways to create a 1D array in Java:

Method 1: Declare and Initialize Separately

// Declare an array of 5 integers
int[] numbers = new int[5];

// Initialize elements one by one
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

Method 2: Declare and Initialize Together

// Create and initialize in one line
int[] numbers = {10, 20, 30, 40, 50};

// Or with the 'new' keyword
int[] numbers = new int[]{10, 20, 30, 40, 50};

Method 3: Different Data Types

// String array
String[] names = {"Alice", "Bob", "Charlie"};

// Double array
double[] prices = {19.99, 29.99, 39.99};

// Boolean array
boolean[] flags = new boolean[3]; // All false by default

Accessing and Modifying Elements

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

// Access elements using index
System.out.println(numbers[0]);  // Output: 10
System.out.println(numbers[2]);  // Output: 30

// Modify elements
numbers[1] = 25;  // Change 20 to 25
System.out.println(numbers[1]);  // Output: 25

// Get array length
System.out.println("Array length: " + numbers.length);  // Output: 5

Traversing a 1D Array

Use loops to process all elements in an array:

Using a for loop

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

// Print all elements
for (int i = 0; i < numbers.length; i++) {
    System.out.println("Element at index " + i + ": " + numbers[i]);
}

Using an enhanced for loop (for-each)

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

// Print all elements (simpler syntax)
for (int num : numbers) {
    System.out.println(num);
}

2D Arrays (Two-Dimensional Arrays)

A two-dimensional array is like a table with rows and columns. It's essentially an "array of arrays" and is perfect for representing matrices, grids, or tabular data.

Visual Representation of 2D Array

Example: int[][] matrix = new int[3][4]; (3 rows, 4 columns)

[0][0]
[0][1]
[0][2]
[0][3]
[1][0]
[1][1]
[1][2]
[1][3]
[2][0]
[2][1]
[2][2]
[2][3]

Row 0, 1, 2 (first index)

Column 0, 1, 2, 3 (second index)

Creating a 2D Array

Method 1: Declare with Size

// Create a 3x4 array (3 rows, 4 columns)
int[][] matrix = new int[3][4];

// Initialize elements
matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[1][0] = 5;
// ... and so on

Method 2: Declare and Initialize Together

// Create and initialize in one step
int[][] matrix = {
    {1, 2, 3, 4},
    {5, 6, 7, 8},
    {9, 10, 11, 12}
};

// String 2D array example
String[][] students = {
    {"Alice", "A+"},
    {"Bob", "B"},
    {"Charlie", "A"}
};

Accessing 2D Array Elements

int[][] matrix = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

// Access elements using [row][column]
System.out.println(matrix[0][0]);  // Output: 1 (first row, first column)
System.out.println(matrix[1][2]);  // Output: 6 (second row, third column)
System.out.println(matrix[2][1]);  // Output: 8 (third row, second column)

// Modify elements
matrix[1][1] = 50;  // Change 5 to 50

// Get dimensions
System.out.println("Rows: " + matrix.length);        // Output: 3
System.out.println("Columns: " + matrix[0].length);  // Output: 3

Traversing a 2D Array

Use nested loops to process all elements:

Using nested for loops

int[][] matrix = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

// Print all elements row by row
for (int i = 0; i < matrix.length; i++) {
    for (int j = 0; j < matrix[i].length; j++) {
        System.out.print(matrix[i][j] + " ");
    }
    System.out.println();  // New line after each row
}

// Output:
// 1 2 3
// 4 5 6
// 7 8 9

Using enhanced for loops

int[][] matrix = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

// Print all elements
for (int[] row : matrix) {
    for (int element : row) {
        System.out.print(element + " ");
    }
    System.out.println();
}

Common Array Operations

Let's explore some common operations you'll perform with arrays, including storing elements, searching, and finding maximum/minimum values.

1. Storing Elements (Input from User)

import java.util.Scanner;

public class ArrayInput {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        // Create array
        int[] numbers = new int[5];
        
        // Store elements from user input
        System.out.println("Enter 5 numbers:");
        for (int i = 0; i < numbers.length; i++) {
            System.out.print("Enter number " + (i + 1) + ": ");
            numbers[i] = sc.nextInt();
        }
        
        // Display the array
        System.out.println("\nYou entered:");
        for (int num : numbers) {
            System.out.print(num + " ");
        }
    }
}

2. Searching for an Element (Linear Search)

public class ArraySearch {
    public static void main(String[] args) {
        int[] numbers = {10, 25, 30, 45, 50};
        int searchValue = 30;
        int foundIndex = -1;
        
        // Search for the element
        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] == searchValue) {
                foundIndex = i;
                break;  // Stop searching once found
            }
        }
        
        // Display result
        if (foundIndex != -1) {
            System.out.println(searchValue + " found at index " + foundIndex);
        } else {
            System.out.println(searchValue + " not found in array");
        }
    }
}

3. Finding Maximum and Minimum

public class ArrayMinMax {
    public static void main(String[] args) {
        int[] numbers = {45, 12, 78, 23, 91, 34};
        
        // Initialize with first element
        int max = numbers[0];
        int min = numbers[0];
        
        // Find max and min
        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] > max) {
                max = numbers[i];
            }
            if (numbers[i] < min) {
                min = numbers[i];
            }
        }
        
        System.out.println("Maximum value: " + max);  // Output: 91
        System.out.println("Minimum value: " + min);  // Output: 12
    }
}

4. Calculating Sum and Average

public class ArraySumAverage {
    public static void main(String[] args) {
        int[] marks = {85, 90, 78, 92, 88};
        int sum = 0;
        
        // Calculate sum
        for (int mark : marks) {
            sum += mark;
        }
        
        // Calculate average
        double average = (double) sum / marks.length;
        
        System.out.println("Total marks: " + sum);        // Output: 433
        System.out.println("Average: " + average);        // Output: 86.6
    }
}

5. Copying an Array

public class ArrayCopy {
    public static void main(String[] args) {
        int[] original = {1, 2, 3, 4, 5};
        
        // Method 1: Manual copy
        int[] copy1 = new int[original.length];
        for (int i = 0; i < original.length; i++) {
            copy1[i] = original[i];
        }
        
        // Method 2: Using System.arraycopy()
        int[] copy2 = new int[original.length];
        System.arraycopy(original, 0, copy2, 0, original.length);
        
        // Method 3: Using clone()
        int[] copy3 = original.clone();
        
        // All three methods create independent copies
    }
}

6. Reversing an Array

public class ArrayReverse {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        
        // Reverse the array in place
        int start = 0;
        int end = numbers.length - 1;
        
        while (start < end) {
            // Swap elements
            int temp = numbers[start];
            numbers[start] = numbers[end];
            numbers[end] = temp;
            
            start++;
            end--;
        }
        
        // Display reversed array
        for (int num : numbers) {
            System.out.print(num + " ");  // Output: 5 4 3 2 1
        }
    }
}

Key Points to Remember

  • Arrays have a fixed size that cannot be changed after creation.
  • Array indexing starts at 0 and ends at length - 1.
  • All elements in an array must be of the same data type.
  • Use array.length to get the size of a 1D array.
  • For 2D arrays, array.length gives rows, array[0].length gives columns.
  • Use for loops to traverse arrays; nested loops for 2D arrays.
  • Default values: 0 for numbers, false for boolean, null for objects.
  • Always check array bounds to avoid ArrayIndexOutOfBoundsException.