Java Do…While Loop

🔄 Java Do…While Loop

The do...while loop is similar to the while loop, but with one important difference:

👉 The code block executes at least once, even if the condition is false, because the condition is checked after the loop executes.


Syntax

do {
// code to execute
} while (condition);

📌 Note: A semicolon ; is required after the condition.


📘 Example 1: Basic do…while Loop

public class Main {
public static void main(String[] args) {
int i = 1;

do {
System.out.println(i);
i++;
} while (i <= 5);
}
}

📌 Output:

1
2
3
4
5

📘 Example 2: Condition False at First

Even when the condition is false, the block executes once:

public class Main {
public static void main(String[] args) {
int i = 10;

do {
System.out.println("This will print at least once!");
} while (i < 5);
}
}

📌 Output:

This will print at least once!

📘 Example 3: User Input Loop (Practical Use Case)

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number;

do {
System.out.print("Enter a number greater than 0: ");
number = input.nextInt();
} while (number <= 0);

System.out.println("Thank you! You entered: " + number);
}
}

📌 This forces input until user enters a valid number.


🔍 Key Difference: while vs do...while

Feature while Loop do...while Loop
Condition checked Before execution After execution
Executes at least once? ❌ No ✅ Yes
Best used when Unsure if loop should run Loop must run at least once

👍 Summary

  • do...while ensures code runs at least one time.

  • Useful for input validation or cases requiring an initial action.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

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