1. What is the primary function of the while loop in Java?
Answer:
Explanation:
The while loop in Java is used to loop through a block of code repeatedly, as long as a specified condition remains true【95†source】.
2. In a while loop, when is the condition checked?
Answer:
Explanation:
In a while loop, the condition is checked before the execution of the code block within the loop【95†source】.
3. How does a do/while loop differ from a while loop?
Answer:
Explanation:
The do/while loop differs from a while loop in that it executes the code block once before checking the condition, ensuring the code block is executed at least once【96†source】.
4. What is the syntax to increment a counter variable in a while loop?
Answer:
Explanation:
Commonly, 'i++' is used within a while loop to increment a counter variable, although 'i += 1' or '++i' are also valid.
5. In a do/while loop, where is the condition written?
Answer:
Explanation:
In a do/while loop, the condition is written after the while keyword, following the code block enclosed in the do block【96†source】.
6. What is the risk of not updating the loop variable in a while loop?
Answer:
Explanation:
If the loop variable is not updated within a while loop, it may result in an infinite loop as the condition might never become false【95†source】.
7. Can a while loop be used to iterate over an array?
Answer:
Explanation:
A while loop can iterate over an array by using an index variable to access each element in sequence.
8. What will be the output of the following code?
int i = 0;
while (i < 3) {
System.out.println(i);
i++;
}
Answer:
Explanation:
The while loop will print the values 0, 1, and 2, as it increments 'i' from 0 to 2 and stops when 'i' becomes 3【95†source】.
9. In a do/while loop, is the condition checked during the first iteration?
Answer:
Explanation:
In a do/while loop, the condition is checked after the first execution of the code block, ensuring the code block runs at least once【96†source】.
10. What is a common use case for a do/while loop?
Answer:
Explanation:
A do/while loop is typically used when the code block needs to be executed at least once, even if the loop condition is false at the start​“【oaicite:3】“​.
11. Which loop is guaranteed to execute its code block at least once?
Answer:
Explanation:
The do/while loop is guaranteed to execute its code block at least once because the condition is checked after the execution of the code block​“【oaicite:2】“​.
12. How can an infinite loop be created using a while loop?
Answer:
Explanation:
An infinite loop can occur in a while loop if the condition is set in such a way that it always evaluates to true, and there's no mechanism within the loop to break out of it​“【oaicite:1】“​.