Lesson 7 • Intermediate
Java Arrays
So far, each variable holds one value. But what if you need to store 100 student scores, 365 daily temperatures, or 1,000 product prices? You can't create 1,000 separate variables! Arrays solve this — they let you store multiple values of the same type in a single variable.
What You'll Learn
- ✅ What arrays are and when to use them
- ✅ Two ways to create arrays — with values or with a size
- ✅ Accessing elements with 0-based indexing
- ✅ Looping through arrays with for, for-each, and while
- ✅ Common operations: sum, average, max, min, search, reverse
- ✅ 2D arrays — tables, grids, and matrices
- ✅ The
Arraysutility class — sort, copy, fill, toString - ✅ Arrays vs ArrayList — when to use each
💡 Real-World Analogy
Think of an array as a row of numbered mailboxes in an apartment building. Each mailbox (index) holds exactly one item. You access mailbox #3 directly — you don't need to check mailboxes 0, 1, and 2 first. The building has a fixed number of mailboxes decided at construction — you can't add more later.
1️⃣ Creating Arrays — Two Approaches
There are two main ways to create an array. Use the first when you already know the values. Use the second when you know the size but will fill it later.
// Approach 1: Declare with known values
int[] scores = {85, 92, 78, 95, 88};
String[] days = {"Mon", "Tue", "Wed", "Thu", "Fri"};
// Approach 2: Declare with size (values default to 0, null, or false)
int[] temperatures = new int[7]; // 7 slots, all start at 0
String[] names = new String[100]; // 100 slots, all start at null
boolean[] flags = new boolean[5]; // 5 slots, all start at false🔑 Key point: Once created, the array size is fixed forever. You cannot add or remove slots. If you need a resizable collection, use ArrayList (you'll learn this in the Collections lesson).
2️⃣ Accessing Elements — 0-Based Indexing
Every element in an array has an index (position number). Java uses 0-based indexing, which means the first element is at index 0, not 1. This trips up almost every beginner, so let's be clear:
int[] scores = {85, 92, 78, 95, 88};
// [0] [1] [2] [3] [4] ← indices
scores[0] // 85 (first element)
scores[2] // 78 (third element)
scores[4] // 88 (last element)
scores.length // 5 (number of elements — NOT an index!)
scores[scores.length - 1] // 88 (last element — ALWAYS use this pattern)
// Modify an element
scores[2] = 82; // Change 78 to 82
// ❌ CRASH: ArrayIndexOutOfBoundsException!
scores[5] // Index 5 doesn't exist in a 5-element array!
scores[-1] // Negative indices don't work in Java⚠️ The most common array error: ArrayIndexOutOfBoundsException. This happens when you try to access an index that doesn't exist. Remember: a 5-element array has indices 0 through 4, NOT 1 through 5.
3️⃣ Looping Through Arrays
The real power of arrays comes from processing every element with a loop. There are two main approaches:
Standard For — when you need the index
for (int i = 0; i < scores.length; i++) {
System.out.println("Student " + i +
": " + scores[i]);
}
// Use i < scores.length, NOT <=For-Each — cleanest for reading
for (int score : scores) {
System.out.println("Score: " + score);
}
// No index variable needed
// Can't modify the array with this💡 Which to use? Use for-each when you just need to read every element. Use the standard for when you need the index (e.g., "item 3 of 10") or need to modify elements.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// 1. Create and access
int[] scores = {85, 92, 78, 95, 88};
System.out.println("1. ARRAY ACCESS:");
System.out.println(" scores = " + Arrays.toString(scores));
System.out.println(" Length: " + scores.length);
System.out.println(" First (index 0): " + scores[0]);
System.out.println(" Third (index 2): " + scores[2]);
System.out.println(" Last: " + scores[scores.length - 1]);
// 2. Modify an element
scores[2] = 82;
System.out.println("\n2. MODIFY:");
System.out.println(" Changed index 2 from 78 to 82");
System.out.println(" scores = " + Arrays.toString(scores));
// 3. Standard for loop (with index)
System.out.println("\n3. FOR LOOP (with index):");
for (int i = 0; i < scores.length; i++) {
System.out.println(" Student " + i + ": " + scores[i]);
}
// 4. For-each loop
System.out.println("\n4. FOR-EACH LOOP:");
for (int score : scores) {
String grade = score >= 90 ? "A" : score >= 80 ? "B" : "C";
System.out.println(" Score: " + score + " (" + grade + ")");
}
// 5. Default values: a new int[] is filled with zeros
int[] empty = new int[5];
System.out.println("\n5. DEFAULT VALUES:");
System.out.println(" new int[5] defaults to: " + Arrays.toString(empty));
}
}1. ARRAY ACCESS:
scores = [85, 92, 78, 95, 88]
Length: 5
First (index 0): 85
Third (index 2): 78
Last: 88
2. MODIFY:
Changed index 2 from 78 to 82
scores = [85, 92, 82, 95, 88]
3. FOR LOOP (with index):
Student 0: 85
Student 1: 92
Student 2: 82
Student 3: 95
Student 4: 88
4. FOR-EACH LOOP:
Score: 85 (B)
Score: 92 (A)
Score: 82 (B)
Score: 95 (A)
Score: 88 (B)
5. DEFAULT VALUES:
new int[5] defaults to: [0, 0, 0, 0, 0]4️⃣ Common Array Operations
These operations come up constantly in real programming. Master these patterns and you'll solve 80% of array problems:
int[] scores = {85, 92, 78, 95, 88};
// Sum all elements
int sum = 0;
for (int score : scores) sum += score;
System.out.println("Sum: " + sum); // 438
// Calculate average (cast to double for decimal result!)
double average = (double) sum / scores.length;
System.out.println("Average: " + average); // 87.6
// Find maximum and minimum
int max = scores[0];
int min = scores[0];
for (int score : scores) {
if (score > max) max = score;
if (score < min) min = score;
}
System.out.println("Max: " + max); // 95
System.out.println("Min: " + min); // 78
// Linear search — find a value
int target = 92;
int foundAt = -1; // -1 means "not found"
for (int i = 0; i < scores.length; i++) {
if (scores[i] == target) {
foundAt = i;
break;
}
}
System.out.println("Found " + target + " at index " + foundAt);5️⃣ The Arrays Utility Class
Java provides java.util.Arrays with ready-made methods for common array tasks. Always use these instead of writing your own:
import java.util.Arrays;
int[] data = {42, 17, 93, 8, 55};
// Sort (ascending, in-place — modifies original!)
Arrays.sort(data);
// data is now {8, 17, 42, 55, 93}
// Print readable representation
System.out.println(Arrays.toString(data));
// → "[8, 17, 42, 55, 93]"
// Copy an array
int[] copy = Arrays.copyOf(data, data.length); // full copy
int[] first3 = Arrays.copyOf(data, 3); // first 3 elements
// Fill all elements with a value
int[] zeros = new int[10];
Arrays.fill(zeros, -1); // all elements become -1
// Compare two arrays
boolean same = Arrays.equals(data, copy); // true (same content)
// Binary search (array MUST be sorted first!)
int index = Arrays.binarySearch(data, 42); // returns 2⚠️ Common trap: System.out.println(arr) prints a memory address like [I@1b6d3586, not the values! Always use Arrays.toString(arr) to print arrays.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] scores = {85, 92, 78, 95, 88, 72, 91, 65, 83, 97};
System.out.println("Scores: " + Arrays.toString(scores) + "\n");
// 1. Sum and average
int sum = 0;
for (int s : scores) sum += s;
double avg = (double) sum / scores.length;
System.out.println("1. SUM & AVERAGE:");
System.out.println(" Sum: " + sum);
System.out.printf(" Average: %.1f%n", avg);
// 2. Max and min (tracking the index of each)
int max = scores[0], min = scores[0], maxIdx = 0, minIdx = 0;
for (int i = 0; i < scores.length; i++) {
if (scores[i] > max) { max = scores[i]; maxIdx = i; }
if (scores[i] < min) { min = scores[i]; minIdx = i; }
}
System.out.println("\n2. MAX & MIN:");
System.out.println(" Max: " + max + " (index " + maxIdx + ")");
System.out.println(" Min: " + min + " (index " + minIdx + ")");
// 3. Linear search
System.out.println("\n3. LINEAR SEARCH:");
int target = 91, foundAt = -1;
for (int i = 0; i < scores.length; i++) {
if (scores[i] == target) { foundAt = i; break; }
}
System.out.println(" Search for " + target + ": " +
(foundAt >= 0 ? "Found at index " + foundAt : "Not found"));
// 4. Sort a copy (Arrays.sort is in-place, so copy first)
int[] sorted = Arrays.copyOf(scores, scores.length);
Arrays.sort(sorted);
System.out.println("\n4. SORTED:");
System.out.println(" " + Arrays.toString(sorted));
// 5. Grade distribution
System.out.println("\n5. PASSING (>=70):");
int passing = 0;
for (int s : scores) if (s >= 70) passing++;
System.out.println(" " + passing + " of " + scores.length + " passed");
}
}Scores: [85, 92, 78, 95, 88, 72, 91, 65, 83, 97]
1. SUM & AVERAGE:
Sum: 846
Average: 84.6
2. MAX & MIN:
Max: 97 (index 9)
Min: 65 (index 7)
3. LINEAR SEARCH:
Search for 91: Found at index 6
4. SORTED:
[65, 72, 78, 83, 85, 88, 91, 92, 95, 97]
5. PASSING (>=70):
9 of 10 passed6️⃣ 2D Arrays — Tables and Grids
A 2D array is an "array of arrays" — think of it as a table with rows and columns. Each element is accessed with two indices: [row][column]. They're used for game boards, spreadsheets, images, and mathematical matrices.
// Create a 3×4 matrix
int[][] matrix = {
{1, 2, 3, 4}, // row 0
{5, 6, 7, 8}, // row 1
{9, 10, 11, 12} // row 2
};
// Access: matrix[row][column]
matrix[0][0] // 1 (top-left)
matrix[1][2] // 7 (row 1, column 2)
matrix[2][3] // 12 (bottom-right)
// Dimensions
matrix.length // 3 (number of rows)
matrix[0].length // 4 (number of columns)
// Iterate 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] + "\t");
}
System.out.println();
}7️⃣ Arrays vs ArrayList
A common question: when should you use an array vs an ArrayList? Here's the decision guide:
| Feature | Array | ArrayList |
|---|---|---|
| Size | Fixed — can't change | Dynamic — grows/shrinks |
| Speed | Slightly faster | Slightly slower |
| Primitives | ✅ int, double, etc. | ❌ Objects only (Integer) |
| Add/Remove | ❌ Can't | ✅ .add(), .remove() |
| Best for | Known-size data | Growing collections |
Rule of thumb: Use arrays when the size is known and won't change (days of week, game board). Use ArrayList when you need to add/remove items (shopping cart, to-do list).
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// 1. Multiplication table (5x5)
System.out.println("1. MULTIPLICATION TABLE (5x5):");
for (int i = 1; i <= 5; i++) {
StringBuilder row = new StringBuilder();
for (int j = 1; j <= 5; j++) {
row.append(String.format("%4d", i * j));
}
System.out.println(" " + row);
}
// 2. Seating chart (2D String array)
System.out.println("\n2. SEATING CHART:");
String[][] seats = {
{"Alice", "Bob", "Carol"},
{"Dave", "Eve", "Frank"},
{"Grace", "Henry", "Iris"}
};
for (int row = 0; row < seats.length; row++) {
StringBuilder rowStr = new StringBuilder(" Row " + (row + 1) + ": ");
for (int col = 0; col < seats[row].length; col++) {
rowStr.append(String.format("%-8s", seats[row][col]));
}
System.out.println(rowStr);
}
System.out.println(" seats[1][2] = " + seats[1][2] + " (Row 2, Seat 3)");
// 3. Matrix sum
System.out.println("\n3. MATRIX SUM:");
int[][] matA = {{1, 2}, {3, 4}};
int[][] matB = {{5, 6}, {7, 8}};
int[][] matSum = new int[matA.length][matA[0].length];
for (int i = 0; i < matA.length; i++) {
for (int j = 0; j < matA[i].length; j++) {
matSum[i][j] = matA[i][j] + matB[i][j];
}
}
System.out.println(" A+B = " + Arrays.deepToString(matSum));
// 4. Search a 2D array
System.out.println("\n4. SEARCH 2D ARRAY:");
int[][] grid = {{10, 20, 30}, {40, 50, 60}, {70, 80, 90}};
int searchFor = 50;
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[r].length; c++) {
if (grid[r][c] == searchFor) {
System.out.println(" Found " + searchFor + " at [" + r + "][" + c + "]");
}
}
}
}
}1. MULTIPLICATION TABLE (5x5):
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
2. SEATING CHART:
Row 1: Alice Bob Carol
Row 2: Dave Eve Frank
Row 3: Grace Henry Iris
seats[1][2] = Frank (Row 2, Seat 3)
3. MATRIX SUM:
A+B = [[6, 8], [10, 12]]
4. SEARCH 2D ARRAY:
Found 50 at [1][1]Common Mistakes
- ❌ ArrayIndexOutOfBoundsException:
int[] arr = new int[5]; arr[5] = 10; // ❌ Index 5 doesn't exist! Valid: 0-4 arr[arr.length] = 10; // ❌ Same bug — use arr.length - 1
- ❌ Printing array with println:
System.out.println(arr); // ❌ Prints "[I@1b6d3586" System.out.println(Arrays.toString(arr)); // ✅ Prints "[1, 2, 3]"
- ❌ Comparing arrays with ==: This checks if they're the same object, not the same content. Use
Arrays.equals(a, b). - ❌ Forgetting arrays are fixed-size: You can't call
add()orremove()on arrays — use ArrayList for that. - ❌ Using
<=in the loop condition:for (int i = 0; i <= arr.length; i++)will crash on the last iteration. Use<.
Pro Tips
💡 Default values: int[] defaults to 0, boolean[] to false, double[] to 0.0, String[] to null.
💡 Use .length not .length(): Arrays use a property (arr.length), strings use a method (str.length()). Don't mix them up!
💡 Prefer for-each for reading: It's cleaner and prevents off-by-one errors. Only use standard for when you need the index.
💡 Always initialize before use: Accessing an uninitialized object array element gives null, which will cause NullPointerException if you call methods on it.
📋 Quick Reference
| Operation | Syntax | Notes |
|---|---|---|
| Create (values) | int[] a = {1,2,3} | Size inferred |
| Create (size) | int[] a = new int[5] | Defaults to 0 |
| Access | a[index] | 0-based |
| Length | a.length | Property (no parentheses) |
| Sort | Arrays.sort(a) | In-place, ascending |
| Arrays.toString(a) | "[1, 2, 3]" | |
| Copy | Arrays.copyOf(a, len) | Returns new array |
| Compare | Arrays.equals(a, b) | Content comparison |
🎉 Lesson Complete!
You can now create, access, iterate, and manipulate arrays! You understand 0-based indexing, common operations like sum/max/min/search, 2D arrays for grids, and the Arrays utility class.
Next up: Strings — master text manipulation with Java's powerful String methods, formatting, and the critical difference between == and .equals().
Sign up for free to track which lessons you've completed and get learning reminders.