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.
Try It: Array Basics
Create, access, and loop through arrays
// 💡 Try modifying this code and see what happens!
// Array Basics — Java logic simulated in JavaScript
console.log("=== Array Basics ===\n");
// 1️⃣ Create and access
let scores = [85, 92, 78, 95, 88];
console.log("1. ARRAY ACCESS:");
console.log(" scores = [" + scores.join(", ") + "]");
console.log(" Length: " + scores.length);
console.log(" First (index 0): " + scores[0]);
console.log(" Third (index 2): " + scores[2]);
console.log(" Last: " + scores[scores.length - 1]);
// 2️⃣ Mo
...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.
Try It: Array Operations
Sum, average, max, min, sort, and search arrays
// 💡 Try modifying this code and see what happens!
// Array Operations — Java logic simulated in JavaScript
console.log("=== Array Operations ===\n");
let scores = [85, 92, 78, 95, 88, 72, 91, 65, 83, 97];
console.log("Scores: [" + scores.join(", ") + "]\n");
// 1️⃣ Sum and Average
let sum = 0;
for (let s of scores) sum += s;
let avg = sum / scores.length;
console.log("1. SUM & AVERAGE:");
console.log(" Sum: " + sum);
console.log(" Average: " + avg.toFixed(1));
// 2️⃣ Max and Min
let max
...6️⃣ 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).
Try It: 2D Arrays & Real-World Problems
Build a multiplication table, seating chart, and tic-tac-toe board
// 💡 Try modifying this code and see what happens!
// 2D Arrays — Java logic simulated in JavaScript
console.log("=== 2D Arrays & Real-World Problems ===\n");
// 1️⃣ Multiplication table
console.log("1. MULTIPLICATION TABLE (5×5):");
let header = " × |";
for (let j = 1; j <= 5; j++) header += " " + j;
console.log(" " + header);
console.log(" " + "—".repeat(20));
for (let i = 1; i <= 5; i++) {
let row = " " + i + " |";
for (let j = 1; j <= 5; j++) {
let val = i * j;
row += (v
...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.