Arrays: Storing Multiple Values
Imagine you are developing a grading system for a school classroom with 50 students. Without arrays, how would you store their exam marks?
int mark1 = 85;int mark2 = 92;int mark3 = 78;// ... do you really want to write 50 separate variables?!int mark50 = 88;Now imagine writing code to calculate the average mark: you would have to write int total = mark1 + mark2 + mark3 + ... + mark50;! What if your school has 10,000 students? Managing independent variables becomes completely impossible.
Java provides a fundamental, high-performance solution: The Array.
1. What Is an Array?
An Array is a container object that holds a fixed number of values of a single uniform data type in contiguous (unbroken) memory locations.
Everyday Analogy: The Row of Mailboxes 📬
Think of a row of physical metal mailboxes outside an apartment complex:
- All mailboxes are the exact same size.
- They are physically attached side-by-side in an unbroken line.
- Each mailbox is labeled with a specific number (an Index) starting from
0. - If you want the mail for box #3, you walk directly to position 3 without checking boxes 0, 1, or 2 first.
An Array of 5 Integers
┌──────────┬──────────┬──────────┬──────────┬──────────┐
│ 85 │ 92 │ 78 │ 90 │ 88 │
└──────────┴──────────┴──────────┴──────────┴──────────┘
Index 0 Index 1 Index 2 Index 3 Index 4
2. Declaring and Creating Arrays
There are two primary ways to create an array in Java:
Method A: Array Literal (When you already know the values)
If you already know the data values ahead of time:
int[] marks = {85, 92, 78, 90, 88};String[] days = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};Method B: Using new (When you only know the capacity)
If you don't know the values yet, but know how many slots you need:
int[] marks = new int[5]; // Creates 5 integer slotsHere, 5 is the capacity (length) of the array. Java immediately allocates memory on the Heap for exactly five integers.
3. The Sacred Rule: Zero-Based Indexing
In Java, array indices ALWAYS start at 0 and end at length - 1.
If an array has length = 5:
- First element:
marks[0] - Second element:
marks[1] - Third element:
marks[2] - Fourth element:
marks[3] - Last element:
marks[4](which islength - 1, i.e.5 - 1 = 4)
Accessing & Mutating Elements:
public class Main { public static void main(String[] args) { int[] scores = {90, 80, 70}; // Reading elements: System.out.println("First score: " + scores[0]); // 90 // Mutating (updating) an element: scores[1] = 95; // Overwrites 80 with 95 System.out.println("Updated score: " + scores[1]); // 95 }}4. Under the Hood: Memory Layout (Stack vs Heap)
How does Java physically store an array?
int[] numbers = new int[4]; STACK MEMORY HEAP MEMORY
(Holds the reference variable) (Contiguous block of 4 integers)
┌────────────────────────────┐ ┌──────────────────────────────────────┐
│ main() frame: │ │ Address: @0x500 │
│ │ │ ┌──────┬──────┬──────┬──────┐ │
│ numbers = @0x500 ──────────┼─────────────►│ │ 0 │ 0 │ 0 │ 0 │ │
│ │ │ └──────┴──────┴──────┴──────┘ │
│ │ │ [0] [1] [2] [3] │
└────────────────────────────┘ └──────────────────────────────────────┘
Why Contiguous Memory Matters ( Random Access) ⚡
Because array elements are stored side-by-side in uninterrupted memory blocks, the computer can calculate the exact memory address of any element instantly using pure arithmetic:
For an int array starting at address 1000 (where each int takes 4 bytes):
- Index 0
- Index 3
The computer jumps directly to index 3 without having to traverse through 0, 1, or 2! This is why reading array[i] is instantaneous ( time complexity).
5. Default Values in Newly Created Arrays
When you allocate an array using new Type[size], Java automatically fills every slot with a safe default value based on its type:
| Array Type | Declaration Example | Default Value in Every Slot |
|---|---|---|
int[], byte[], short[] | int[] arr = new int[3]; | 0[0, 0, 0] |
long[] | long[] arr = new long[3]; | 0L[0L, 0L, 0L] |
float[], double[] | double[] arr = new double[3]; | 0.0[0.0, 0.0, 0.0] |
boolean[] | boolean[] arr = new boolean[3]; | false[false, false, false] |
char[] | char[] arr = new char[3]; | '\u0000' (null character) |
Object Arrays (String[], Student[]) | String[] arr = new String[3]; | null[null, null, null] |
6. Iterating Through Arrays: Two Ways
To process every element in an array, we use loops.
Way 1: Traditional for Loop (Index-Based)
Use this when you need the index (e.g. to update elements or print positions):
int[] numbers = {10, 20, 30, 40};for (int i = 0; i < numbers.length; i++) { System.out.println("Element at index " + i + " is " + numbers[i]);}💡 Notice: We use
.length(a property, not a method! Do NOT write.length()).
Way 2: Enhanced for-each Loop (Read-Only Elegance)
Introduced in Java 5, the for-each loop lets you iterate through all elements cleanly without dealing with loop counters or boundary indices:
int[] numbers = {10, 20, 30, 40};// Read as: "For each integer 'num' in 'numbers':"for (int num : numbers) { System.out.println("Value: " + num);}When to use which?
- Use
for-eachwhen you just want to read, search, or sum elements (cleaner, zero risk of index errors). - Use traditional
forwhen you need to modify array values (arr[i] = val) or traverse backwards.
7. The #1 Array Pitfall: ArrayIndexOutOfBoundsException 💥
What happens if you try to access an index that does not exist?
int[] numbers = {10, 20, 30, 40}; // Length is 4. Valid indices: 0, 1, 2, 3// ❌ Common Beginner Off-by-One Mistake:System.out.println(numbers[4]);Console Crash:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
The Golden Rule:
For an array of length :
- The minimum index is always
0.- The maximum index is always
N - 1.- Attempting to access negative index
arr[-1]or indexarr[N]will immediately crash your program with anArrayIndexOutOfBoundsException.
8. Multi-Dimensional Arrays: 2D Grids & Matrices
Real-world data is often tabular (like a spreadsheet, chess board, or pixel display). Java supports 2D Arrays, which are conceptually arrays of arrays.
Creating a 2D Array:
// 3 rows, 3 columns (a 3x3 tic-tac-toe grid)int[][] matrix = { {1, 2, 3}, // Row 0 {4, 5, 6}, // Row 1 {7, 8, 9} // Row 2}; Col 0 Col 1 Col 2
Row 0 ───► [ 1 ] [ 2 ] [ 3 ]
Row 1 ───► [ 4 ] [ 5 ] [ 6 ]
Row 2 ───► [ 7 ] [ 8 ] [ 9 ]
Accessing 2D Elements (matrix[row][col]):
int val = matrix[1][2]; // Row 1, Column 2 -> 6Traversing a 2D Array with Nested Loops:
for (int row = 0; row < matrix.length; row++) { for (int col = 0; col < matrix[row].length; col++) { System.out.print(matrix[row][col] + " "); } System.out.println(); // Newline after each row}Output:
1 2 3
4 5 6
7 8 9
9. The Fixed-Size Limitation (Why We Need ArrayList)
Arrays are blindingly fast, but they have one massive architectural limitation:
Once an array is created on the Heap, its length can NEVER grow or shrink.
Imagine booking a private dining table for exactly 4 people:
- If a 5th friend arrives, you cannot stretch the table.
- You must physically reserve a brand-new table for 5, move everyone over, and abandon the old table!
In Java, if you have an int[4] and need to add a 5th number, you have to:
- Allocate
new int[8] - Manually copy all 4 elements over
- Point your variable to the new array
Doing this manually is tedious. That is why Java created ArrayList, a dynamic resizing collection that handles all memory growth for you automatically! We will explore ArrayList in the very next lesson.
10. Complete Hands-On Code Example
Let's write a program that finds the maximum value, computes the average, and prints grades:
// File: GradeAnalyzer.javapublic class Main { public static void main(String[] args) { int[] testScores = {78, 94, 88, 62, 99, 85}; int sum = 0; int maxScore = testScores[0]; // Assume first is highest // Using enhanced for-each to analyze scores for (int score : testScores) { sum += score; if (score > maxScore) { maxScore = score; } } double average = (double) sum / testScores.length; System.out.println("Total Students : " + testScores.length); System.out.println("Highest Score : " + maxScore); System.out.printf("Average Score : %.2f\n", average); System.out.println("\n--- Student Roster ---"); for (int i = 0; i < testScores.length; i++) { System.out.println("Student #" + (i + 1) + ": " + testScores[i]); } }}Output:
Total Students : 6
Highest Score : 99
Average Score : 84.33
--- Student Roster ---
Student #1: 78
Student #2: 94
Student #3: 88
Student #4: 62
Student #5: 99
Student #6: 85
11. Beginner Summary Checklist
- Arrays store multiple items of the same data type in contiguous memory.
- Indexing is strictly zero-based (
0tolength - 1). - Reading array elements is constant time because memory addresses are calculated directly with arithmetic.
- Array elements on the Heap receive default values (
0,0.0,false,null). for-eachloops provide clean, read-only iteration without index errors.- Accessing index
< 0or>= lengththrowsArrayIndexOutOfBoundsException. - Arrays have a fixed size; they cannot expand dynamically.