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
14: For Loops
A few years ago, I was reviewing a pull request from a junior developer who was tasked with calculating the total value of a shopping cart. When I opened the file, I found something that made me chuckle: he had written cartTotal += item[0]; cartTotal += item[1]; and so on, all the way down to index 15. It worked, but it was fragile. The moment a customer added a 16th item to their cart, the code ignored it. When I asked him how he'd handle a cart with 1,000 items, he realized he'd spent half his afternoon writing code that a three-line loop could have handled. That's the core of why we use for loops—not just to save typing, but to write code that scales regardless of the input size.
The Mechanics of the Iteration
At its heart, a for loop is just a way to tell Java, "Do this specific block of code a certain number of times, and keep track of where we are." You'll see the syntax usually broken into three parts inside the parentheses: the initialization, the condition, and the update expression. I like to think of it as a contract. You define where you start (usually int i = 0), the rule that keeps the loop running (like i < 10), and how you move to the next step (i++).
for (int i = 0; i < 5; i++) {
System.out.println("Processing record number: " + i);
}
In this example, i is our counter. It starts at 0, and as long as it's less than 5, the code inside the curly braces runs. After each run, i++ bumps the number up by one. Once i hits 5, the condition 5 < 5 becomes false, and Java jumps straight to the code following the loop. It's clean, predictable, and prevents that manual copy-paste nightmare I mentioned earlier.
Walking Through Data Arrays
While counting from 0 to 10 is useful, you'll most often use for loops to traverse arrays or lists. Instead of hardcoding a number like 5 or 10, we use the .length property of the array. This is where the loop becomes powerful; your code now works whether the array has two elements or two million.
Let's say you're building a simple system to apply a tax to a list of product prices. You wouldn't want to manually call every index. Instead, you'd do something like this:
double[] prices = {12.99, 25.00, 9.95, 100.00, 4.50};
double taxRate = 0.07;
for (int i = 0; i < prices.length; i++) {
double taxAmount = prices[i] * taxRate;
System.out.println("Tax for item " + i + " is: " + taxAmount);
}
Notice how I'm using prices[i]. As i increments, we are essentially sliding a window across the array, grabbing one value at a time. One quick tip: always be careful with your comparison operator. Using <= prices.length is a classic mistake that will crash your program with an ArrayIndexOutOfBoundsException because Java arrays are zero-indexed. If an array has 5 elements, the last index is 4, not 5.
📋 Practical Task
Exercise: Weekly Step Tracker Analysis
You are building a fitness app. You have an array containing the number of steps a user took each day for one week. Your task is to write a program that uses a for loop to accomplish two things: calculate the total number of steps for the week and identify the day with the highest step count.
Requirements:
- Create an integer array named
weeklyStepswith the following values:{8500, 12000, 7000, 11000, 15000, 9000, 10000}. - Use a
forloop to sum all the values in the array into a variable calledtotalSteps. - Inside the same loop (or a second one), track the highest value found in the array and store it in a variable called
maxSteps. - Print both the
totalStepsand themaxStepsto the console.
There are no comments for now.