Java Introduction to Arrays
Table of Contents + −
In the last lesson you learned about Java pattern programs. So far each variable held one value. But real programs juggle many values at once, like 50 students’ marks. Java solves this with the array, one variable that holds many values.
🤔 Why do we need arrays?
To store five students’ marks today, you would make one variable each.
// One variable per student. It works, but it does not scale.int mark1 = 85;int mark2 = 90;int mark3 = 78;int mark4 = 92;int mark5 = 88;Separate variables cause real pain:
- They do not scale. Fifty students means fifty names. You cannot type
mark1,mark2forever. - You cannot loop. A loop needs one changing name like
mark[i]. - You cannot easily sum. You must type every name by hand.
- You cannot grow or shrink. A sixth student means adding
mark6everywhere.
An array stores all those marks under one name, reached by position. So you can loop, sum, and sort in a few lines.
📦 What is an array?
An array is a fixed-size, ordered, indexed collection of values that all share the same type. Pulling that apart:
- Collection means it holds many values, not one.
- Same type means every value is the same kind: all
int, or allString, or alldouble. - Ordered means the values keep their positions. The value you put first stays first.
- Indexed means each value has a number, called an index, that you use to reach it.
- Fixed-size means you choose how many slots it has when you create it, and that count never changes.
Picture an egg tray. The tray is the array, and each slot holds one egg. You grab an egg by the tray’s name plus a slot number like “slot 0” or “slot 3”. An array works the same way: one name for the whole row, plus a number for each spot.
🔢 How indexes work
Array positions start counting from zero, not one:
- The first item is at index 0, the second at index 1, and so on.
- An array of 5 items has indexes 0, 1, 2, 3, 4. The last index is always one less than the size.
- The index means “how far from the start”, so the first item sits 0 steps away.
Here is the picture for an array of five marks.
Index: 0 1 2 3 4 +-----+-----+-----+-----+-----+Value: | 85 | 90 | 78 | 92 | 88 | +-----+-----+-----+-----+-----+So marks[0] is 85, marks[2] is 78, and marks[4] is 88. There is no marks[5], because indexes only go up to 4. Using marks[5] would crash the program, an error we cover in Common Mistakes below.
Why start at 0?
Starting at 0 is a long tradition in programming, shared by Java, C, Python, JavaScript, and many more. The index measures distance from the start, so the first item is 0 steps away. It feels odd on day one, then it becomes second nature fast.
💡 A first look at an array
This program creates an array of five marks and prints the first one, the last one, and the count.
public class FirstArray { public static void main(String[] args) { // One variable holds all five marks. int[] marks = {85, 90, 78, 92, 88};
System.out.println("First mark: " + marks[0]); System.out.println("Last mark: " + marks[4]); System.out.println("Total students: " + marks.length); }}Line by line:
marksis one variable that holds all five values at once.marks[0]reaches the first value,marks[4]reaches the last.marks.lengthtells you how many items the array holds, which is 5 here.
Output
First mark: 85Last mark: 88Total students: 5📏 The length field
The length is a built-in field on every array that tells you how many slots it has:
- You write it as
arrayName.length, somarks.lengthgives 5. - It is a field, not a method, so no round brackets:
marks.length, nevermarks.length(). - It never changes, because the size is fixed.
Length lets you loop over an array without guessing its size. Here we print every mark.
public class PrintAll { public static void main(String[] args) { int[] marks = {85, 90, 78, 92, 88};
// i goes from 0 up to length - 1, so we touch every slot once. for (int i = 0; i < marks.length; i++) { System.out.println("Mark at index " + i + ": " + marks[i]); } }}The loop runs i from 0 while i is less than marks.length, so it stops right after index 4. We never hard-code 5, so the loop still works if the array changes.
Output
Mark at index 0: 85Mark at index 1: 90Mark at index 2: 78Mark at index 3: 92Mark at index 4: 88🫙 What an empty array holds by default
Create an array without giving it any values, and Java still fills every slot with a default value based on the type:
- A number array (
int,double) fills with 0 (or0.0for decimals). - A
booleanarray fills with false. - An object array (
String) fills with null, meaning “points to nothing yet”.
This program makes three arrays of size 3 without listing values, then prints what each slot holds.
public class Defaults { public static void main(String[] args) { int[] numbers = new int[3]; // three int slots boolean[] flags = new boolean[3]; // three boolean slots String[] names = new String[3]; // three String slots
System.out.println("int default: " + numbers[0]); System.out.println("boolean default: " + flags[0]); System.out.println("String default: " + names[0]); }}We never assigned to slot 0, yet each one already has a value: 0, false, and null. So a fresh Java array is never truly empty. It is full of starting values, waiting for you to overwrite them.
Output
int default: 0boolean default: falseString default: nullWhy this matters
Because slots start at 0, you can build a totals array and start adding to it right away, with no setup step. The zeros are already there, so the first += just works.
🧠 Arrays are reference types
In Java, an array is a reference type, which changes what your variable holds:
- With
int x = 5, the value 5 sits right insidex. - With an array, the row of values lives on the heap, the area where Java keeps objects.
- The variable holds a reference: an arrow (address) that points to the row on the heap.
- When you write
marks[2], Java follows the arrow to the row, then steps to slot 2.
This explains a result that confuses many people. Copy one array variable into another and you copy the arrow, not the row. So both point to the same row.
public class Reference { public static void main(String[] args) { int[] a = {1, 2, 3}; int[] b = a; // copies the arrow, not the values
b[0] = 99; // change through b
System.out.println("a[0] is " + a[0]); // a sees it too }}We changed b[0], but a[0] changed too. That is because a and b are two arrows pointing at one shared row, so a change through either name shows up through both. Keep this in mind; it explains plenty of bugs later.
Output
a[0] is 99🚧 The fixed-size limit
A 5-slot array stays 5 slots for its whole life. There is no “add one more” and no “make it bigger”. When a sixth student joins, your options are clumsy:
- Make a new, bigger array, then copy every old value across by hand. Slow and easy to get wrong.
- Or guess a big size up front, like 100 slots. That wastes memory and still breaks at 101.
This limit is exactly why Java gives you the ArrayList, which can grow and shrink as you add and remove items. So the array is the simple, fast base, and ArrayList is the flexible tool built on top. Learn the array first, because everything else stands on it.
🌍 Where arrays are used
Arrays show up everywhere once you start looking.
| Real-life thing | What the array holds |
|---|---|
| A class result sheet | The marks of every student |
| A music playlist | The list of songs in order |
| A shopping cart | The items you are about to buy |
| A week’s temperatures | The high temperature for each day |
Anytime you have a list of similar things, an array is the tool. It is one of the most used building blocks in programming. Even big apps like YouTube and Amazon lean on this idea to hold lists of videos and products in order.
⚠️ Common Mistakes
A few misunderstandings trip up nearly everyone at the start.
Off-by-one: thinking the last index equals the size. For 5 items the last index is 4, not 5. Valid indexes run 0 to length - 1, so a loop going “up to and including 5” walks one step too far.
int[] marks = {85, 90, 78, 92, 88};
// ❌ Wrong: <= length means i reaches 5, which does not existfor (int i = 0; i <= marks.length; i++) { System.out.println(marks[i]);}
// ✅ Right: < length stops at index 4, the real last slotfor (int i = 0; i < marks.length; i++) { System.out.println(marks[i]);}Going past the end and hitting ArrayIndexOutOfBoundsException. Ask for a slot that does not exist and Java stops the program with an error. The wrong loop above does this when i becomes 5.
Output
8590789288Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5The message says the bad index was 5 and the length was 5, so the largest legal index was 4. It points right at the fix.
Using .length() like a String. A String uses length() with brackets (a method). An array uses length with no brackets (a field). Mixing them up is a common slip.
int[] marks = {85, 90, 78, 92, 88};
// ❌ Wrong: arrays have no length() method, this will not compileint n = marks.length();
// ✅ Right: length on an array is a field, no bracketsint n = marks.length;Mixing types in one array. A Java array holds one type only. You cannot store an int and a String together. Pick one type and stay with it.
✅ Best Practices
- Use arrays for lists of the same kind of thing. Marks, names, prices, temperatures: same type, many values.
- Remember indexes start at 0. The last valid index is always
length - 1. - Loop with
< length, never<= length. This one habit stops most ArrayIndexOutOfBoundsException errors. - Use
.lengthto find the size. Never guess or hard-code a number, so your code stays right if the size changes. - Pick a plural name like
marks,names,prices, so readers see at a glance it holds many values. - Reach for
ArrayListwhen you need to grow. A plain array fights you if the size changes at run time.
🧩 What You’ve Learned
Nicely done. Here is the recap.
- ✅ An array stores many values of the same type under one name.
- ✅ An array is fixed-size, ordered, and indexed, and indexes start at 0.
- ✅ For an array of size N, the valid indexes are 0 to N − 1.
- ✅
array.lengthis a field (no brackets) that gives the item count. - ✅ A fresh array fills with defaults: 0 for numbers, false for booleans, null for objects.
- ✅ Arrays are reference types, so the variable holds an arrow to a row on the heap.
- ✅ The fixed size is the big limit, which is why
ArrayListexists for later.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
What is the main reason to use an array?
Why: An array lets you keep many related values together in one variable instead of many separate ones.
- 2
If an array has 5 items, what is the last valid index?
Why: Indexes run from 0 to length minus 1, so for 5 items the last index is 4.
- 3
What does a fresh int array of size 3 hold before you assign anything?
Why: Java fills a new int array with the default value 0 in every slot; booleans default to false and objects to null.
- 4
How do you correctly get the number of items in an array named marks?
Why: On an array, length is a field with no brackets, so it is marks.length. The length() method with brackets is for String.
🚀 What’s Next?
Now you know what an array is and why it helps. Next we cover creating arrays: the ways to declare them, set their size, and put values in.