Java Accessing Array Elements
Table of Contents + โ
In the last lesson you learned about Java creating arrays. Now you have an array full of values. To read or replace one, you point at its slot by number. That number is the index.
๐ข Zero-based indexing
Each slot has a number called its index. Counting starts at 0, not 1.
int[] marks = {85, 90, 78, 92, 88};// index: 0 1 2 3 4- First slot is index 0, second is index 1, and so on.
85is at index 0; the last value88is at index 4, not 5.- This is zero-based indexing, used by almost every language.
- Largest index is always one less than the count.
๐ Reading an element with arr[i]
Write the array name, then the index in square brackets. You get the value in that slot.
int[] marks = {85, 90, 78, 92, 88};
System.out.println(marks[0]); // first slotSystem.out.println(marks[2]); // third slotSystem.out.println(marks[4]); // fifth slotmarks[0]is 85, the value at index 0.marks[2]is 78;marks[4]is the last value 88.- The brackets mean โthe value at this slotโ.
Output
857888A read like marks[2] is just a value, so you can add it, compare it, store it, or print it like any plain number.
int[] marks = {85, 90, 78, 92, 88};
int first = marks[0];int total = marks[0] + marks[1];
System.out.println("First score: " + first);System.out.println("Sum of first two: " + total);marks[0]is copied intofirst.- The next line adds two slots together.
- Once read, slots behave like ordinary
intvalues.
Output
First score: 85Sum of first two: 175โ๏ธ Writing or updating an element
To update a slot, put arr[i] on the left of an = and the new value on the right.
int[] marks = {85, 90, 78, 92, 88};
marks[0] = 100; // change the first slotmarks[2] = 80; // change the third slot
System.out.println(marks[0]);System.out.println(marks[2]);marks[0] = 100throws away 85 and puts 100 in its place.marks[2]goes from 78 to 80.- Updating fully replaces the old value; there is no history. Whatever you write last is what stays.
Output
10080You can also build a new value from the old one. This adds 5 bonus marks to the first slot.
int[] marks = {85, 90, 78, 92, 88};
marks[0] = marks[0] + 5; // read it, add 5, write it back
System.out.println(marks[0]);- The right side runs first:
marks[0] + 5reads 85 and works out 90. - The
=then writes 90 back into the same slot.
Output
90๐ The length field and the last element
Get an arrayโs size with array.length. No brackets: it is a field the array carries, not a method.
int[] marks = {85, 90, 78, 92, 88};
System.out.println(marks.length); // how many slotsThe answer is 5, because there are five values.
Output
5The last index is one less than the size, so the last slot is always array.length - 1.
int[] marks = {85, 90, 78, 92, 88};
int last = marks[marks.length - 1]; // last slot
System.out.println("Last score: " + last);marks.lengthis 5, somarks.length - 1is 4, andmarks[4]is 88.- The formula still works if you add or remove items later.
- You never hard-code the number 4.
Output
Last score: 88Memorize the pair: first is always array[0], last is always array[array.length - 1].
length has no brackets
Arrays use array.length with no (). String uses text.length() with brackets. Arrays use a field; Strings use a method. Mixing them up is a common beginner error.
๐งฎ Using a variable or expression as the index
The index can be a fixed number, a variable, or a small calculation. Whatever is inside the brackets just has to work out to an int.
int[] marks = {85, 90, 78, 92, 88};
int i = 3;System.out.println(marks[i]); // same as marks[3]Java works out i (3), then reads marks[3], so the slot you read can change while the program runs.
Output
92The brackets can also hold math. This reads the slot just before the last one.
int[] marks = {85, 90, 78, 92, 88};
System.out.println(marks[marks.length - 2]); // second from the endmarks.length - 2 is 5 - 2, which is 3, so this reads marks[3], the value 92.
Output
92This is why loops and arrays fit together: a loop changes a counter, and you feed that counter into the brackets to walk through every slot. The next lesson covers that.
๐ฅ ArrayIndexOutOfBoundsException
Ask for an index that does not exist and Java stops the program with ArrayIndexOutOfBoundsException. This array has slots 0 to 4. Watch index 5.
public class Main { public static void main(String[] args) { int[] marks = {85, 90, 78, 92, 88};
System.out.println(marks[5]); // there is no slot 5 }}- The program does not skip the bad line; it crashes right there.
- The number 5 in the message is the index you asked for.
Output
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5 at Main.main(Main.java:5)A negative index breaks the same way. There is no slot -1, so Java refuses it too.
public class Main { public static void main(String[] args) { int[] marks = {85, 90, 78, 92, 88};
System.out.println(marks[-1]); // negative is never valid }}Some languages let -1 mean โthe last itemโ. Java does not; a negative index is always out of bounds.
Output
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 5 at Main.main(Main.java:5)A valid index must be 0 or more and less than array.length. Anything outside that range crashes, so check your math when the index comes from a variable or loop.
๐ฅ Getting the first and last safely
Here are the first and last items together, the safe way.
int[] marks = {85, 90, 78, 92, 88};
System.out.println("First: " + marks[0]);System.out.println("Last: " + marks[marks.length - 1]);- First is always index 0; last is always
length - 1. - Using
marks.length - 1instead of a hard number keeps the code working if the array grows or shrinks.
Output
First: 85Last: 88โ ๏ธ Common Mistakes
A few index slip-ups show up over and over.
Off-by-one on the last item. The last index is length - 1, not length. Using length itself goes one slot too far:
int[] marks = {85, 90, 78, 92, 88};System.out.println(marks[marks.length]); // โ crashes: length is one past the endSystem.out.println(marks[marks.length - 1]); // โ
last valid indexUsing .length() instead of .length on an array. Arrays have no length() method, so this will not even compile:
int[] marks = {85, 90, 78, 92, 88};System.out.println(marks.length()); // โ won't compile: arrays have no length() methodSystem.out.println(marks.length); // โ
field, no bracketsExpecting a negative index to wrap around. In Java, -1 does not mean โlastโ. It just crashes:
int[] marks = {85, 90, 78, 92, 88};System.out.println(marks[-1]); // โ crashes: negative indexSystem.out.println(marks[marks.length - 1]); // โ
this is the real last itemReading a slot you never set in a fresh new array is fine, but reading past the size is not. The size, not what you filled, decides the limit:
int[] data = new int[3]; // slots 0, 1, 2System.out.println(data[3]); // โ crashes: only 0 to 2 existSystem.out.println(data[2]); // โ
valid, prints the default 0The one-less rule
For an array of size n, the valid indexes are 0 to n - 1. The first item is array[0]. The last item is array[array.length - 1]. If you ever write array[array.length], stop, because that slot does not exist.
โ Best Practices
A few habits keep your element access clean and crash-free.
- Use
array[0]for the first item andarray[array.length - 1]for the last. Never hard-code the last index. - Remember indexes run from 0 to
length - 1. The largest valid index is one less than the size. - Write
array.lengthwith no brackets. Savelength()forString. - Be extra careful when the index is a variable. Make sure it stays inside 0 and
length - 1. - When in doubt, print
array.lengthfirst so you know the real range before you reach into a slot.
๐งฉ What Youโve Learned
Nice work. Letโs recap how to reach into an array.
- โ
Indexes start at 0, so the first slot is index 0 and the last is
length - 1. - โ
Read a value with
array[i], and use it like any normal value. - โ
Update a slot with
array[i] = x, which fully replaces the old value. - โ
Get the size with
array.length(a field, no brackets), and reach the last item witharray[array.length - 1]. - โ
The index can be a variable or a small calculation, as long as it works out to a valid
int. - โ
An index outside 0 to
length - 1throws ArrayIndexOutOfBoundsException, and negative indexes never wrap around.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
In int[] marks = {85, 90, 78, 92, 88}, what does marks[2] give you?
Why: Indexing starts at 0, so index 2 is the third value, 78.
- 2
How do you reach the last element of any array?
Why: The last valid index is length minus one, so array[array.length - 1].
- 3
What happens when you run System.out.println(marks[5]) on a 5-item array?
Why: A 5-item array has indexes 0 to 4, so index 5 is out of bounds and crashes.
- 4
Which line correctly gets the size of an int array?
Why: Arrays use the length field with no brackets. length() is for String.
๐ Whatโs Next?
You can now read and update any single slot by its index. But reaching for slots one at a time gets slow once an array has many items. The real power shows up when you walk through every element automatically with a loop. Next we learn to traverse arrays from the first slot to the last.