[!NOTE] Often, you'll need to store a list of related data—like 50 high scores or 10 usernames. Instead of creating 50 separate integer variables, you can store them in a single Array.
Declaring and Initializing Arrays
An Array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is strictly fixed.
// Method 1: Literal Initialization (when you know the values upfront)
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
int[] myScores = {10, 20, 30, 40};
// Method 2: Size Initialization (when you just want to reserve space)
int[] blankArray = new int[5]; // Creates space for 5 integers, all defaulting to 0
Accessing Elements
You access an array element by referring to the index number. Array indexes start with 0. [0] is the first element, [1] is the second, etc.
String[] cars = {"Volvo", "BMW", "Ford"};
System.out.println(cars[0]); // Outputs "Volvo"
// Modifying an element
cars[0] = "Opel";
System.out.println(cars[0]); // Now Outputs "Opel"
[!CAUTION] If you create an array of size 3, and try to access
cars[3], you will get a catastrophicArrayIndexOutOfBoundsException. Remember, a size 3 array only has indexes0, 1, 2.
Looping Through Arrays
To iterate over every element in an array, you have two amazing options.
Standard For Loop
Use this if you need to know the exact index you are currently processing.
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
System.out.println("Car at index " + i + " is: " + cars[i]);
}
The Enhanced For-Each Loop
Introduced in Java 5, this loop cleanly iterates through the elements without you having to manage an index counter.
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}
Arrays as Fixed-Size Building Blocks
Arrays are simple and fast because their size is fixed. That fixed size is both their strength and their limitation. If you know you need exactly 7 daily temperatures or exactly 100 marks, an array is natural. If the number of items grows and shrinks often, ArrayList is usually more convenient.
Default Values
When you create an array with a size but no values, Java fills it with defaults.
int[] scores = new int[3]; // [0, 0, 0]
boolean[] flags = new boolean[2]; // [false, false]
String[] names = new String[2]; // [null, null]
The null default for object arrays matters. If you call a method on a null element, the program can fail.
Finding the Maximum Value
int[] marks = {72, 91, 64, 88};
int max = marks[0];
for (int i = 1; i < marks.length; i++) {
if (marks[i] > max) {
max = marks[i];
}
}
System.out.println("Highest marks: " + max);
When Index Loops Beat For-Each
Use a normal for loop when you need the index, want to update values, or need to compare neighboring elements. Use enhanced for when you only need to read every value.
Mini Practice
Create an array of five marks. Print the total, average, highest mark, and the number of students who scored at least 60.
Practice Lab: Analyze Marks With Arrays
Use one array to calculate several useful results.
- Create
int[] marks = {72, 39, 88, 91, 55};. - Find the total and average.
- Find the highest mark.
- Count failed marks below 40.
- Print every mark with its index.
Goal: Practice index loops, enhanced loops, array length, and basic aggregation.
Revision Checkpoint
- Fixed size: Array length cannot change after creation.
- Zero index: First element is at index
0. - Last index:
array.length - 1. - Index loop: Best when index matters or values need updating.
- Enhanced loop: Best for reading every value simply.
Before the quiz: Predict what happens when code accesses arr[arr.length].