1D Arrays
Overview
Imagine you are building an app for a classroom of 50 students and you need to store their grades. Creating 50 separate variables (`grade1`, `grade2`, `grade3`...) would be a nightmare.
An Array solves this. An array is a single data structure that holds multiple items of the *same type* in a strict sequence. It's like a tightly packed row of lockers. You give the row a single name (like `grades`), and access each locker using a number (called an index).
1. Fixed Size
The most important rule of basic arrays in Java: Once you create an array and tell it how big it is (e.g., 5 items), its size is locked forever. You cannot make it bigger or smaller later.
2. Zero-Indexed
Arrays in programming don't start counting at 1. They start at 0. So, the very first locker in the array is at index 0. If the array holds 5 items, the last item is at index 4.
3. Looping through Arrays
Arrays and Loops are best friends. Because arrays use numerical indexes (0, 1, 2, 3), we use `for` loops to easily check or print every item in the array in a split second.
Syntax
You can create an array empty and fill it, or create it with all the items at once.
// Method 1: Create an array with a fixed size of 3 slots
int[] scores = new int[3];
scores[0] = 85; // First slot
scores[1] = 90; // Second slot
scores[2] = 95; // Third (last) slot
// Method 2: Array Literal (Faster if you know the data already)
String[] friends = {"Alice", "Bob", "Charlie"};
// Accessing data
System.out.println("My best friend is " + friends[0]); // Prints AliceA special, cleaner loop designed specifically for going through arrays.
String[] fruits = {"Apple", "Banana", "Mango"};
// Reads as: "For each String 'fruit' inside the 'fruits' array..."
for (String fruit : fruits) {
System.out.println("I love " + fruit);
}Common Pitfalls
- Accessing an invalid index. If an array has 3 items, asking for `friends[3]` will crash your app! (The valid indexes are 0, 1, 2).
- Trying to put a `String` into an `int[]` array. Arrays can only hold one specific data type.
Interview Tips
- The `ArrayIndexOutOfBoundsException` is the most common bug developers face. Always use `array.length` in your loops to ensure you never go past the edge of the array.
Real-World Example
Arrays are the foundation of storing lists of data, like recent messages or a shopping cart.
public class ChatApp {
public static void main(String[] args) {
// Storing the 3 most recent chat messages
String[] recentMessages = {"Hey!", "How are you?", "Call me."};
System.out.println("--- Recent Chats ---");
for (int i = 0; i < recentMessages.length; i++) {
System.out.println("Message " + (i+1) + ": " + recentMessages[i]);
}
}
}