Sub topic 3
Indexes, Length, and Bounds
An array is a fixed-size sequence of values in Java. Each value in the array is an element. To read or change an element, you need to know its position.
An index is the number Java uses for that position. Indexes start at 0, not 1. Knowing this helps you find the right value and avoid errors.
Counting positions from zero
Imagine an array named scores with three elements:
| Index | Element |
|---|---|
| `0` | `80` |
| `1` | `90` |
| `2` | `100` |
The first element is at index 0. The second is at index 1. The third is at index 2.
To access an element, write the array name followed by its index in square brackets. For example, scores[1] means the element at index 1, which is 90.
Read and update elements
This program reads and changes values in an array. Save it in a file named ScoresDemo.java.
public class ScoresDemo {
public static void main(String[] args) {
int[] scores = {80, 90, 100};
System.out.println("First: " + scores[0]);
System.out.println("Second: " + scores[1]);
scores[1] = 95;
System.out.println("Updated second: " + scores[1]);
System.out.println("Length: " + scores.length);
System.out.println("Last: " + scores[scores.length - 1]);
}
}The main method is where this program starts. The line beginning with int[] creates an array of whole numbers and names it scores.
To run the program, use these commands in the folder containing the file. The first command turns the Java code into a form Java can run.
javac ScoresDemo.java
java ScoresDemoThe output is:
First: 80
Second: 90
Updated second: 95
Length: 3
Last: 100The statement scores[1] = 95; replaces the value at index 1. It does not add a new element. After the update, the array contains 80, 95, and 100.
Find the length
An array’s length is its number of elements. Read it by writing the array name, a dot, and length:
scores.lengthFor the scores array, scores.length is 3. Java arrays have a fixed length: after an array is created, its length cannot change.
The length is a count, while an index is a position starting from zero. For a nonempty array:
- The first index is
0. - The last index is
length - 1. - The number
lengthitself is not a valid index.
That is why the program uses scores[scores.length - 1] to read the last element. For this array, scores.length - 1 is 2.
Understand bounds
The bounds of an array are the limits on which indexes you can use. An index is valid when it is at least 0 and less than the array’s length.
For the three-element scores array:
| Index | Valid? | Reason |
|---|---|---|
| `-1` | No | It is below `0`. |
| `0` | Yes | It is the first index. |
| `2` | Yes | It is the last index. |
| `3` | No | It equals the length, so it is past the last index. |
Java checks an index when the program tries to use it. This check applies when you read an element and when you update one.
What happens with an invalid index?
If an index is outside the bounds, Java throws an ArrayIndexOutOfBoundsException. An exception is a signal that something went wrong while a program was running.
The following program deliberately causes that error. Save it as BoundsDemo.java.
public class BoundsDemo {
public static void main(String[] args) {
int[] scores = {80, 90, 100};
System.out.println(scores[3]);
System.out.println("This line will not run.");
}
}Compile and run it:
javac BoundsDemo.java
java BoundsDemoYou will see an error message containing ArrayIndexOutOfBoundsException. The exact message may depend on your Java version. The second print statement does not run because the program stops at the invalid access.
The error can be easy to make: the array has three elements, but 3 is not one of its indexes. Change scores[3] to scores[2] to print the last element instead.
Check an index before using it
Sometimes an index comes from a variable, so you may not know its value in advance. A variable is a named place that holds a value.
Check both ends of the valid range before accessing the array. Save this program as SafeIndexes.java.
public class SafeIndexes {
public static void main(String[] args) {
int[] scores = {80, 90, 100};
int index = 3;
if (index >= 0 && index < scores.length) {
System.out.println("Score: " + scores[index]);
} else {
System.out.println("Index is outside the array.");
}
int[] empty = {};
if (empty.length > 0) {
System.out.println("Last: " + empty[empty.length - 1]);
} else {
System.out.println("The array has no last element.");
}
}
}Run it with:
javac SafeIndexes.java
java SafeIndexesThe output is:
Index is outside the array.
The array has no last element.The first if statement tests whether the index is safe. The symbol >= means “greater than or equal to,” and && means both conditions must be true. So this test requires the index to be at least 0 and less than scores.length.
Try changing index from 3 to 1. The program will print Score: 90. Try -1 as well; it is rejected because it is below zero.
Checking only index < scores.length is not enough. A negative index also passes that test. Similarly, checking index <= scores.length is wrong because an index equal to the length is outside the array.
Empty arrays have no valid indexes
An empty array has length 0. It has no first or last element, so even index 0 is invalid.
In SafeIndexes, the second if statement checks that empty.length is greater than 0 before trying to read the last element. This check matters because empty.length - 1 would be -1.
Use the same check whenever an array might be empty and you want its first or last element.
Use index expressions
An expression is a piece of code that produces a value. An index can be an expression rather than a number written directly.
For the original three-element scores array:
| Access | Index used | Value |
|---|---|---|
| `scores[0]` | `0` | `80` |
| `scores[1 + 1]` | `2` | `100` |
| `scores[scores.length - 1]` | `2` | `100` |
Java works out the index expression, then checks whether the result is in bounds. An expression can still produce an invalid index. For example, scores[scores.length] tries to use index 3 and causes an exception.
An index stored in an int variable works for array access, as shown by index in SafeIndexes. An int holds a whole number; a value with a decimal part cannot be used as an array index.
One more error: no array to access
A variable meant to refer to an array can contain null, which means it does not refer to an array. In that case, asking for its length or an element causes a NullPointerException, not an ArrayIndexOutOfBoundsException.
Before accessing an array that might be null, check that it is not null. For example, a check can start with scores != null before checking its length. The && operator checks conditions from left to right and stops when one is false, so a later length check is skipped when the array is null.
Practice
Exercise
An array named values has four elements. What are its first and last valid indexes, and is values[4] valid?
Show answer
The first index is 0 and the last is 3. values[4] is not valid because 4 equals the length.
Exercise
An array named items might be empty. What should you check before reading items[items.length - 1]?
Show answer
Check that items.length > 0. An empty array has no last element.
Exercise
A program checks only whether index < scores.length before using scores[index]. What invalid index could pass that check?
Show answer
A negative index such as -1 could pass. Also check that index >= 0.