egg carton: it has a specific number of slots, and each slot holds one egg. You can’t put a bowling ball in an egg carton, and you can't suddenly make it hold 20 eggs if it was built for 12.
In Java, arrays are zero-indexed. This means the computer starts counting at 0, not 1.
The 1st item is at index
[0].The 2nd item is at index
[1].The 10th item is at index
[9].
Key Rules of Arrays
Fixed Size: Once you create an array of size 5, it stays size 5 forever.
Same Type: You can have an array of integers OR an array of Strings, but you cannot mix them.
The
.lengthProperty: You can always ask an array how big it is by usingarrayName.length.
The Code Example:
public class ArraysDemo {
public static void main(String[] args) {
// 1. Declaring and initializing an array (The "Quick" way)
String[] favoriteFruits = {"Apple", "Banana", "Mango", "Cherry"};
// 2. Accessing elements using their index [0, 1, 2, 3]
System.out.println("First fruit in the list: " + favoriteFruits[0]);
System.out.println("Third fruit in the list: " + favoriteFruits[2]);
// 3. Changing a value in the array
favoriteFruits[1] = "Blueberry"; // Banana is now gone!
System.out.println("Updated second fruit: " + favoriteFruits[1]);
// 4. Declaring an empty array with a specific size
int[] scores = new int[3]; // Creates [0, 0, 0]
scores[0] = 95;
scores[1] = 88;
scores[2] = 72;
// 5. Using a Loop to print all elements (Very common!)
System.out.println("\n--- All Student Scores ---");
for (int i = 0; i < scores.length; i++) {
System.out.println("Score at index " + i + ": " + scores[i]);
}
// Bonus: The "Enhanced For-Loop" (For-Each)
System.out.println("\n--- Fast Fruit List ---");
for (String fruit : favoriteFruits) {
System.out.println("I love " + fruit);
}
}
}Expected Output:
First fruit in the list: Apple
Third fruit in the list: Mango
Updated second fruit: Blueberry
--- All Student Scores ---
Score at index 0: 95
Score at index 1: 88
Score at index 2: 72
--- Fast Fruit List ---
I love Apple
I love Blueberry
I love Mango
I love Cherry