Syllabus / Java / Phase 2: Control Flow & Data (Days 6–10)
Beginner

Introduction to Arrays

📂 Phase 2: Control Flow & Data (Days 6–10) · Java

An array is a fixed-size container that holds multiple values of the same type in contiguous memory, accessed by a numeric index. Arrays replace the need to declare dozens of separate variables for related data.

Declaring and Initializing Arrays

// Declare and initialize together
int[] scores = {85, 90, 78, 92, 88};

// Declare with a fixed size, fill later
int[] marks = new int[5];
marks[0] = 70;
marks[1] = 80;

// String array
String[] names = {"Vishwas", "Rahul", "Priya"};

Accessing Elements — Zero-Based Indexing

Array indices always start at 0, not 1. For an array of length 5, valid indices are 0 through 4.

int[] scores = {85, 90, 78, 92, 88};
System.out.println(scores[0]);  // 85 — first element
System.out.println(scores[4]);  // 88 — last element
System.out.println(scores.length); // 5 — total number of elements
A very common runtime error: accessing scores[5] on a 5-element array throws ArrayIndexOutOfBoundsException — the last valid index is always length - 1.

Looping Through an Array

int[] scores = {85, 90, 78, 92, 88};

// Standard for loop (use when you need the index)
for (int i = 0; i < scores.length; i++) {
    System.out.println("Index " + i + ": " + scores[i]);
}

// For-each loop (use when you only need the values)
for (int score : scores) {
    System.out.println(score);
}

Common Array Operations

int[] arr = {4, 2, 9, 1, 7};

// Find the sum
int sum = 0;
for (int num : arr) {
    sum += num;
}

// Find the maximum
int max = arr[0];
for (int num : arr) {
    if (num > max) max = num;
}

Arrays Are Fixed-Size

Once created, an array's size cannot change. If you need a dynamically resizable collection, that's exactly what ArrayList (covered later in Collections) is built for — arrays are the foundation that ArrayList is built on top of internally.

Interview tip: Be ready to write "find largest/smallest element," "reverse an array," and "sum of array elements" from memory — these are the most frequently asked entry-level array questions.