Arrays: Managing Collections of Data
Until now, we have stored data in single variables. But what if you need to store the names of 50 students, or the prices of 100 products? Creating 100 separate variables (price1, price2, etc.) would be a nightmare. Arrays allow you to store multiple values of the same type in a single variable.
1. What is an Array?
An array is a fixed-size container that holds a sequence of values.
- Fixed Size: Once you create an array, you cannot change its length.
- Same Type: An array can only hold one type of data (e.g., all
intor allString). - Zero-Indexed: In Java, counting starts at 0, not 1.
2. Declaring and Initializing Arrays
There are two main ways to create an array:
Method A: The "Empty" Array (Size first)
Use this when you know how many items you need, but you don't have the data yet.
// Create an array that can hold 5 integers
int[] numbers = new int[5];
// Assigning values
numbers[0] = 10;
numbers[1] = 20;
Method B: The "Populated" Array (Values first)
Use this when you already know exactly what data goes inside.
String[] cars = {"Tesla", "BMW", "Ford", "Mazda"};
3. Accessing and Modifying Elements
You use the Index Number inside square brackets [] to talk to a specific "box" in the array.
String[] tools = {"Java", "Kali", "VS Code"};
System.out.println(tools[0]); // Output: Java
tools[2] = "Sublime"; // Changes "VS Code" to "Sublime"
System.out.println(tools[2]); // Output: Sublime
4. Arrays and Loops
Since arrays are indexed by numbers, they are perfect partners for for loops.
String[] levels = {"Easy", "Medium", "Hard"};
for (int i = 0; i < levels.length; i++) {
System.out.println("Difficulty: " + levels[i]);
}
Tip: Use
.lengthto automatically get the size of the array so your loop doesn't go out of bounds!
5. The "ForEach" Loop
Java provides a specialized loop for arrays that is much cleaner if you only need to read the data.
int[] scores = {95, 88, 72};
for (int score : scores) {
System.out.println("Score: " + score);
}
💻 Full Practical Example: The Average Calculator
Copy this code to see how to process a collection of numbers:
public class ArrayStats {
public static void main(String[] args) {
double[] prices = {19.99, 5.50, 10.00, 120.00};
double sum = 0;
// Loop through array to calculate sum
for (double price : prices) {
sum += price;
}
double average = sum / prices.length;
System.out.println("Total Items: " + prices.length);
System.out.printf("Average Price: $%.2f %n", average);
}
}
⚠️ Common Pitfall: ArrayIndexOutOfBoundsException
If you have an array of size 5 and you try to access index 5 (myArray[5]), your program will crash. Remember: an array of size 5 only has indexes 0, 1, 2, 3, and 4.
💡 Challenge: The Name Searcher
Write a program that:
- Creates an array of 5 names.
- Asks the user to enter a name to search for.
- Uses a loop and an
ifstatement to check if that name exists in the array. - Prints "Found it!" or "Not in the list."