Using Loop Constructs practice questions

From OCA Java SE 7 (1Z0-803) · 24 questions on this topic

Using Loop Constructs practice questions from OCA Java SE 7 (1Z0-803). This pack has 24 questions tagged Using Loop Constructs, drawn from its timed mock exams. 8 of them are worked through in full below — the question, every option, why each is right or wrong, and the explanation.

Worked examples for Using Loop Constructs

  1. Question 1

    What is the output of the following program? ```java public class Main { public static void main(String[] args) { int i, j; for (i = 0, j = 5; i < j; i++, j--) { } System.out.println(i + " " + j); } } ```

    1. A. 3 2Correct answer

      Comma lists are legal in init and update; tracing (0,5)->(1,4)->(2,3) then i=3, j=2 makes 3 < 2 false, so it exits at 3 2.

    2. B. 2 3

      This swaps the two values; i ends at 3 and j at 2, not the reverse.

    3. C. 5 0

      These are the initial values before any iteration; the loop runs several times, changing both i and j.

    4. D. Compilation fails because a for loop cannot have two update expressions

      A for loop may have multiple comma-separated update expressions, so this compiles.

    Explanation

    Comma-separated lists are legal in both the init and update sections (`Compilation fails because a for loop cannot...` is wrong). Trace the pairs: (0,5) → (1,4) → (2,3) → after the third update i=3, j=2 and 3 < 2 is false, so the loop exits with i=3, j=2.

  2. Question 2

    Which parts of a basic for statement `for (init; condition; update)` are optional?

    1. A. Only the init section

      All three for sections are independently optional, not just the init.

    2. B. Only the update section

      Every section, not only the update, may be omitted.

    3. C. All three — for ( ; ; ) is a valid (infinite) loopCorrect answer

      Each section may be left empty; with the condition omitted it defaults to true, making for ( ; ; ) an infinite loop.

    4. D. None — all three are required

      None are required; each of the three sections may be omitted.

    Explanation

    Each section may be left empty independently; with the condition omitted it defaults to true, making for ( ; ; ) the classic infinite loop (exited via break or return).

  3. Question 3

    What is the output of the following program? ```java public class Main { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 5; i++) { if (i % 2 == 0) { continue; } sb.append(i); } System.out.println(sb); } } ```

    1. A. 024

      These are the even values that continue skips, so they are never appended; only the odd values reach the append.

    2. B. 1

      This includes only the first odd value and misses 3, which is also appended.

    3. C. It loops forever because continue skips i++

      In a for loop the update i++ still runs after continue, so the loop always advances and never spins forever.

    4. D. 13Correct answer

      continue skips the append only for even i; the odd values 1 and 3 are appended, giving 13.

    Explanation

    continue jumps past the rest of the body to the next iteration — and in a for loop the UPDATE expression (i++) still runs, so there is no infinite loop (ruling out `It loops forever because continue skips i++`). Even values are skipped; 1 and 3 are appended: "13".

  4. Question 4

    Which loop construct is guaranteed to execute its body at least once?

    1. A. while

      A while is a pre-test loop, so it can execute its body zero times if the condition is false initially.

    2. B. for

      A for is also pre-test, checking its condition before the first pass, so it may run zero times.

    3. C. do/whileCorrect answer

      do/while is the only post-test loop: it runs the body before checking the condition, guaranteeing at least one execution.

    4. D. enhanced for

      The enhanced for does nothing for an empty array or collection, so it is not guaranteed to run its body.

    Explanation

    do/while is the only post-test loop: the body runs before the condition is first checked. while and for are pre-test (zero iterations possible), and the enhanced for does nothing for an empty array or collection.

  5. Question 5

    What is the result of compiling the following program? ```java public class Main { public static void main(String[] args) { int k = 3; while (k--) { System.out.println(k); } } } ```

    1. A. It prints 2, 1, 0 on separate lines

      This assumes a nonzero int counts as true, a C idiom Java rejects; the code never runs because it does not compile.

    2. B. It loops forever

      This also treats the int expression as a boolean condition; Java requires an explicit boolean, so the program fails to compile rather than loop.

    3. C. It prints 3, 2, 1 on separate lines

      This again assumes int-as-boolean truthiness that Java does not support, and it never executes because compilation fails.

    4. D. Compilation failsCorrect answer

      A while condition must be boolean, but k-- is an int expression and Java never converts nonzero ints to true, so compilation fails.

    Explanation

    A while condition must be boolean. k-- is an int expression, and Java never treats nonzero ints as true — that's a C idiom. The condition must be written explicitly, e.g. while (k-- > 0).

  6. Question 6

    What is the output of the following program? ```java public class Main { public static void main(String[] args) { int[][] m = { {1, 2}, {3, 4} }; int sum = 0; for (int[] row : m) { for (int v : row) { sum += v; } } System.out.println(sum); } } ```

    1. A. 10Correct answer

      The nested enhanced-for adds every element 1+2+3+4, giving 10.

    2. B. 6

      This sums only one row rather than both; the outer loop visits every row.

    3. C. 4

      This is a single element, not the total of all elements across both rows.

    4. D. Compilation fails because the outer loop variable must be int

      The outer enhanced-for variable is each row, correctly typed as int[], so this compiles.

    Explanation

    Iterating a 2D array with the enhanced for: the outer loop variable is each ROW (an int[], so `Compilation fails because the outer loop variable...` is wrong), the inner one each element. 1+2+3+4 = 10.

  7. Question 7

    What is the result of compiling the following program? ```java public class Main { public static void main(String[] args) { for (int i = 0; i < 3; i++) { } System.out.println(i); } } ```

    1. A. 3

      i is out of scope after the loop, so it cannot be printed; the code fails to compile.

    2. B. 2

      The loop variable does not survive past the for statement, so no value is printed.

    3. C. Compilation failsCorrect answer

      A variable declared in the for-init exists only within the for statement, so referencing i afterward is cannot find symbol.

    4. D. 0

      i is not accessible after the loop, so nothing is printed; it is a scope compile error.

    Explanation

    A variable declared in the for-init exists only within the for statement. After the loop, i is out of scope — "cannot find symbol". To read the final value afterward, declare i before the loop.

  8. Question 8

    What is the result of compiling the following program? ```java public class Main { public static void main(String[] args) { for (int i = 0; i < 3; i++) { break; System.out.println(i); } } } ```

    1. A. It compiles and prints nothing

      The println after an unconditional break is provably unreachable, which Java rejects at compile time rather than silently ignoring.

    2. B. 0

      Even though break precedes the println, the unreachable println is a compile error, so nothing is printed.

    3. C. Compilation failsCorrect answer

      The statement after the unconditional break can never execute, and Java treats such unreachable statements as a compile error.

    4. D. 0 1 2 on separate lines

      This ignores both the break and the unreachable-statement error; the code does not compile, let alone iterate.

    Explanation

    The println after the unconditional break can never execute, and Java treats provably unreachable statements as a COMPILE ERROR ("unreachable statement"), not dead code to ignore. Remove the println (or make the break conditional) and it compiles.

Practise all 24 Using Loop Constructs questions

OCA Java SE 7 has the full set, inside timed mock exams that mirror real exam conditions — every question with a worked explanation.

Open OCA Java SE 7

Other topics in this pack