Java Accessing Array Elements

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.
  • 85 is at index 0; the last value 88 is 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 slot
System.out.println(marks[2]); // third slot
System.out.println(marks[4]); // fifth slot
  • marks[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

85
78
88

A 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 into first.
  • The next line adds two slots together.
  • Once read, slots behave like ordinary int values.

Output

First score: 85
Sum 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 slot
marks[2] = 80; // change the third slot
System.out.println(marks[0]);
System.out.println(marks[2]);
  • marks[0] = 100 throws 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

100
80

You 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] + 5 reads 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 slots

The answer is 5, because there are five values.

Output

5

The 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.length is 5, so marks.length - 1 is 4, and marks[4] is 88.
  • The formula still works if you add or remove items later.
  • You never hard-code the number 4.

Output

Last score: 88

Memorize 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

92

The 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 end

marks.length - 2 is 5 - 2, which is 3, so this reads marks[3], the value 92.

Output

92

This 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 - 1 instead of a hard number keeps the code working if the array grows or shrinks.

Output

First: 85
Last: 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 end
System.out.println(marks[marks.length - 1]); // โœ… last valid index

Using .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() method
System.out.println(marks.length); // โœ… field, no brackets

Expecting 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 index
System.out.println(marks[marks.length - 1]); // โœ… this is the real last item

Reading 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, 2
System.out.println(data[3]); // โŒ crashes: only 0 to 2 exist
System.out.println(data[2]); // โœ… valid, prints the default 0

The 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 and array[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.length with no brackets. Save length() for String.
  • Be extra careful when the index is a variable. Make sure it stays inside 0 and length - 1.
  • When in doubt, print array.length first 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 with array[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 - 1 throws ArrayIndexOutOfBoundsException, and negative indexes never wrap around.

Check Your Knowledge

Test what you learned. Pick an answer for each question, then click Check.

  1. 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. 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. 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. 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.

Java Traversing Arrays

Share & Connect