📦 Arrays in Java

What is an Array?

An array is a fixed-size, ordered collection of elements of the same data type. Each element is accessed by its index, starting from 0

Declaration and Initialization

// Declaration
int[] numbers;
 
// Initialization
numbers = new int[5];
 
// Declaration and Initialization
int[] values = {10, 20, 30, 40, 50};

Accessing and Modifying Elements

System.out.println(values[2]); // Outputs 30
values[2] = 35;
System.out.println(values[2]); // Outputs 35

Iterating Through an Array

for (int i = 0; i < values.length; i++) {
    System.out.println(values[i]);
}

Multidimensional Arrays

Java supports multidimensional arrays, such as 2D arrays

int[][] matrix = {
    {1, 2},
    {3, 4}
};
System.out.println(matrix[1][0]); // Outputs 3

Visualising an Integer Array:

int[] arr = {10, 20, 30, 40, 50};
flowchart TD
    A0["Index: 0 Value: 10"]
    A1["Index: 1 Value: 20"]
    A2["Index: 2 Value: 30"]
    A3["Index: 3 Value: 40"]
    A4["Index: 4 Value: 50"]

    A0 --> A1 --> A2 --> A3 --> A4

Further Learning