Lesson 9 of 36Article16 min
Arrays
An array holds many values of the same type in one variable. Size is fixed after creation.
Arrays — fixed-size lists
An array holds many values of the same type in one variable. Size is fixed after creation.
Index starts at 0. Last index is length - 1. Access with arr[i].
Real-life example: An array is a row of lockers — each locker has a number (index). You cannot add a 11th locker without a new row.
Create and use arrays
int[] scores = {90, 85, 78, 92};
System.out.println(scores[0]); // 90
System.out.println(scores.length); // 4
String[] names = new String[3];
names[0] = "Asha";
names[1] = "Rohan";
names[2] = "Priya";Loop through arrays
Use for loop with index or enhanced for (for-each) to visit every element.
for-each is simpler when you only need values, not index.
Real-life example: for-each is like reading every name on a attendance sheet top to bottom without caring about roll number.
For-each and indexed loop
int[] nums = {10, 20, 30};
for (int n : nums) {
System.out.println(n);
}
for (int i = 0; i < nums.length; i++) {
System.out.println("Index " + i + ": " + nums[i]);
}