Java Store a Fixed-Size Sequence
An array holds a fixed number of elements of one component type. Its length does not change after creation, even though the values stored at its positions may change.
Understand the idea
Array positions start at zero and stop before length. An array’s length is a field, unlike a collection’s size method or a String’s length method. An enhanced for loop visits values without exposing an index; use an indexed loop when the position is part of the task or when replacing elements. An array is an object, and copying its reference shares the same storage.
Run it locally
Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.
javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out MainA worked example
public class Main {
public static void main(String[] args) {
int[] booked = {4, 7, 2};
int total = 0;
for (int seats : booked) total += seats;
booked[1] = 6;
System.out.println(total);
System.out.println(booked.length);
System.out.println(booked[1]);
}
}
Expected output
13
3
6The total is computed before the second element is changed, so it remains thirteen. Updating an array element does not automatically recalculate a separate local variable. The array still has three positions. If the number of records must grow as bookings arrive, a collection such as ArrayList is a more natural starting point.
Check the official Java documentation for detailed contracts and supported options.