The do-while
loop in Java is similar to the while
loop, but with a key difference: the do-while
loop guarantees that the code block will execute at least once, even if the condition is initially false. This is because the condition is evaluated after the code block is executed.
Syntax of Do/While Loop
do {
// Code block to be executed
} while (condition);
do
: The block of code inside thedo
statement is executed first, before the condition is tested.while (condition)
: After executing the block, the condition is checked. If it’s true, the code block will be executed again. If false, the loop terminates.
Basic Example of Do/While Loop
Here’s a simple example that prints the numbers from 1 to 5 using the do-while
loop:
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
In this example, the loop will print the numbers from 1 to 5. The condition i <= 5
is checked after the code block is executed, ensuring that the code runs at least once.
How the Do/While Loop Works:
- Code Execution: The code inside the
do
block is executed first. - Condition Check: After the code execution, the condition in the
while
statement is checked. - If the condition is true, the loop repeats.
- If the condition is false, the loop stops.
Difference Between While and Do/While Loop
The main difference between a while
loop and a do-while
loop is when the condition is checked:
- In a
while
loop, the condition is checked before executing the code. - In a
do-while
loop, the condition is checked after the code block is executed, ensuring the code runs at least once.
Example of While vs Do/While Loop
// While loop example
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
// Do-While loop example
int j = 1;
do {
System.out.println(j);
j++;
} while (j <= 5);
Both loops will output the same result, but the do-while
loop guarantees that the code executes once even if the condition is false.
Infinite Do/While Loop
If the condition in a do-while
loop is always true, it will create an infinite loop.
public class InfiniteDoWhile {
public static void main(String[] args) {
do {
System.out.println("This will print forever!");
} while (true);
}
}
Output:
This will print forever!
This will print forever!
...
To stop the loop, you would need to manually interrupt the program, such as by using Ctrl + C in the terminal.
Using break
and continue
in Do/While Loop
You can also use break
and continue
in a do-while
loop to control its execution:
break
: Exits the loop immediately, regardless of the condition.continue
: Skips the current iteration and moves to the next iteration.
Example with break
public class BreakExample {
public static void main(String[] args) {
int i = 1;
do {
if (i == 3) {
break; // Exits the loop when i is 3
}
System.out.println(i);
i++;
} while (i <= 5);
}
}
Output:
1
2
Example with continue
public class ContinueExample {
public static void main(String[] args) {
int i = 1;
do {
i++;
if (i == 3) {
continue; // Skips printing 3
}
System.out.println(i);
} while (i <= 5);
}
}
Output:
2
4
5
Real-Life Example: Input Validation with Do/While Loop
A practical use of the do-while
loop is to repeatedly ask for user input until it meets a certain condition, such as ensuring that the input is a positive number.
import java.util.Scanner;
public class InputValidation {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int userInput;
do {
System.out.println("Enter a positive number:");
userInput = sc.nextInt();
} while (userInput <= 0);
System.out.println("You entered a valid positive number: " + userInput);
sc.close();
}
}
Output:
Enter a positive number:
-5
Enter a positive number:
0
Enter a positive number:
10
You entered a valid positive number: 10
In this example, the loop keeps asking the user for input until a positive number is provided.
Key Points to Remember About Do/While Loop
- The
do-while
loop guarantees that the block of code runs at least once, even if the condition is false initially. - It is ideal for situations where you need to ensure the code executes before checking the condition.
- Be cautious of infinite loops, which occur when the condition always evaluates to true.
- Use
break
to exit the loop prematurely andcontinue
to skip an iteration.
The do-while
loop is a useful tool for situations where the code must be executed at least once, and its flexibility with condition checking makes it a valuable part of your Java programming toolkit.
For more insights and practical coding tips, visit Master Coding Science at mastercodingscience.com.