1. What is the basic structure of a for loop in Java?
Answer:
Explanation:
The standard for loop in Java consists of an initialization, a condition, and an update expression, all enclosed in parentheses.
2. Which part of a for loop is executed only once?
Answer:
Explanation:
The initialization part of a for loop is executed only once at the beginning of the loop.
3. What is the For-Each loop primarily used for in Java?
Answer:
Explanation:
The For-Each loop in Java is used to iterate over elements in arrays or collections.
4. What is the syntax of a For-Each loop in Java?
Answer:
Explanation:
The For-Each loop in Java uses the syntax 'for (type var : array)' where 'type' is the data type and 'var' is the variable that iterates over the array or collection.
5. What happens if the condition in a for loop is initially false?
Answer:
Explanation:
If the condition in a for loop is initially false, the loop's body does not execute at all.
6. Which component of a for loop is optional?
Answer:
Explanation:
All components of a for loop (initialization, condition, and update statement) are optional. Omitting the condition can lead to an infinite loop.
7. Can the initialization block of a for loop declare multiple variables?
Answer:
Explanation:
The initialization block of a for loop can declare multiple variables, but they must all be of the same type.
8. In a For-Each loop, is it possible to modify the current element?
Answer:
Explanation:
The For-Each loop does not allow modification of the current element being iterated over. It is typically used for read-only operations.
9. What is the correct way to iterate over an array using a for loop?
Answer:
Explanation:
The correct way to iterate over an array using a for loop involves initializing 'i' to 0 and continuing while 'i' is less than the array's length.
10. How is the update statement in a for loop typically used?
Answer:
Explanation:
The update statement in a for loop is typically used to increment or decrement a loop counter, thereby progressing the loop towards its termination condition.
11. What will be the output of the following For-Each loop?
int[] nums = {1, 2, 3};
for (int num : nums) {
System.out.print(num + " ");
}
Answer:
Explanation:
The For-Each loop will iterate through each element of the array 'nums', printing each number followed by a space, resulting in the output "1 2 3".
12. Which statement is true about the initialization block in a for loop?
Answer:
Explanation:
The initialization block of a for loop can contain method calls, variable declarations, or any other valid Java statement. It is executed only once, at the start of the loop.