Understanding Loops in Java Programming

Loops are a fundamental concept in programming, allowing you to repeat a block of code multiple times. In this article, we’ll explore two types of loops in Java: while and do…while loops.

What is a While Loop?

A while loop in Java is used to execute a specific code block until a certain condition is met. The syntax of a while loop is as follows:

java
while (textExpression) {
// code to be executed
}

Here’s how it works:

  1. The textExpression inside the parentheses is evaluated.
  2. If the textExpression evaluates to true, the code inside the while loop is executed.
  3. The textExpression is evaluated again.
  4. This process continues until the textExpression evaluates to false.
  5. When the textExpression evaluates to false, the loop stops.

Flowchart of While Loop

To better understand the while loop, let’s look at its flowchart.

Example 1: Display Numbers from 1 to 5

Here’s an example of using a while loop to display numbers from 1 to 5:
java
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}

This will output:


1
2
3
4
5

Java do…while Loop

A do…while loop in Java is similar to a while loop, but with one key difference: the body of the loop is executed once before the test expression is checked.

The syntax of a do…while loop is as follows:
java
do {
// code to be executed
} while (textExpression);

Here’s how it works:

  1. The body of the loop is executed at first.
  2. The textExpression is evaluated.
  3. If the textExpression evaluates to true, the body of the loop is executed again.
  4. The textExpression is evaluated once again.
  5. If the textExpression evaluates to true, the body of the loop is executed again.
  6. This process continues until the textExpression evaluates to false.

Flowchart of do…while Loop

To better understand the do…while loop, let’s look at its flowchart.

Example 3: Display Numbers from 1 to 5

Here’s an example of using a do…while loop to display numbers from 1 to 5:
java
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);

This will output:


1
2
3
4
5

Infinite Loops

If the condition of a loop is always true, the loop will run indefinitely. Here’s an example of an infinite while loop:
java
while (true) {
System.out.println("Hello");
}

And here’s an example of an infinite do…while loop:
java
do {
System.out.println("Hello");
} while (true);

Java for vs while loop

When should you use a for loop versus a while or do…while loop?

Use a for loop when the number of iterations is known. For example:
java
for (int i = 0; i < 10; i++) {
System.out.println(i);
}

Use a while or do…while loop when the number of iterations is unknown. For example:
java
int i = 0;
while (i < 10) {
System.out.println(i);
i++;
}

Leave a Reply

Your email address will not be published. Required fields are marked *