Many programming tasks involve repeating the same action multiple times, such as printing a list of numbers, processing every item in a collection, or checking a condition repeatedly until it changes. Writing the same line of code again and again for each repetition would be inefficient and difficult to maintain, which is exactly the problem loops are designed to solve.
Java provides several types of loops, each suited to slightly different situations. Some loops are ideal when you know exactly how many times a task should repeat, while others are better suited when the number of repetitions depends on a condition that may change during execution.
In this tutorial, you will learn how the for loop, while loop, do-while loop, and enhanced for loop work, along with how the break and continue statements can be used to control loop behavior more precisely.
A loop is a control structure that repeats a block of code as long as a specified condition remains true. Once the condition becomes false, the loop stops, and the program continues with the code that follows it.
public class LoopExample {
public static void main(String[] args) {
String channel = "CS Engineering Gyan";
for (int i = 1; i <= 3; i++) {
System.out.println(channel + " video number " + i + " uploaded.");
}
}
}
CS Engineering Gyan video number 1 uploaded. CS Engineering Gyan video number 2 uploaded. CS Engineering Gyan video number 3 uploaded.
Instead of writing the same print statement three separate times, the loop repeats it automatically, adjusting the value of i with each repetition.
The for loop is typically used when the number of repetitions is known in advance. It combines initialization, condition checking, and updating into a single, compact line, making it one of the most commonly used loops in Java.
for (initialization; condition; update) {
// code to repeat
}
public class ForLoopExample {
public static void main(String[] args) {
String channel = "CS Engineering Gyan";
for (int week = 1; week <= 5; week++) {
System.out.println(channel + " weekly upload " + week + " completed.");
}
}
}
CS Engineering Gyan weekly upload 1 completed. CS Engineering Gyan weekly upload 2 completed. CS Engineering Gyan weekly upload 3 completed. CS Engineering Gyan weekly upload 4 completed. CS Engineering Gyan weekly upload 5 completed.
In this example, week starts at 1, the loop continues as long as it is less than or equal to 5, and its value increases by 1 after each repetition, until the condition becomes false.
The while loop is useful when the number of repetitions is not known beforehand and instead depends on a condition that may change while the program is running. The condition is checked before each repetition, meaning the loop may not execute at all if the condition starts out false.
while (condition) {
// code to repeat
}
public class WhileLoopExample {
public static void main(String[] args) {
String channel = "CS Engineering Gyan";
int subscribers = 96000;
while (subscribers < 100000) {
subscribers += 1000;
System.out.println(channel + " subscribers now: " + subscribers);
}
}
}
CS Engineering Gyan subscribers now: 97000 CS Engineering Gyan subscribers now: 98000 CS Engineering Gyan subscribers now: 99000 CS Engineering Gyan subscribers now: 100000
Here, the loop keeps running and increasing the subscriber count until it reaches 100000, at which point the condition becomes false and the loop stops automatically.
The do-while loop is similar to the while loop, but with one important difference: the condition is checked after the code block runs, not before. This guarantees that the loop's body executes at least once, even if the condition is false from the very beginning.
do {
// code to repeat
} while (condition);
public class DoWhileExample {
public static void main(String[] args) {
String channel = "CS Engineering Gyan";
int videoCount = 0;
do {
videoCount++;
System.out.println(channel + " published video " + videoCount);
} while (videoCount < 3);
}
}
CS Engineering Gyan published video 1 CS Engineering Gyan published video 2 CS Engineering Gyan published video 3
The do-while loop is particularly useful in situations such as menu-driven programs, where an action should happen at least once before checking whether it should be repeated again.
| while Loop | do-while Loop |
|---|---|
| Condition is checked before the loop body executes. | Condition is checked after the loop body executes. |
| The loop body may not execute at all if the condition is false initially. | The loop body always executes at least once. |
| Commonly used when the number of repetitions depends entirely on a condition. | Commonly used when at least one execution is required regardless of the condition. |
Java provides an enhanced for loop, also known as a for-each loop, which is specifically designed for iterating through elements of arrays or collections. It removes the need to manually manage an index variable, making the code shorter and easier to read.
for (dataType element : collection) {
// code to execute for each element
}
public class EnhancedForExample {
public static void main(String[] args) {
String channel = "CS Engineering Gyan";
String[] playlists = {"Java Basics", "Data Structures", "DBMS", "Operating Systems"};
System.out.println(channel + " current playlists:");
for (String playlist : playlists) {
System.out.println("- " + playlist);
}
}
}
CS Engineering Gyan current playlists: - Java Basics - Data Structures - DBMS - Operating Systems
The enhanced for loop automatically moves through each element in the array, from the first to the last, without requiring you to track the index or the length of the array manually.
The break statement is used to exit a loop immediately, even if the loop's condition would otherwise still be true. This is useful when a specific situation is reached and there is no need to continue checking further repetitions.
public class BreakExample {
public static void main(String[] args) {
String channel = "CS Engineering Gyan";
for (int video = 1; video <= 10; video++) {
if (video == 5) {
System.out.println(channel + " stopped uploads at video " + video);
break;
}
System.out.println(channel + " uploaded video " + video);
}
}
}
CS Engineering Gyan uploaded video 1 CS Engineering Gyan uploaded video 2 CS Engineering Gyan uploaded video 3 CS Engineering Gyan uploaded video 4 CS Engineering Gyan stopped uploads at video 5
As soon as the condition inside the if statement becomes true, the break statement immediately ends the loop, skipping any remaining repetitions that would have otherwise occurred.
The continue statement works differently from break. Instead of ending the loop completely, it skips the rest of the current repetition and moves directly to the next one, without stopping the loop altogether.
public class ContinueExample {
public static void main(String[] args) {
String channel = "CS Engineering Gyan";
for (int video = 1; video <= 5; video++) {
if (video == 3) {
continue;
}
System.out.println(channel + " processed video " + video);
}
}
}
CS Engineering Gyan processed video 1 CS Engineering Gyan processed video 2 CS Engineering Gyan processed video 4 CS Engineering Gyan processed video 5
Notice that video 3 is skipped entirely, but the loop continues running normally for the remaining values, unlike break, which would have stopped the loop completely at that point.
Java also allows loops to be placed inside other loops, a structure known as a nested loop. This is often used when working with grid-like data or when repeating an entire sequence of steps multiple times.
public class NestedLoopExample {
public static void main(String[] args) {
String channel = "CS Engineering Gyan";
for (int week = 1; week <= 2; week++) {
System.out.println(channel + " week " + week + " schedule:");
for (int day = 1; day <= 3; day++) {
System.out.println(" Day " + day + ": New video uploaded");
}
}
}
}
CS Engineering Gyan week 1 schedule: Day 1: New video uploaded Day 2: New video uploaded Day 3: New video uploaded CS Engineering Gyan week 2 schedule: Day 1: New video uploaded Day 2: New video uploaded Day 3: New video uploaded
In this example, the outer loop controls the number of weeks, while the inner loop runs completely for each single repetition of the outer loop, resulting in a structured, repeated pattern of output.
| Situation | Recommended Loop |
|---|---|
| Number of repetitions is known in advance. | for loop |
| Repetition depends on a condition that may change over time. | while loop |
| Code must run at least once regardless of the condition. | do-while loop |
| Iterating through every element of an array or collection. | enhanced for loop |
| Mistake | Correct Practice |
|---|---|
| Forgetting to update the loop variable, causing an infinite loop. | Always ensure the update statement changes the condition over time. |
| Using a semicolon accidentally after the for loop declaration. | Avoid placing a semicolon right after the loop's closing parenthesis. |
| Confusing when to use break versus continue. | Use break to exit the loop completely, and continue to skip only the current repetition. |
| Using a while loop when a do-while loop is actually required. | Use do-while when the code must execute at least once before checking the condition. |
Loops allow Java programs to repeat tasks efficiently without duplicating code, making them essential for handling repetitive operations such as processing lists, generating patterns, or waiting for a condition to change. The for loop works best when the number of repetitions is known in advance, while the while and do-while loops handle situations where repetition depends on a condition evaluated during execution.
The enhanced for loop further simplifies working with arrays and collections, while the break and continue statements provide additional control over how a loop behaves during execution. Together, these tools give you the ability to build programs that can process data efficiently, regardless of how many times a particular task needs to be repeated.
With a solid understanding of loops, you are now ready to explore arrays, which allow you to store and manage multiple related values using loops to process them efficiently.