Nearby lessons

24 of 125

Java - 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)

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

while and do-while

Example01
JCode Cell
1while (condition) { // check first, then run
2 // body
3}
4 
5do { // run first, then check
6 // body
7} while (condition);

while and do-while

Difference: do-while runs the body at least once even if the condition is false from the start. while may run zero times.

In simple words: `while` checks the condition before running the body, but `do-while` runs the body once and then checks. That is why do-while always runs at least once, even when the condition is false from the start.
Example02
JCode Cell
1class WhileDemo {
2 public static void main(String[] args) {
3 int i = 1;
4 while (i <= 3) {
5 System.out.println("while: " + i);
6 i++;
7 }
8 int j = 1;
9 do {
10 System.out.println("do-while: " + j);
11 j++;
12 } while (j <= 3);
13 }
14}
Output
while: 1 while: 2 while: 3 do-while: 1 do-while: 2 do-while: 3
📝 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