Mastering Loops in Java - Day 06 of Java Series

Table of contents

Loops are one of the most fundamental concepts in any programming language, and Java is no exception. They allow you to repeat a block of code multiple times, which is incredibly useful for tasks like iterating through data, automating repetitive operations, or solving algorithmic problems. In this blog, we’ll break down everything you need to know about loops in Java—from the basics to some advanced use cases. Let’s dive in!
Loops in Java: An Introduction
At its core, a loop is a programming construct that lets you execute a block of code repeatedly based on a condition. The main types of loops in Java are:
for loop
while loop
do-while loop
Each type has its own specific use cases, but they all share the same basic idea: continue running the loop until a condition is no longer true.
Why Use Loops?
Efficiency: You can execute repetitive tasks without duplicating code.
Dynamic Operations: Work with varying input sizes, such as arrays or lists.
Code Readability: Simplify logic and make your code cleaner and more maintainable.
Elements of Loops: How They Work
Every loop in Java consists of three key elements:
Initialization: Sets up a starting point for the loop. For example,
int i = 0
.Condition: Determines whether the loop should continue. For example,
i < 10
.Update: Changes the state of the loop variable after each iteration. For example,
i++
.
These elements are critical to ensuring that your loop works correctly and terminates when it’s supposed to. If you forget to update the loop variable or set an unreachable condition, you might end up with an infinite loop.
Real-life analogy: Imagine you’re baking cookies, and you have to bake 12 batches. Here,
Initialization: Starting at batch 1 (
int batch = 1
)Condition: Bake until you’ve reached batch 12 (
batch <= 12
)Update: Move to the next batch after finishing one (
batch++
).
Mastering the for
Loop in Java
The for
loop is the most commonly used loop in Java. It’s ideal when you know how many times you want the loop to run.
Syntax:
for (initialization; condition; update) {
// Code to execute
}
Example:
Let’s say you have a list of 5 students, and you want to greet each one by their position.
for (int i = 1; i <= 5; i++) {
System.out.println("Hello, Student " + i);
}
Output:
Hello, Student 1
Hello, Student 2
Hello, Student 3
Hello, Student 4
Hello, Student 5
How it works:
Initialization: The loop starts with
i = 1
.Condition: The loop continues as long as
i <= 5
.Update: After each iteration,
i
is incremented by 1.
Enhanced for
Loop:
The enhanced for
loop (also called a for-each loop) is perfect for iterating through arrays or collections. For example, let’s say you want to print the names of students in a class:
String[] students = {"Alice", "Bob", "Charlie", "Diana"};
for (String student : students) {
System.out.println("Hello, " + student);
}
Output:
Hello, Alice
Hello, Bob
Hello, Charlie
Hello, Diana
How it works: For each element in the array students
, the variable student
holds the value of the current element, and the loop processes it.
The while
and do-while
Loops Explained
while
Loop:
The while
loop executes a block of code as long as the condition is true. It’s often used when you don’t know beforehand how many iterations are needed.
Syntax:
while (condition) {
// Code to execute
}
Real Example:
Suppose you’re reading books in a series, and you’ll stop reading when you finish all books.
int booksLeft = 5;
while (booksLeft > 0) {
System.out.println("Reading a book. " + booksLeft + " books left.");
booksLeft--;
}
Output:
Reading a book. 5 books left.
Reading a book. 4 books left.
Reading a book. 3 books left.
Reading a book. 2 books left.
Reading a book. 1 books left.
How it works:
The loop starts with
booksLeft = 5
.It keeps executing the block until
booksLeft > 0
is false.On each iteration,
booksLeft
is decremented.
do-while
Loop:
The do-while
loop ensures the code block runs at least once, even if the condition is false.
Syntax:
do {
// Code to execute
} while (condition);
Real Example:
Suppose you’re testing a game, and you want to simulate rolling a die until you get a 6:
import java.util.Random;
Random rand = new Random();
int roll;
do {
roll = rand.nextInt(6) + 1;
System.out.println("Rolled: " + roll);
} while (roll != 6);
Output (varies):
Rolled: 3
Rolled: 5
Rolled: 6
How it works:
The code inside the
do
block runs first.After rolling the die, the condition (
roll != 6
) is checked.
Using break
and continue
in Java Loops
break
Statement:
The break
statement is used to exit a loop prematurely, regardless of the condition.
Real-life analogy: If you’re flipping through TV channels and find your favorite show, you stop flipping (break the loop).
Example:
for (int i = 1; i <= 10; i++) {
if (i == 6) {
break;
}
System.out.println(i);
}
Output:
1
2
3
4
5
continue
Statement:
The continue
statement skips the current iteration and moves to the next iteration of the loop.
Real-life analogy: If you’re scanning emails and come across spam, you skip it and move to the next email.
Example:
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue;
}
System.out.println(i);
}
Output:
1
3
5
7
9
Nested Loops and Printing Patterns in Java
Nested loops are loops inside loops. They’re especially useful for working with multidimensional arrays or creating patterns.
Example: Print a triangle pattern
Let’s create a simple triangle pattern with stars:
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
Output:
*
**
***
****
*****
How it works:
The outer loop controls the rows.
The inner loop controls the number of stars printed in each row.
Example: Multiplication Table
Let’s generate a multiplication table using nested loops:
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
System.out.print(i * j + "\t");
}
System.out.println();
}
Output:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
...
Labeled break
and continue
Statements
In Java, you can use labels with break
and continue
to control nested loops more effectively.
Real Example:
Suppose you’re searching for a specific number in a 2D array. If you find it, you want to exit all loops immediately:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
boolean found = false;
outerLoop:
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] == 5) {
found = true;
break outerLoop;
}
}
}
System.out.println("Number found: " + found);
Output:
Number found: true
Additional Advanced Tips
1. Loop Optimization
Avoid unnecessary computations inside loops by performing constant expressions outside the loop.
// Inefficient
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
// Do something
}
}
// Efficient
int length = array.length;
for (int i = 0; i < length; i++) {
for (int j = 0; j < length; j++) {
// Do something
}
}
2. Combining Loops with Conditional Logic
Combining loops with if-else
logic can help solve complex problems.
for (int i = 1; i <= 100; i++) {
if (i % 15 == 0) {
System.out.println("FizzBuzz");
} else if (i % 3 == 0) {
System.out.println("Fizz");
} else if (i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i);
}
}
3. Using Streams for Iterative Tasks
For advanced users, Java Streams (introduced in Java 8) can sometimes replace loops for certain operations like filtering, mapping, or reducing data.
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.stream()
.filter(n -> n % 2 == 0)
.forEach(System.out::println);
Practice Problems
Here are some practice problems to help you solidify your understanding of loops in Java:
Write a program to print the multiplication table for a given number.
Create a program to check whether a number is a palindrome using a
while
loop.Write a program to calculate the factorial of a number using a
for
loop.Use nested loops to print the following pattern:
1 12 123 1234 12345
Write a program to count the number of vowels and consonants in a string using a
for
loop.Create a program to generate the Fibonacci sequence up to a certain number.
Solve the "FizzBuzz" problem using both loops and streams.
Conclusion
Loops are a powerful tool in Java, allowing you to write efficient and concise code. By mastering for
, while
, and do-while
loops—along with techniques like nested loops, labeled control statements, and performance optimization—you’ll be well-equipped to tackle a wide range of programming problems. Keep practicing, explore edge cases, and experiment with advanced scenarios to deepen your understanding!
Subscribe to my newsletter
Read articles from Ajink Gupta directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Ajink Gupta
Ajink Gupta
I am an engineering student pursuing a degree in Artificial Intelligence and Data Science at Datta Meghe College of Engineering. I have strong technical skills in Full Stack Web Development, as well as programming in Python and Java. I currently manage Doubtly's blog and am exploring job opportunities as an SDE. I am passionate about learning new technologies and contributing to the tech community.