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.
Learn Arrays in our free Java course — a beginner-friendly interactive lesson with worked examples, a practice exercise and a quick reference.
Part of the free Java course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
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 Arrays utility 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.
🔑 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:
⚠️ 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-Each — cleanest for reading
💡 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.
4️⃣ Common Array Operations
These operations come up constantly in real programming. Master these patterns and you'll solve 80% of array problems:
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:
⚠️ Common trap: System.out.println(arr) prints a memory address like [I@1b6d3586 , not the values! Always use Arrays.toString(arr) to print arrays.
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.
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).
Common Mistakes
- ❌ ArrayIndexOutOfBoundsException:
- ❌ Printing array with println:
- ❌ 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() or remove() 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() .
Practice quiz
What is the index of the FIRST element in a Java array?
- 1
- -1
- 0
- It depends
Answer: 0. Java arrays use 0-based indexing, so the first element is at index 0.
For 'int[] scores = {85, 92, 78, 95, 88};', what is scores[2]?
- 78
- 92
- 95
- 85
Answer: 78. Index 2 is the third element, which is 78.
How do you get the number of elements in an array named arr?
- arr.length()
- arr.size()
- length(arr)
- arr.length
Answer: arr.length. Arrays use the .length property (no parentheses); Strings use .length() with parentheses.
Continue this course
- Previous: Previous Lesson
- Next: Next Lesson