Java
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented Java
-
Section 4: Collections Framework
-
Section 5: Exception Handling
-
Section 6: Generics
-
Section 7: Functional Java
-
Section 8: Concurrency
-
Section 9: I/O and NIO
-
Section 10: JVM Internals
-
Section 11: Modern Java Features
-
Section 12: Build Tools and Project Structure
-
Section 13: Testing
-
Section 14: Databases and Persistence
-
Section 15: Networking
-
Section 16: Design and Best Practices
-
Section 17: Reflection and Annotations
-
Section 18: Logging and Diagnostics
-
Section 19: Date, Time, and Internationalization
-
Section 20: Java Platform Module System
-
Section 21: Security in Java
-
Section 22: Advanced Collections and Data Structures
-
Section 23: More Concurrency Patterns
-
Section 24: Compression, Files, and System Integration
-
Section 25: GUI Programming
-
Section 26: Practical Projects
-
Section 27: Data Structures and Algorithms
-
Section 28: Interview and Algorithm Practice
-
Section 29: JSON and Data Interchange
-
Section 30: More Concurrency Utilities
-
Section 31: More Collections and Streams Practice
-
Section 32: More File and System Programming
-
Section 33: Standard Library Deep Dive
-
Section 34: More Practice and Drills
-
Section 35: More Testing and Quality
-
Section 36: More Design Patterns and Architecture
-
Section 37: Career and Ecosystem
-
Section 38: More OOP and Architecture Practice
-
Section 39: More Enterprise Concepts
-
Section 40: Advanced JavaFX
-
Section 41: More Interview Practice
17: Arrays in Java
Imagine you're organizing a small cinema for a film festival. Instead of having random chairs scattered around the room, you set up a single, long row of 10 seats. Every seat is identical, and they are bolted to the floor in a specific order. If you want to find the person in the third seat, you don't have to search the whole room; you just count over to the third spot. However, there's a catch: once you've bolted those 10 seats down, you can't suddenly decide the row should hold 11 people without rebuilding the whole setup.
That's exactly how an array works in Java. Here is how that cinema row maps to the code:
- The Row: This is the array itself. It's a single container holding multiple values of the same type.
- The Seat Number: This is the
index. In Java, we start counting at 0, so the first seat is index 0, not 1. This trips up almost everyone at first, but you'll get used to it. - The Person in the Seat: This is the
elementor the value stored at that specific index. - The Bolted Floor: This represents the
fixed length. Once you initialize an array in Java, you cannot change its size.
Carving out space for your data
To use an array, you have to tell Java two things: what kind of data it will hold and how big it needs to be. Let's say we're tracking the daily high temperatures for a business week (5 days). I wouldn't want to create five separate variables like tempMonday, tempTuesday, etc.—that's a nightmare to maintain.
// Declaring an array of integers that can hold 5 values
int[] weeklyTemps = new int[5];
// Now we fill the "seats"
weeklyTemps[0] = 72; // Monday
weeklyTemps[1] = 75; // Tuesday
weeklyTemps[2] = 68; // Wednesday
weeklyTemps[3] = 70; // Thursday
weeklyTemps[4] = 74; // Friday
Notice the [] brackets? That's Java's way of saying "this isn't just one integer; it's a collection of them." If you try to access weeklyTemps[5], Java will throw an ArrayIndexOutOfBoundsException and crash your program. Why? Because we only bolted down 5 seats (0 through 4). Always remember: the last index is always length - 1.
The shortcut for known values
Sometimes, you already know exactly what needs to go into the array the moment you create it. In those cases, you don't need to specify the size or assign values one by one. You can use an array literal.
// This does the same thing as the code above, but much faster
int[] weeklyTemps = {72, 75, 68, 70, 74};
I use this shorthand 90% of the time when the data is static. It's cleaner and easier to read at a glance.
Walking through the array
The real power of arrays comes when you combine them with loops. You don't want to manually write a line of code for every single element. Instead, you can "iterate" through them. I'll show you the two most common ways to do this.
The classic for loop is great when you actually need to know the index (for example, if you want to print "Day 1: 72 degrees").
for (int i = 0; i < weeklyTemps.length; i++) {
System.out.println("Day " + (i + 1) + ": " + weeklyTemps[i]);
}
But if you just care about the values and don't care about the index, use the "enhanced" for-loop (often called the for-each loop). It's much more concise.
for (int temp : weeklyTemps) {
System.out.println("Temperature: " + temp);
}
Essentially, the for-each loop says: "For every integer temp inside the weeklyTemps array, execute this code." It's cleaner, though you lose the ability to modify the specific index you're currently visiting.
📋 Practical Task
Build a Monthly Rainfall Analyzer
Your goal is to create a program that analyzes rainfall data for a 30-day month. Follow these requirements:
- Create an array of
doublevalues namedmonthlyRainfall. - Initialize it with 30 values (you can make up the numbers, but ensure they are doubles, e.g.,
0.5, 1.2, 0.0). - Write a loop to calculate the total rainfall for the entire month.
- Write a second loop to find the highest single-day rainfall amount in the array.
- Print both the total and the maximum value to the console.
There are no comments for now.