Chapter 4: Loops and Methods
Chapter 3 taught you how to make decisions with if-else and switch. This chapter builds on that by covering how Java repeats work with loops, and how you can package reusable logic into methods so your programs don't turn into one giant block of code.
1. The For Loop
A for loop is ideal when you know exactly how many times you want to repeat something. It has three parts: an initializer, a condition, and an update step, all separated by semicolons.
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
2. The While and Do-While Loops
A while loop repeats as long as its condition remains true, and is a better fit when you don't know the exact number of iterations in advance — for example, reading input until a user types "quit". A do-while loop is nearly identical, except it guarantees the loop body runs at least once before the condition is checked.
int count = 0;
while (count < 3) {
System.out.println("While iteration: " + count);
count++;
}
3. Breaking and Continuing
The break keyword exits a loop immediately, while continue skips the rest of the current iteration and jumps to the next one. Both are useful for handling special cases without nesting extra if statements.
for (int i = 1; i <= 10; i++) {
if (i == 5) continue; // skip 5
if (i == 8) break; // stop entirely at 8
System.out.println(i);
}
4. Writing Your Own Methods
A method is a named, reusable block of code. Methods let you avoid repeating yourself and make your programs easier to read and test. A method has a return type, a name, and a set of parameters in parentheses.
public static int square(int number) {
return number * number;
}
public static void main(String[] args) {
System.out.println(square(6)); // 36
}
If a method doesn't return anything, its return type is void. Methods can also take multiple parameters, separated by commas, and can call other methods to build up more complex behavior from small, testable pieces.
Common Beginner Mistakes
- Infinite loops: forgetting to update the loop's counter variable, so the condition never becomes false.
- Off-by-one errors: using
<=when you meant<, causing a loop to run one time too many. - Mismatched return types: declaring a method as
intbut forgetting to return a value on every possible path.
Try It Yourself
- Write a
forloop that prints all even numbers from 2 to 20. - Write a method called
isEventhat takes anintand returns aboolean. - Combine both: loop from 1 to 20 and use your method to print only the even numbers.
Enhanced For Loops
When looping through arrays or collections, the enhanced for loop (sometimes called "for-each") is more concise and less error-prone than a traditional indexed loop.
int[] scores = {90, 85, 78};
for (int score : scores) {
System.out.println(score);
}
Method Overloading
Java lets you define multiple methods with the same name but different parameters — the compiler picks the right one based on the arguments you pass.
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
CodeMaster Academy