while Loop
The while loop in Java is a control flow statement used to execute a block of code repeatedly as long as a given condition remains true. It is best suited when the number of iterations is not known in advance. This loop is widely used in input-driven logic, polling, and condition-controlled execution.
What Is a while Loop?
- Executes code while a condition is true
- Condition is evaluated before each iteration
- Loop may execute zero or more times
Basic Syntax
while (condition) {
// code to execute
}
Simple Example
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
Output:
1
2
3
4
5
Execution Flow of while Loop
- Condition is evaluated
- If condition is true, loop body executes
- Loop variable is updated
- Control returns to condition check
- Loop stops when condition becomes false
while Loop with Decrement
int i = 5;
while (i > 0) {
System.out.println(i);
i--;
}
Infinite while Loop
while (true) {
System.out.println("Infinite loop");
}
Use case: Server listeners, background processes (with break conditions).
while Loop with break
while (true) {
if (conditionMet) {
break;
}
}
while Loop with continue
int i = 0;
while (i < 5) {
i++;
if (i == 3) {
continue;
}
System.out.println(i);
}
Nested while Loop
int i = 1;
while (i <= 3) {
int j = 1;
while (j <= 2) {
System.out.println(i + "," + j);
j++;
}
i++;
}
Common Use Cases
- Reading user input
- Polling conditions
- Iterating until a condition is met
- File reading, network checks
while vs for Loop
| Feature | while | for |
|---|---|---|
| Condition Check | Before loop | Before loop |
| Iterations Known | Usually no | Usually yes |
| Structure | Simple | Compact |
| Use Case | Condition-based | Count-based |
Common Beginner Mistakes
- Forgetting to update loop variable (infinite loop)
- Using wrong condition
- Confusing while with do-while
- Overcomplicating loop logic
Interview-Ready Answers
Short Answer
The while loop executes a block of code repeatedly as long as the condition is true.
Detailed Answer
In Java, the while loop evaluates a condition before each iteration and executes the loop body only when the condition is true. It is best used when the number of iterations is not predetermined.
while Loop Examples
1. Basic while Loop (Print 1 to 5)
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
Explanation
- Initializes
ibefore the loop. - Loop runs while condition is true.
- Output: 1 2 3 4 5
2. while Loop Printing Even Numbers
int i = 1;
while (i <= 10) {
if (i % 2 == 0) {
System.out.println(i);
}
i++;
}
Explanation
- Checks even condition inside the loop.
- Output: 2 4 6 8 10
3. while Loop Printing Odd Numbers
int i = 1;
while (i <= 10) {
if (i % 2 != 0) {
System.out.println(i);
}
i++;
}
Explanation
- Prints only odd numbers.
- Output: 1 3 5 7 9
4. Reverse while Loop
int i = 5;
while (i >= 1) {
System.out.println(i);
i--;
}
Explanation
- Loop runs backward.
- Output: 5 4 3 2 1
5. while Loop with break
int i = 1;
while (i <= 5) {
if (i == 3) {
break;
}
System.out.println(i);
i++;
}
Explanation
- Loop terminates when
i == 3. - Output: 1 2
6. while Loop with continue
int i = 0;
while (i < 5) {
i++;
if (i == 3) {
continue;
}
System.out.println(i);
}
Explanation
- Skips only iteration where
i == 3. - Output: 1 2 4 5
7. Infinite while Loop (Controlled with break)
while (true) {
System.out.println("Running");
break;
}
Explanation
- Condition is always true.
breakis mandatory to stop execution.
8. while Loop for Array Traversal
int[] nums = {10, 20, 30};
int i = 0;
while (i < nums.length) {
System.out.println(nums[i]);
i++;
}
Explanation
- Uses index to traverse array.
- Output: 10 20 30
9. while Loop with Enhanced Logic (Skip Negatives)
int[] nums = {5, -2, 8, -1, 10};
int i = 0;
while (i < nums.length) {
if (nums[i] < 0) {
i++;
continue;
}
System.out.println(nums[i]);
i++;
}
Explanation
- Skips negative numbers.
- Output: 5 8 10
10. while Loop for Summation
int i = 1;
int sum = 0;
while (i <= 5) {
sum += i;
i++;
}
System.out.println(sum);
Explanation
- Accumulates sum of numbers.
- Output: 15
11. while Loop for Factorial Calculation
int num = 5;
int fact = 1;
while (num > 0) {
fact *= num;
num--;
}
System.out.println(fact);
Explanation
- Calculates factorial.
- Output: 120
12. while Loop for String Traversal
String s = "JAVA";
int i = 0;
while (i < s.length()) {
System.out.println(s.charAt(i));
i++;
}
Explanation
- Iterates over each character.
- Output:
J
A
V
A
13. while Loop for Digit Extraction
int num = 1234;
while (num > 0) {
System.out.println(num % 10);
num /= 10;
}
Explanation
- Extracts digits from right to left.
- Output: 4 3 2 1
14. while Loop for Palindrome Check
int num = 121;
int temp = num;
int rev = 0;
while (temp > 0) {
rev = rev * 10 + temp % 10;
temp /= 10;
}
System.out.println(num == rev);
Explanation
- Reverses number using while.
- Output: true
15. Nested while Loop
int i = 1;
while (i <= 3) {
int j = 1;
while (j <= 3) {
System.out.println("i=" + i + ", j=" + j);
j++;
}
i++;
}
Explanation
- Inner loop completes fully for each outer loop.
- Used in matrix/grid logic.
16. while Loop with Boolean Flag
int i = 1;
boolean found = false;
while (i <= 5) {
if (i == 4) {
found = true;
break;
}
i++;
}
System.out.println(found);
Explanation
- Flag stores result after loop.
- Output: true
17. while Loop for User Validation (Simulation)
int attempts = 0;
while (attempts < 3) {
System.out.println("Trying login");
attempts++;
}
Explanation
- Limits attempts.
- Common real-world pattern.
18. while Loop to Skip Blank Values
String[] data = {"A", "", "B", "", "C"};
int i = 0;
while (i < data.length) {
if (data[i].isEmpty()) {
i++;
continue;
}
System.out.println(data[i]);
i++;
}
Explanation
- Skips empty strings.
- Output: A B C
19. while Loop with Decrement Logic
int i = 10;
while (i > 0) {
System.out.println(i);
i -= 2;
}
Explanation
- Decreases by 2 each iteration.
- Output: 10 8 6 4 2
20. Interview Summary Example
int i = 1;
while (i <= 3) {
System.out.println(i);
i++;
}
Explanation
- Demonstrates:
- Initialization outside loop
- Condition check
- Increment inside loop
- Very common interview question.
Key Takeaway
The while loop is ideal for condition-controlled execution. Correct management of the loop condition and updates is crucial to avoid infinite loops.