Java Arrays
An array stores a fixed number of values of one declared element type. Each value has a position called an index, and the first index is zero. Once an array is created, its length cannot change.
Why Do We Need This?
If we need to keep the marks for three tests, an array lets us store them under one variable name. We can read one mark by its index or use a loop to process every mark.
Main Ideas
| Concept | What it means |
|---|---|
| Element | A value stored at one position |
| Index | The position used to read or replace an element |
| length | The number of positions in the array |
| Single-dimensional array | Stores elements in one indexed sequence |
| Multi-dimensional array | Uses arrays whose elements are other arrays |
Simple Working Example
Run this program on its own. All required imports and classes are included.
public class HelloWorld {
public static void main(String[] args) {
int[] marks = {72, 85, 91};
System.out.println("First mark: " + marks[0]);
System.out.println("Number of tests: " + marks.length);
int total = 0;
for (int mark : marks) {
total += mark;
}
System.out.println("Total: " + total);
}
}Output
First mark: 72
Number of tests: 3
Total: 248The array has three positions: 0, 1, and 2. The enhanced for loop visits each mark. Using index 3 would fail because it is outside this array.
Topics in This Section
Easy Way to Remember
An array has a fixed length, but its elements can usually be replaced. A final array reference does not make those elements immutable.
See you in next page....??