Array Basics

Arrays are a fundamental data structure in Java, allowing you to store and manage collections of elements of the same type efficiently. Here is a simple and comprehensive guide to everything you need to know about arrays in Java.


What is an Array?


Declaring and Initializing Arrays

Declaration Syntax:

int[] numbers;      // Preferred style
// or
int numbers[];      // Also valid

Initialization:

numbers = new int[5]; // Creates an array of size 5 with default values (0s)

Declaration + Initialization:

int[] numbers = new int[5]; // Array of 5 integers
String[] names = {"Alice", "Bob", "Charlie"}; // Direct initialization

Default Values:


Accessing and Modifying Array Elements

int x = numbers[0]; // Gets the first element
numbers[1] = 42;    // Sets the second element to 42

Array Length

int size = numbers.length;

Types of Arrays in Java

1. Single-Dimensional Arrays

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

2. Multi-Dimensional Arrays

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

3. Jagged Arrays

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

Looping Through Arrays

for (int i = 0; i < numbers.length; i++) {
    System.out.println(numbers[i]);
}
// Enhanced for loop
for (int num : numbers) {
    System.out.println(num);
}

Array Utility Methods

Java provides the java.util.Arrays class with many helpful methods:


Key Points and Limitations


Example: Complete Array Usage

int[] scores = new int[3];      // Declaration and memory allocation
scores[0] = 90;                 // Assign values
scores[1] = 85;
scores[2] = 78;
for (int i = 0; i < scores.length; i++) {
    System.out.println("Score " + i + ": " + scores[i]);
}