Scenario 1: Loop Execution
Interview Question
How does the while loop decide whether to execute its block of code?
Answer:
The while loop checks the condition before each iteration. If the condition is true, the loop body executes; if false, the loop stops immediately.
Tip: while is an entry-controlled loop condition is checked first.
Scenario 2: Infinite Loop
A student writes
int i = 1;
while(i <= 5) {
System.out.println(i);
}
Interview Question
What will happen when this program runs, and why?
Answer:
It will cause an infinite loop because i is never incremented inside the loop. The condition i <= 5 will always remain true.
Tip: Always ensure the loop variable changes, or else the loop may never end.
Scenario 3: Loop Initialization
Interview Question
Where should you initialize the variable and how should you update it?
Answer:
The variable must be initialized before the loop starts, and updated inside the loop. Example:
int num = 10;
while(num >= 1) {
System.out.println(num);
num--;
}
Tip: Initialize before the loop, update inside the loop.
Scenario 4: Condition Check
You want to print "Java is fun" at least once, even if the condition is false.
Interview Question
Which loop would you choose instead of while, and why?
Answer:
I would use a do-while loop because it executes the body at least once before checking the condition.
Tip: Use do-while if you need at least one execution.
Scenario 5: Real-life Example
You are building a login system where a user has 3 attempts to enter the correct password.
Interview Question
How can a while loop be useful in this case?
Answer:
A while loop can keep asking for the password while attempts are less than 3 and the input is wrong. Once either condition fails, the loop stops.
Tip: While loops are useful when the number of iterations is not fixed.