Nearby lessons

25 of 125

Java - do-while Loop

📌 What You Will Learn
  • The small building blocks of Java: tokens
  • All 8 primitive data types with their ranges
  • Type casting — implicit and explicit
  • Control statements: if, switch, loops
  • Arrays — single, double and jagged
  • Variable length arguments (var-args)

do-while Loop is a core concept of the Java language. This lesson explains while vs do-while — The Classic Question with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

while vs do-while — The Classic Question

Pointwhiledo-while
Checks the conditionBefore running the bodyAfter running the body
Body runs at least once?Not guaranteed (may run 0 times)Always at least once
Use whenYou are not sure how many timesThe body must run at least once
Example01
JCode Cell
1class WhileVsDoWhile {
2 public static void main(String[] args) {
3 int a = 5;
4 while (a < 3) { System.out.println("while runs"); } // never prints
5 
6 int b = 5;
7 do { System.out.println("do-while runs once"); } while (b < 3); // prints once
8 }
9}
Output
do-while runs once
📝 Key Takeaways
  • Tokens are the smallest pieces of a program: identifiers, literals, keywords, operators, separators.
  • Java has 8 primitive types: byte, short, int, long, float, double, char, boolean.
  • Widening casting is automatic and safe; narrowing casting needs brackets and may lose data.
  • if / switch decide which path runs; for / while / do-while repeat code; break and continue control loops.
  • Arrays hold many same-type values; index starts at 0; size is fixed; for-each loop reads them simply.
  • Var-args (int... x) lets a method take any number of arguments.

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1