What is the purpose of a `while` loop in Java?
A
To execute a block once B
To make decisions C
To repeat a block while a condition is true D
To store values
Analysis & Theory
`while` loops repeat the enclosed code block as long as the given condition is true.
Which of the following is the correct syntax of a `while` loop?
A
while x > 0 { } B
while(x > 0) { } C
while x > 0: { } D
while(x > 0); { }
Analysis & Theory
Correct syntax: `while(condition) { // code }`.
What is the output?
```java
int x = 0;
while(x < 3) {
System.out.print(x);
x++;
}```
A
012 B
123 C
0123 D
Error
Analysis & Theory
`x` starts at 0 and prints 0, 1, 2 before stopping when `x == 3`.
What happens if the condition in `while` is never false?
A
The loop runs once B
It causes a compile error C
It creates an infinite loop D
It exits automatically
Analysis & Theory
If the condition never becomes false, the loop continues forever.
Which keyword can be used to exit a `while` loop early?
A
exit B
stop C
break D
return
Analysis & Theory
`break` is used to immediately exit a loop.
What is the output?
```java
int i = 5;
while(i > 0) {
i--;
}
System.out.print(i);```
A
5 B
4 C
0 D
-1
Analysis & Theory
Loop runs while `i > 0`, reducing `i` to 0, then prints 0.
Which of the following causes an infinite loop?
A
while(false) { } B
while(true) { } C
while(i > 0) { i--; } D
while(i < 10) { i++; }
Analysis & Theory
`while(true)` runs forever unless there's a `break` or `return`.
Can a `while` loop have a body with no statements?
A
No B
Yes, using semicolon C
Only if condition is false D
Only in for-loops
Analysis & Theory
Yes, an empty loop is valid: `while(condition);`
What is printed?
```java
int i = 1;
while(i < 1) {
System.out.print(i);
}```
A
1 B
0 C
Nothing D
Error
Analysis & Theory
Since `i < 1` is false at the start, the loop body never runs.
Which loop is guaranteed to run at least once?
A
while B
for C
do-while D
switch
Analysis & Theory
`do-while` always executes the loop body at least once, unlike `while`.