Java Programming - Lesson 6

Java Loops for Beginners: While, Do-While, For Loops and Break

Introduction

Imagine writing a programme that needs to display the numbers from one to one hundred.

One approach would be to write one hundred separate print statements. However, that would make the programme unnecessarily long, difficult to maintain and inefficient to develop.

Fortunately, Java provides a powerful programming feature called a loop.

A loop allows a programme to execute a block of instructions repeatedly, either while a condition remains true or until a particular condition is satisfied.

Loops are essential in programming because they help automate repetitive tasks, process collections of data, validate user input and control how programmes operate.

In this tutorial, you will learn about the three traditional looping statements in Java:

while

do-while

for

You will also learn about variable scope, infinite loops and the break statement.

Let's begin!

1. What Is a Loop in Java?

A loop is a control structure that allows a programme to execute the same block of code repeatedly.

For example, suppose we want to display the message:

Welcome to Java Programming!


five times.

Without a loop, we could write:

System.out.println("Welcome to Java Programming!");

System.out.println("Welcome to Java Programming!");

System.out.println("Welcome to Java Programming!");

System.out.println("Welcome to Java Programming!");

System.out.println("Welcome to Java Programming!");


This works, but it involves unnecessary repetition.

Using a loop, we can achieve the same result more efficiently:

for (int i = 0; i < 5; i++) {

    System.out.println("Welcome to Java Programming!");

}


The message is displayed five times, but the code is much shorter and easier to maintain.

This illustrates one of the major benefits of loops: they allow us to repeat instructions without repeatedly writing the same code.

2. The While Loop

The while loop executes a block of code as long as its condition evaluates to true.

Syntax

while (condition) {

    // Statements to execute

}


Before each execution of the loop body, Java evaluates the condition.

If the condition is true, the statements execute.

If the condition is false, the loop terminates, and programme execution continues after the loop.

Example: Counting from Zero to Nine

public class WhileExample {


    public static void main(String[] args) {


        int a = 0;


        while (a < 10) {

            System.out.println("A is " + a);

            a++;

        }


        System.out.println("Finished the loop");

    }

}


Output

A is 0

A is 1

A is 2

A is 3

A is 4

A is 5

A is 6

A is 7

A is 8

A is 9

Finished the loop


Understanding the Code

Let's examine the important statements.

Step 1: Initialise the variable.

int a = 0;


The variable a starts with a value of zero.

Step 2: Check the condition.

while (a < 10)


The loop continues while a is less than ten.

Step 3: Execute the loop body.

System.out.println("A is " + a);


The current value of a is displayed.

Step 4: Update the variable.

a++;


The value of a increases by one.

The process repeats until a becomes ten.

At that point, the condition a < 10 becomes false, so Java exits the loop.

Important Lesson

A while loop may execute zero times.

Consider:

int a = 10;


while (a < 10) {

    System.out.println("This message will not appear.");

}


Because a is already ten, the condition is false before the loop begins.

Consequently, the message is never displayed.

This behaviour makes the while loop useful when the programme must check a condition before deciding whether to perform an operation.

3. The Do-While Loop

The do-while loop is similar to the while loop, but the order of execution is different.

A while loop checks its condition before executing the body.

A do-while loop executes its body first and checks the condition afterwards.

Syntax

do {

    // Statements to execute

} while (condition);


Notice the semicolon after the closing parenthesis.

Example

public class DoWhileExample {


    public static void main(String[] args) {


        int a = 10;


        do {

            System.out.println("A is " + a);

            a++;

        } while (a < 10);


        System.out.println("Finished the do-while loop");

    }

}


Output

A is 10

Finished the do-while loop


Why does the message appear even though the condition is false?

The reason is that Java executes the body of a do-while loop before evaluating its condition.

The programme prints the value ten, increases a to eleven and then checks whether a is less than ten.

Since the condition is false, the loop terminates.

Nevertheless, its body has already executed once.

When Should You Use a Do-While Loop?

A do-while loop is useful when an operation must happen at least once.

For example, consider a programme that displays a menu:

int choice;


do {

    System.out.println("1. View Profile");

    System.out.println("2. Settings");

    System.out.println("3. Exit");


    // In a complete application, obtain the user's choice here.


    choice = 3;


} while (choice != 3);


In this simplified example, the menu is displayed before the condition is checked. The loop then stops because the choice is three.

In a real application, the programme would obtain the user's choice through an input mechanism.

4. The For Loop

The for loop is especially useful when we know how to initialise a counting variable, what condition should control repetition and how the variable should change after each repetition.

Syntax

for (initialisation; condition; update) {

    // Statements to execute

}


The three sections have distinct purposes.

Initialisation: Establishes the starting state, often by declaring and initialising a counter.

Condition: Determines whether the loop should continue.

Update: Changes the counter or another variable after each execution of the loop body.

Example: Counting from Zero to Nine

public class ForExample {


    public static void main(String[] args) {


        for (int x = 0; x < 10; x++) {

            System.out.println("X is " + x);

        }


        System.out.println("Finished the for loop");

    }

}


Output

X is 0

X is 1

X is 2

X is 3

X is 4

X is 5

X is 6

X is 7

X is 8

X is 9

Finished the for loop


How the For Loop Works

Consider the loop statement:

for (int x = 0; x < 10; x++)


The execution proceeds as follows:

Java initialises x to zero.

Java checks whether x < 10.

If the condition is true, the loop body executes.

Java executes x++.

Java checks the condition again.

The process continues until the condition becomes false.

When x becomes ten, the condition fails, and the loop terminates.

Unlike a while loop, the for loop places the initialisation, condition and update expressions together, making it particularly convenient for counting operations.

5. Understanding Variable Scope in a For Loop

Variable scope determines where a variable can be accessed in a programme.

Consider:

for (int x = 0; x < 5; x++) {

    System.out.println(x);

}


The variable x is declared in the initialisation section of the for loop.

Its scope is limited to the loop statement and its body.

Therefore, this code is invalid:

for (int x = 0; x < 5; x++) {

    System.out.println(x);

}


System.out.println(x);


The last statement produces a compilation error because x is not accessible outside the loop.

If we need to access the variable after the loop, we can declare it before the loop:

int x;


for (x = 0; x < 5; x++) {

    System.out.println(x);

}


System.out.println("Final value: " + x);


Output:

0

1

2

3

4

Final value: 5


The variable remains accessible because it was declared outside the loop.

This is an important concept when developing programmes with multiple control structures.

6. Omitting Sections of a For Loop

Java allows us to omit the initialisation and update expressions of a for loop.

For example:

int a = 10;


for (; a < 15; ) {

    System.out.println(a);

    a++;

}


Output:

10

11

12

13

14


The first section is empty because a has already been initialised.

The third section is also empty because the variable is updated inside the loop body.

This example is similar to:

int a = 10;


while (a < 15) {

    System.out.println(a);

    a++;

}


Both versions perform the same task.

Although the flexibility of the for loop can be useful, beginners should generally use the most readable structure for each situation.

7. Infinite Loops

An infinite loop is a loop that continues indefinitely unless something causes it to terminate.

One way to create an infinite loop in Java is:

for (;;) {

    System.out.println("Running...");

}


The three sections of the for loop are empty.

When the condition section is omitted, Java treats it as true.

Therefore, the loop has no built-in condition that causes it to stop.

Another example is:

while (true) {

    System.out.println("Running...");

}


Both examples create loops that continue until the programme is otherwise interrupted or the loop exits through a control statement.

Infinite loops can be appropriate in continuously running applications, but they must be designed carefully.

A Common Beginner's Mistake

Consider:

int a = 0;


while (a < 5) {

    System.out.println(a);

}


This programme creates an unintended infinite loop because the value of a never changes.

The condition remains true, so the programme repeatedly prints zero.

A correct version would be:

int a = 0;


while (a < 5) {

    System.out.println(a);

    a++;

}


Always ensure that a loop's condition can eventually become false unless you deliberately design an infinite loop with an appropriate exit mechanism.

8. The Break Statement

Java provides a control statement called break.

When executed inside a loop, break immediately terminates that loop.

Programme execution then continues with the statement following the loop.

Example

public class BreakExample {


    public static void main(String[] args) {


        int a = 20;


        for (;;) {


            System.out.println("A is " + a);


            if (a > 25) {

                break;

            }


            a++;

        }


        System.out.println("Finished the loop");

    }

}


Output

A is 20

A is 21

A is 22

A is 23

A is 24

A is 25

A is 26

Finished the loop


Understanding the Example

The loop starts with a equal to twenty.

It prints the value of a before checking whether the value is greater than twenty-five.

When a reaches twenty-six, the programme prints it and evaluates:

if (a > 25)


The condition is true, so Java executes:

break;


The loop terminates immediately.

The final message is then displayed.

Remember: The position of the break statement matters. Since the example prints a before checking the condition, twenty-six appears in the output.

If we moved the condition check before the print statement, the result would be different.

9. Comparing Java's Three Traditional Loops

Although the three loop structures all allow repetition, their behaviour and typical uses differ.

Feature

while

do-while

for

Condition checked

Before the body

After the body

Before each iteration

Guaranteed to execute at least once?

No

Yes

No

Initialisation included in loop syntax?

No dedicated section

No dedicated section

Yes

Update included in loop syntax?

No dedicated section

No dedicated section

Yes

Suitable for counting?

Yes

Yes

Often convenient

Suitable when the body must execute once before checking?

No

Yes

No


The most appropriate loop depends on the problem you are trying to solve.

Use a while loop when repetition depends on a condition that should be checked first.

Use a do-while loop when the body must execute at least once.

Use a for loop when initialisation, a continuation condition and an update expression can be expressed clearly together.

10. Practical Exercises

The best way to master loops is to practise writing your own programmes.

Try these exercises using NetBeans or another Java development environment.

Exercise 1: Counting with a While Loop

Write a programme that displays the numbers from one to ten using a while loop.

Exercise 2: Counting with a Do-While Loop

Write a programme that displays the numbers from ten down to one using a do-while loop.

Exercise 3: Using a For Loop

Write a programme that displays the first ten positive even numbers using a for loop.

Exercise 4: Calculating a Total

Use a loop to calculate the sum of the integers from one to one hundred.

Your programme should display the final total.

Exercise 5: Using Break

Write a loop that counts from one upwards but stops when the counter reaches seven.

Experiment with placing the break statement before and after the print statement. Observe how the output changes.

Exercise 6: Avoiding Infinite Loops

Examine the following code:

int counter = 1;


while (counter <= 5) {

    System.out.println(counter);

}


Identify the problem and correct the code so that it displays the numbers one through five and terminates.

Conclusion

Loops are essential tools in Java programming because they allow us to automate repetitive tasks and write more efficient code.

In this tutorial, we explored the while, do-while and for loops. We also learned about variable scope, omitted loop sections, infinite loops and the break statement.

The most important distinction to remember is that a while loop checks its condition before executing the body, whereas a do-while loop checks the condition after executing the body.

The for loop offers a convenient structure for combining initialisation, a condition and an update expression.

As you continue learning Java, practise using these loops in different situations. Experiment with their conditions, observe their outputs and learn how to control repetition effectively.

With regular practice, you will become more confident in writing programmes that are concise, logical and efficient.

Watch the accompanying video tutorial via the link below:

https://youtu.be/MYvO3JC54zU?si=ceVTTD0GLghZIRre 

Creative Skills & Hobbies Hub – Where Creativity, Knowledge, and Inspiration Thrive!


Comments

Popular Posts