Java Do-While Loop Basics and Syntax

🚀 Java Learning – Day 11 Do-While Loop in Java In while loop, condition is checked first. But in do-while loop, the code executes at least once, even if the condition is false. That’s why it is called an exit-controlled loop 💡 💻 Syntax do { // code to repeat } while(condition); 💻 Example Program class Test { public static void main(String[] args) { int i = 1; do { System.out.println(i); i++; } while(i <= 5); } } 🔍 Line-by-Line Explanation 🔹 int i = 1; → Initializes variable 🔹 do { } → Code inside runs first 🔹 System.out.println(i); → Prints value 🔹 i++; → Increments value 🔹 while(i <= 5); → Condition checked after execution 🔹 Loop repeats until condition becomes false ✅ Output 1 2 3 4 5 📝 Important Notes • Do-while loop executes at least once • Condition is checked after loop body • Useful in menu-driven programs • Ends with a semicolon (;) after while condition 🎯 Interview One-Line Answer Do-while loop in Java executes a block of code at least once, and then repeats based on a condition. 💬 Engagement Question If the condition is false at the beginning, how many times will a do-while loop execute? Comment your answer 👇 📌 Follow me to learn Java from Basics to Advanced daily 🚀

To view or add a comment, sign in

Explore content categories