Introduction to Looping and Iteration in Java
Course: Core Java Training
Topic: Introduction to Looping and Iteration
Course Link: Core Java Training Course
Demo Link: Register for a Course Demo
JustAcademy Homepage: Visit JustAcademy
1. Introduction to Looping and Iteration
Looping and iteration are fundamental concepts in Java programming that allow a program to execute a block of code repeatedly. Instead of writing the same statement many times, a programmer can use a loop to repeat an operation according to a condition or a defined sequence.
For example, if a program needs to print the numbers from 1 to 100, writing 100 separate print statements would be inefficient. A loop can perform the same task using only a few lines of code.
Java provides three primary looping statements: for, while, and do-while. Each loop has a different structure and is suitable for particular programming situations.
Learning objectives
- Understand the meaning of looping and iteration.
- Learn why loops are used in Java programs.
- Understand loop conditions, loop bodies, and control variables.
- Identify the differences between for, while, and do-while loops.
- Learn how loops execute step by step.
- Recognize infinite loops and common looping errors.
- Apply loops to practical programming problems.
2. What Is Looping in Java?
Looping is the process of repeatedly executing a statement or group of statements while a specified condition remains true or until a required stopping point is reached.
A loop generally consists of a condition, a body containing the statements to repeat, and some mechanism that eventually changes the program state or ends the repetition.
Example:
public class LoopExample {
public static void main(String[] args) {
int count = 1;
while (count <= 5) {
System.out.println("Hello Java");
count++;
}
}
}
Output:
Hello Java
Hello Java
Hello Java
Hello Java
Hello Java
Explanation: The variable count begins at 1. The loop checks whether count is less than or equal to 5. If the condition is true, the message is printed and count is increased by one. When count becomes 6, the condition is false and the loop ends.
3. What Is Iteration?
An iteration is one complete execution of a loop body. If a loop body runs five times, the loop has completed five iterations, assuming each execution reaches the normal end of that body.
Consider this example:
for (int i = 1; i <= 3; i++) {
System.out.println("Iteration: " + i);
}
Output:
Iteration: 1
Iteration: 2
Iteration: 3
The loop performs three iterations. During each iteration, the value of i is displayed. After the third iteration, i becomes 4, the condition fails, and the loop terminates.
Important terminology
| Term |
Meaning |
Example |
| Loop |
A control structure that repeats statements. |
while |
| Iteration |
One execution of the loop body. |
One pass through a loop |
| Condition |
A Boolean expression that determines whether repetition continues. |
i < 10 |
| Loop body |
The statements executed during each iteration. |
System.out.println(i); |
| Initialization |
Sets the initial value of a loop-control variable. |
int i = 1 |
| Update |
Changes a variable to help the loop progress. |
i++ |
| Termination |
The point at which the loop stops executing. |
Condition becomes false |
4. Why Are Loops Important?
Loops reduce repetition and make programs easier to maintain. They are useful whenever a task must be repeated for multiple values, records, objects, or user interactions.
- Reduce duplicate code: Write a repeated operation once and execute it many times.
- Process collections: Read and process elements in arrays, lists, and other collections.
- Perform calculations: Calculate totals, averages, factorials, and running sums.
- Validate input: Repeat prompts until the user supplies acceptable input.
- Build interactive menus: Keep displaying options until the user chooses to exit.
- Implement algorithms: Search, sort, count, and transform data.
- Automate repetitive work: Perform a defined operation over a sequence of records or values.
5. Types of Loops in Java
Java provides three primary loop statements. The choice depends on whether the number of repetitions is known in advance and whether the condition should be checked before or after executing the loop body.
| Loop type |
Condition checked |
Minimum body executions |
Common use |
for |
Before each iteration |
Zero |
Counting through a known range |
while |
Before each iteration |
Zero |
Repeating while a condition remains true |
do-while |
After each iteration |
One |
Tasks that must execute at least once |
Enhanced for |
Managed by the iteration process |
Zero for an empty source |
Reading array or iterable elements |
6. Introduction to the for Loop
The for loop is commonly used when the repetition follows a counter or a sequence. Its header usually contains three parts: initialization, condition, and update.
Syntax
for (initialization; condition; update) {
// Statements to repeat
}
- Initialization: Executes once when the loop begins.
- Condition: Evaluated before each iteration. If false, the loop ends.
- Update: Runs after the loop body completes normally and prepares for the next condition check.
Example: Print numbers from 1 to 5
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
}
Output:
1
2
3
4
5
How it works:
- The variable
i is initialized to 1.
- Java checks whether
i <= 5.
- If true, the current value is printed.
- The update expression
i++ increases the value by one.
- The condition is checked again until it becomes false.
7. Introduction to the while Loop
The while loop repeatedly executes its body as long as its Boolean condition is true. Because the condition is checked before the body, the loop may execute zero times if the condition is initially false.
Syntax
while (condition) {
// Statements to repeat
}
Example: Print numbers from 1 to 5
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
}
}
Output:
1
2
3
4
5
The variable i is initialized before the loop. After each print operation, i++ moves the counter toward the stopping condition. When the value becomes 6, the condition is false and the loop ends.
8. Introduction to the do-while Loop
The do-while loop executes its body first and checks the condition afterward. Therefore, the body always executes at least once, even if the condition is false at the beginning.
Syntax
do {
// Statements to repeat
} while (condition);
Notice the semicolon after the condition. It is required in Java's do-while syntax.
Example: Print numbers from 1 to 5
public class DoWhileExample {
public static void main(String[] args) {
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);
}
}
Output:
1
2
3
4
5
Demonstrating the key difference
int a = 10;
while (a < 5) {
System.out.println("while body");
}
do {
System.out.println("do-while body");
} while (a < 5);
Output:
do-while body
The while condition is false before its body can run, so it prints nothing. The do-while body executes once before the same false condition is checked.
9. Understanding Loop Control Variables
A loop-control variable is a variable used to control or track repetition. In counter-based loops, it commonly stores the current position or iteration number.
int counter = 1;
while (counter <= 4) {
System.out.println("Counter: " + counter);
counter++;
}
The variable counter determines how many times the body executes. If the variable is never updated and the condition remains true, the loop may never terminate.
Loop variables can count upward or downward. For example:
for (int i = 5; i >= 1; i--) {
System.out.println(i);
}
Output:
5
4
3
2
1
10. Entry-Controlled and Exit-Controlled Loops
Loops can be classified according to when their conditions are checked.
- Entry-controlled loops: Check the condition before running the body. Java's
for and while loops follow this pattern.
- Exit-controlled loop: Checks the condition after running the body. Java's
do-while loop follows this pattern.
This distinction matters when the task must happen at least once, such as displaying a menu before asking whether the user wants to continue.
11. Nested Loops
A nested loop is a loop placed inside another loop. The inner loop can execute multiple times for each iteration of the outer loop.
Example: Display a small number pattern
public class NestedLoopExample {
public static void main(String[] args) {
for (int row = 1; row <= 3; row++) {
for (int column = 1; column <= 2; column++) {
System.out.print("* ");
}
System.out.println();
}
}
}
Output:
* *
* *
* *
The outer loop runs three times. For each outer iteration, the inner loop runs twice, printing two asterisks. Nested loops are useful for tables, grids, matrix processing, and pattern generation.
12. Enhanced for Loop
The enhanced for loop, also called the for-each loop, provides a convenient way to read elements from arrays and objects that implement Iterable. It avoids manually managing an index when the position is not needed.
Syntax
for (Type element : collectionOrArray) {
// Process the element
}
Example: Iterate through an array
public class EnhancedForExample {
public static void main(String[] args) {
String[] languages = {"Java", "Python", "JavaScript"};
for (String language : languages) {
System.out.println(language);
}
}
}
Output:
Java
Python
JavaScript
The loop assigns each array element to the variable language in turn. Use a traditional for loop when you need an index or more control over which positions are visited.
13. Looping with Conditions
Loops often use comparison and logical operators to decide when to continue. Common operators include <, >, <=, >=, ==, !=, &&, and ||.
int number = 1;
while (number <= 10 && number > 0) {
System.out.println(number);
number++;
}
This loop continues while both conditions are true. Logical conditions are useful when repetition depends on multiple requirements, but they should remain easy to understand and test.
14. The break and continue Statements
break
The break statement immediately terminates the innermost loop in which it appears.
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
System.out.println(i);
}
Output:
1
2
3
4
continue
The continue statement skips the remainder of the current iteration and proceeds to the next iteration according to the loop's control flow.
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
System.out.println(i);
}
Output:
1
2
4
5
Use break when the loop should stop, and use continue when the current item should be skipped but the loop should keep processing later iterations.
15. Infinite Loops
An infinite loop is a loop that continues indefinitely because its termination condition never becomes false or because no exit path is reached. Infinite loops can be intentional in applications that continuously process events, but accidental infinite loops can make a program unresponsive.
Example of an accidental infinite loop
int i = 1;
while (i <= 5) {
System.out.println(i);
// i is never incremented
}
Because i stays equal to 1, the condition remains true. The program keeps printing 1.
Corrected version
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
To avoid accidental infinite loops, verify that each repetition progresses toward termination and that all exit conditions can eventually be met.
16. Common Looping Mistakes
- Off-by-one errors: Using
< when the endpoint should be included, or using <= when it should not.
- Missing updates: Forgetting to increment or otherwise change the control variable.
- Wrong initial value: Starting the loop counter at an unintended value.
- Incorrect condition: Writing a condition that stops too early or never becomes false.
- Extra semicolon: Writing a semicolon directly after a loop header can create an unintended empty loop body.
- Incorrect do-while syntax: Forgetting the required semicolon after the condition.
- Confusing break and continue: Using continue when the entire loop should stop, or break when only one iteration should be skipped.
- Changing a counter unexpectedly: Modifying a loop variable in several places can make execution difficult to trace.
17. Choosing the Right Loop
| Situation |
Recommended loop |
Reason |
| Print numbers from 1 to 100 |
for |
The counting range is known. |
| Read data while input is available |
while |
Repetition depends on a condition. |
| Display a menu at least once |
do-while |
The body should execute before the first condition check. |
| Visit each array element |
Enhanced for |
It provides simple element-by-element traversal. |
| Print rows and columns of a grid |
Nested loops |
One loop manages rows and another manages columns. |
18. Practical Example: Calculate the Sum of Numbers
A common beginner programming exercise is calculating the sum of numbers from 1 through a given limit.
public class SumExample {
public static void main(String[] args) {
int limit = 5;
int sum = 0;
for (int i = 1; i <= limit; i++) {
sum += i;
}
System.out.println("Sum: " + sum);
}
}
Output:
Sum: 15
Explanation: The variable sum begins at zero. Each iteration adds the current value of i to the running total. After processing 1, 2, 3, 4, and 5, the final sum is 15.
19. Practical Example: Multiplication Table
Loops are useful for generating multiplication tables without writing each calculation separately.
public class MultiplicationTable {
public static void main(String[] args) {
int number = 7;
for (int i = 1; i <= 10; i++) {
System.out.println(number + " x " + i + " = " + (number * i));
}
}
}
Output:
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
20. Best Practices for Looping and Iteration
- Choose a loop type that matches the task.
- Use descriptive variable names when they improve readability.
- Make the stopping condition clear and easy to verify.
- Ensure the loop makes progress toward termination.
- Use braces around loop bodies, even when the body contains only one statement.
- Avoid changing the same loop-control variable in multiple places unless necessary.
- Test boundary values, including zero iterations and the final expected iteration.
- Use enhanced for loops when you simply need to process every element in an array or iterable.
- Use break and continue only when they make the control flow easier to understand.
- Keep nested loops as simple as possible and consider performance when processing large data sets.
21. Practice Exercises
Exercise 1: Print Numbers
Write a Java program that prints numbers from 1 to 20 using a for loop.
Exercise 2: Even Numbers
Use a while loop to print all even numbers between 2 and 30.
Exercise 3: Reverse Countdown
Use a do-while loop to print numbers from 10 down to 1.
Exercise 4: Sum of Even Numbers
Calculate the sum of all even numbers from 1 to 100 using a loop.
Exercise 5: Factorial
Write a program that calculates the factorial of a non-negative integer using iteration. Consider how the program should handle negative input.
Exercise 6: Array Traversal
Create an integer array and use an enhanced for loop to display every element.
Exercise 7: Number Pattern
Use nested loops to print a triangle of asterisks with five rows.
Exercise 8: Skip a Value
Print numbers from 1 to 10 but skip 5 using the continue statement.
22. Interview Questions and Answers
Q1. What is looping in Java?
Looping is the repeated execution of a statement or block of statements according to a condition or iteration rule.
Q2. What is an iteration?
An iteration is one execution of a loop body.
Q3. Which primary loop statements does Java provide?
Java provides the for, while, and do-while loops. It also provides the enhanced for loop for convenient traversal of arrays and iterable objects.
Q4. What is the difference between for and while loops?
A for loop places initialization, condition, and update in one header, making it convenient for counter-based repetition. A while loop is often used when repetition depends primarily on a condition.
Q5. Why does a do-while loop execute at least once?
Its condition is checked after the body executes, so the first iteration happens regardless of the initial condition's value.
Q6. What is an infinite loop?
An infinite loop is a loop that does not terminate under its current execution conditions.
Q7. What is a nested loop?
A nested loop is a loop placed inside another loop. The inner loop can execute multiple times for every outer-loop iteration.
Q8. What is the difference between break and continue?
Break exits the innermost loop, while continue skips the remainder of the current iteration and moves to the next iteration.
Q9. What is an enhanced for loop?
An enhanced for loop traverses elements of an array or an object implementing Iterable without requiring an explicit index variable.
Q10. What is an off-by-one error?
An off-by-one error occurs when a loop executes one too many or one too few times, often because its starting value or boundary condition is incorrect.
23. Quick Revision Checklist
- Understand the difference between looping and iteration.
- Know the purpose of initialization, condition, update, and loop body.
- Understand how for, while, and do-while loops differ.
- Remember that while and for loops check their conditions before the body.
- Remember that a do-while loop executes its body at least once.
- Know how to iterate through arrays with an enhanced for loop.
- Understand nested loops, break, and continue.
- Recognize off-by-one errors and accidental infinite loops.
- Practice sums, multiplication tables, countdowns, and number patterns.
24. Conclusion
Looping and iteration allow Java programs to repeat operations efficiently without duplicating code. The for loop is especially useful for counter-based tasks, the while loop is appropriate when repetition depends on a condition, and the do-while loop is useful when the body must execute at least once. The enhanced for loop makes traversing arrays and iterable objects straightforward.
By practicing loop conditions, control variables, nested loops, and termination logic, you can build a strong foundation for arrays, collections, algorithms, and more advanced Core Java programming.
Continue learning: Explore the Core Java Training Course, register for a course demo, or visit the JustAcademy homepage.
Official Java reference: Oracle Java Tutorial: Control Flow Statements.