Using Loop Constructs practice questions

From OCA Java SE 8 (1Z0-808) · 19 questions on this topic

Using Loop Constructs practice questions from OCA Java SE 8 (1Z0-808). This pack has 19 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 = 0; int sum = 0; do { i++; if (i == 2) { continue; } sum += i; } while (i < 4); System.out.println(sum); } } ```

    1. A. 10

      This forgets the skip — it is 1+2+3+4, the total if continue never fired. i=2 is skipped, so 2 is never added.

    2. B. 6

      Stops the loop one pass early, summing 1+2+3 or similar. i takes 1, 2, 3 and 4 because the condition i < 4 is tested after the body, so 4 is still added.

    3. C. 8Correct answer

      Correct: i takes 1, 2, 3, 4 and continue skips the sum only for i=2, so sum = 1 + 3 + 4 = 8 (JLS 8 §14.13, §14.16).

    4. D. It loops forever

      Assumes continue skips the increment and stalls at i=2. In a do/while, continue jumps to the while CONDITION, and i was already incremented at the top of the body, so the loop still terminates.

    Explanation

    i takes 1, 2, 3, 4. continue skips the sum only for i=2 (then jumps to the while CONDITION, so no infinite loop — `It loops forever` is wrong). sum = 1 + 3 + 4 = 8. `10` forgets the skip.

  2. Question 2

    You need to process every element of an array and do not need the index. Which loop form expresses this most directly?

    1. A. A do/while loop

      do/while forces manual index bookkeeping and always runs its body once, so it does not express index-free traversal.

    2. B. A while loop with a manual counter

      The manual counter is exactly the bookkeeping (and off-by-one risk) that the index-free form removes.

    3. C. The enhanced for (for-each) loopCorrect answer

      for-each exists precisely for index-free whole-collection traversal — no counter to mismanage, no off-by-one (JLS 8 §14.14.2).

    4. D. A labeled for loop

      Labels are for nested-loop control, not iteration style, and the loop would still need a manual index.

    Explanation

    for-each exists precisely for index-free whole-collection traversal — no counter to mismanage, no off-by-one. The others all force manual index bookkeeping (labels are for nested-loop control, not iteration style).

  3. Question 3

    What is the output of the following program? ```java public class Main { public static void main(String[] args) { int hits = 0; do { hits++; } while (false); System.out.println(hits); } } ```

    1. A. 0

      Assumes the false condition is tested first and the body never runs, as it would in a while loop. A do/while tests only AFTER the body, so hits is incremented once.

    2. B. Compilation fails because the loop body is unreachable

      Borrows the unreachable-code rule from `while (false) { }`, whose body IS unreachable and a compile error. A do/while body is always reachable because it executes before the condition is ever evaluated, so this compiles fine.

    3. C. It loops forever

      Would require the condition to stay true; it is the constant false, so after the single pass the loop exits immediately.

    4. D. 1Correct answer

      Correct: do/while always executes its body once before testing the condition (JLS 8 §14.13), so hits becomes 1; the false condition then ends the loop and 1 is printed.

    Explanation

    do/while always executes its body once before testing the condition, so hits becomes 1. Note the contrast with `while (false) { }`, whose body IS unreachable and a compile error — the do/while body is always reachable, so `Compilation fails because the loop body...` is wrong.

  4. Question 4

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

    1. A. 12Correct answer

      Correct: i=1 and i=2 are appended, then i=3 is divisible by 3 and `break search` exits the loop entirely (JLS 8 §14.15), leaving "12" in the builder.

    2. B. 124

      Treats the break as if it merely skipped i=3 and resumed at 4 — that is continue behaviour. A labelled break on this single loop exits it entirely, so 4 is never appended.

    3. C. 1234

      Ignores the break altogether. The i % 3 == 0 test fires at i=3 and terminates the loop, so the full 1..4 range is never appended.

    4. D. Compilation fails because the label is unnecessary

      Labels are legal even when redundant; on a single loop `break search` simply behaves like a plain break. There is no rule requiring a label to be needed, so the code compiles.

    Explanation

    Labels are legal even when redundant, so `Compilation fails because the label...` is wrong — on a single loop, `break search` behaves like a plain break. i=1, 2 append; i=3 is divisible by 3 and exits the loop entirely (`124` wrongly resumes at 4).

  5. Question 5

    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 < 3; i++) { if (i == 1) { continue; } for (int j = 0; j < 3; j++) { if (j == 2) { break; } sb.append(i).append(j); } } System.out.println(sb); } } ```

    1. A. 000110112021

      Includes the i=1 block, which the continue removes entirely. With that middle block skipped only the i=0 and i=2 pairs remain.

    2. B. 0001

      Treats the continue as if it ended the outer loop, keeping only the i=0 output. continue skips just the current outer pass, so i=2 still runs and appends 20 and 21.

    3. C. 00012021Correct answer

      Correct: i=0 appends 00 and 01 then breaks at j=2; i=1 is skipped entirely by continue; i=2 appends 20 and 21 (JLS 8 §14.15, §14.16), giving 00012021.

    4. D. 001020

      Caps each inner run at a single pair, as if the break fired at j=1. The break triggers only at j==2, so each inner run appends two pairs before stopping.

    Explanation

    i=0: inner appends 00, 01 then breaks at j=2. i=1: skipped entirely by continue. i=2: appends 20, 21. Result 00012021 — the continue removes the middle block (`000110112021`) and the break caps each inner run at two pairs.

  6. Question 6

    What is the output of the following program? ```java public class Main { public static void main(String[] args) { int count = 0; outer: for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (j > i) { continue outer; } count++; } } System.out.println(count); } } ```

    1. A. 9

      This is the no-continue total — 3 outer passes times 3 inner passes. It ignores that `continue outer` abandons the inner loop as soon as j > i.

    2. B. 3

      Assumes each outer pass counts exactly once, as if the inner loop always incremented a single time before continuing. In fact the inner loop counts i+1 times per outer pass: 1, then 2, then 3.

    3. C. 6Correct answer

      Correct: for each i, counting continues while j <= i and then `continue outer` abandons the inner loop (JLS 8 §14.16). i=0 counts 1 pair, i=1 counts 2, i=2 counts 3 — 1+2+3 = 6.

    4. D. 5

      An off-by-one miscount of the triangular sum. The last outer pass (i=2) never triggers `continue outer`, so it counts all three inner passes, giving 1+2+3 = 6 rather than 5.

    Explanation

    For each i, counting continues while j <= i, then `continue outer` abandons the inner loop: i=0 counts 1 pair (j=0), i=1 counts 2 (j=0,1), i=2 counts 3 (j=0,1,2). 1+2+3 = 6. `9` would be the no-continue total.

  7. Question 7

    What is the output of the following program? ```java public class Main { public static void main(String[] args) { StringBuilder sb = new StringBuilder("x"); while (sb.length() < 4) { sb.append(sb.length()); } System.out.println(sb); } } ```

    1. A. x012

      This starts appending from 0; the first append uses the current length of "x", which is 1.

    2. B. x123Correct answer

      Each append uses the current length: "x" (1) appends 1, "x1" (2) appends 2, "x12" (3) appends 3, and "x123" (4) stops (JLS 8 §14.12).

    3. C. x111

      This assumes the length never changes; each append grows the builder, so the appended digit rises each pass.

    4. D. It loops forever

      The growing length guarantees termination once it reaches 4.

    Explanation

    Each append uses the CURRENT length: "x" (1) appends 1 → "x1" (2) appends 2 → "x12" (3) appends 3 → "x123" (4) stops. The growing length guarantees termination (`It loops forever` is wrong).

  8. Question 8

    What is the result of compiling the following program? ```java public class Main { public static void main(String[] args) { for (char c : "abc") { System.out.println(c); } } } ```

    1. A. a, b, c on separate lines

      Assumes a String can be iterated character by character with an enhanced for. It cannot: the right-hand side must be an array or an Iterable, and String is neither, so the code never runs to print anything.

    2. B. Compilation failsCorrect answer

      Correct: the enhanced for's right-hand side must be an ARRAY or an Iterable, and a String is neither — it doesn't implement Iterable (JLS 8 §14.14.2). Iterating its characters would need "abc".toCharArray() or an index loop.

    3. C. abc

      Treats the loop as if it printed the whole string on one line, but println(c) inside a loop would print one character per line anyway — and more fundamentally the program does not compile, since a String is not an array or an Iterable.

    4. D. An exception is thrown at runtime

      Mistakes a compile-time type error for a runtime failure. The mismatch between String and the array/Iterable requirement is caught by the compiler, so the program never reaches runtime.

    Explanation

    The enhanced for's right-hand side must be an ARRAY or an Iterable. A String is neither — it doesn't implement Iterable — so iterating its characters needs "abc".toCharArray() (an array) or an index loop.

Practise all 19 Using Loop Constructs questions

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

Open OCA Java SE 8

Other topics in this pack