Java For Loop MCQ Questions and Answers

1. What is the basic structure of a for loop in Java?

a) for (initialization; condition; update) { // code }
b) for (condition; initialization; update) { // code }
c) for (condition) { // code }
d) for (initialization; update; condition) { // code }

2. Which part of a for loop is executed only once?

a) The condition
b) The initialization
c) The update statement
d) The code block

3. What is the For-Each loop primarily used for in Java?

a) To iterate over arrays or collections
b) To execute a block of code a specific number of times
c) To create infinite loops
d) To iterate in reverse order

4. What is the syntax of a For-Each loop in Java?

a) for (type var : array) { // code }
b) for (type var = 0; var < array.length; var++) { // code }
c) foreach (type var in array) { // code }
d) for (var : type in array) { // code }

5. What happens if the condition in a for loop is initially false?

a) The loop executes once
b) The loop's body does not execute
c) The loop becomes infinite
d) The loop skips to its last iteration

6. Which component of a for loop is optional?

a) Initialization
b) Condition
c) Update statement
d) All of the above

7. Can the initialization block of a for loop declare multiple variables?

a) Yes, but only of the same type
b) Yes, of different types as well
c) No, it can only declare one variable
d) No, the initialization block is not for declaring variables

8. In a For-Each loop, is it possible to modify the current element?

a) Yes, the current element can be modified
b) No, the For-Each loop is read-only
c) Yes, but only in certain cases
d) No, unless using a special iterator

9. What is the correct way to iterate over an array using a for loop?

a) for (int i = 0; i <= array.length; i++) { // code }
b) for (int i = 0; i < array.length; i++) { // code }
c) for (int i : array) { // code }
d) for (i = 0; i < array.length; i++) { // code }

10. How is the update statement in a for loop typically used?

a) To increment or decrement a loop counter
b) To check the loop's termination condition
c) To initialize loop variables
d) To perform a task at the end of each iteration

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 + " ");
   }
a) 1 2 3
b) 0 1 2
c) 1 2 3 4
d) An error occurs

12. Which statement is true about the initialization block in a for loop?

a) It can contain method calls.
b) It is executed before each iteration.
c) It must declare a new variable.
d) It can only initialize a single variable.

Comments