Browse Certification Practice Tests by Exam Family

Java 21 1Z0-830: Controlling Program Flow

Try 10 focused Java 21 1Z0-830 questions on Controlling Program Flow, with explanations, then continue with IT Mastery.

On this page

Open the matching IT Mastery practice page for timed mocks, topic drills, progress tracking, explanations, and full practice.

Try Java 21 1Z0-830 on Web View full Java 21 1Z0-830 practice page

Topic snapshot

FieldDetail
Exam routeJava 21 1Z0-830
Topic areaControlling Program Flow
Blueprint weight7%
Page purposeFocused sample questions before returning to mixed practice

How to use this topic drill

Use this page to isolate Controlling Program Flow for Java 21 1Z0-830. Work through the 10 questions first, then review the explanations and return to mixed practice in IT Mastery.

PassWhat to doWhat to record
First attemptAnswer without checking the explanation first.The fact, rule, calculation, or judgment point that controlled your answer.
ReviewRead the explanation even when you were correct.Why the best answer is stronger than the closest distractor.
RepairRepeat only missed or uncertain items after a short break.The pattern behind misses, not the answer letter.
TransferReturn to mixed practice once the topic feels stable.Whether the same skill holds up when the topic is no longer obvious.

Blueprint context: 7% of the practice outline. A focused topic score can overstate readiness if you recognize the pattern too quickly, so use it as repair work before timed mixed sets.

Sample questions

These questions are original IT Mastery practice items aligned to this topic area. They are designed for self-assessment and are not official exam questions.

Question 1

Topic: Controlling Program Flow

A developer reviews this Java 21 code, where indentation is intentionally misleading and no braces are present. Which statement correctly applies Java’s if/else grouping rule?

class Check {
    public static void main(String[] args) {
        int score = 40;
        boolean audit = true;

        if (score >= 50)
            if (audit)
                System.out.print("audit ");
        else
            System.out.print("fail ");
        System.out.print("done");
    }
}

Options:

  • A. It prints fail done.

  • B. It prints audit done.

  • C. It fails to compile because the else is ambiguous.

  • D. It prints done.

Best answer: D

Explanation: Java resolves a dangling else by matching it with the nearest unmatched if. In this code, the inner if (audit) and its else form the single statement controlled by the outer if. Because score >= 50 is false, that whole nested statement is skipped.

Without braces, an if controls exactly one statement. Here, that one statement is the nested if (audit) ... else ... construct. The else is not controlled by indentation; Java’s grammar attaches it to the closest unmatched if, which is the inner if (audit). Since the outer condition score >= 50 evaluates to false, Java skips the entire nested if/else statement. The separate statement after it still executes and prints done. Braces would be required to make a different grouping explicit.

  • Outer else assumption fails because indentation does not make else pair with the outer if.
  • Audit output requires the outer condition to be true before the inner if can run.
  • Compile error claim fails because Java has a defined dangling-else rule.

Question 2

Topic: Controlling Program Flow

A method maps priority codes to display text:

static String status(int code) {
    String text = "";
    switch (code) {
        case 1:
            text = "low";
        case 2:
            text = "medium";
        case 3:
            text = "high";
            break;
        default:
            text = "unknown";
    }
    return text;
}

The required results are 1 -> "low", 2 -> "medium", 3 -> "high", and any other value -> "unknown". The team wants to keep the colon-label switch statement and the single return. Which change is the best fix?

Options:

  • A. Add break; only after text = "low";.

  • B. Remove the existing break; after text = "high";.

  • C. Add break; after the first two assignments.

  • D. Move default before case 1.

Best answer: C

Explanation: In a colon-label switch statement, a case label is an entry point, not an automatic stopping point. The current code lets codes 1 and 2 continue into later case groups. Adding break; after the first two assignments stops that fall-through while keeping the existing structure.

Colon-label switch statements use fall-through behavior: after matching a label, execution continues into following statements until it reaches break, return, throw, or the end of the switch. Here, case 1 assigns "low" but then continues into case 2 and case 3, so the value is overwritten. case 2 similarly falls into case 3. The existing break after case 3 correctly prevents falling into default, so the missing stops are after the assignments for cases 1 and 2. The key takeaway is that colon labels do not isolate case bodies by themselves.

  • Partial break fixes code 1 but still lets code 2 fall through to case 3.
  • Removing the break lets code 3 continue into default, producing "unknown".
  • Moving default does not create a fall-through boundary and can make unmatched values continue into later cases.

Question 3

Topic: Controlling Program Flow

Which statement describes a valid Java 21 rule for switch statements and switch expressions?

Options:

  • A. A long selector is valid with case 1L labels.

  • B. A boolean selector is valid when both true and false labels appear.

  • C. A String case label may use any local String variable.

  • D. An int selector may use distinct constant int labels.

Best answer: D

Explanation: Java 21 switch statements and switch expressions support specific selector types and strict case-label rules. For an int selector, constant case labels are valid when they are compile-time constants compatible with int and have no duplicate values.

The core rule is that Java 21 does not allow every type as a switch selector. Traditional constant-label switching supports char, byte, short, int, their wrappers, String, and enum types, while pattern switch also supports reference-type selectors. For constant labels, the label values must be compatible with the selector type and duplicates are compile-time errors. A primitive long or boolean selector is not valid in Java 21 switch syntax, and a String case constant cannot be just any runtime local variable.

The key takeaway is that selector validity and case-label validity are compile-time rules.

  • Primitive long trap fails because primitive long is not a valid Java 21 switch selector type.
  • Runtime variable trap fails because a String constant case label must be a compile-time constant expression.
  • Boolean selector trap fails because primitive boolean switch selectors are not supported in Java 21.

Question 4

Topic: Controlling Program Flow

An access method must implement this truth table: signedIn=false returns GUEST; signedIn=true, admin=false returns USER; signedIn=true, admin=true returns ADMIN. Treat the two boolean parameters as independent. The current Java 21 code is below. Which replacement for the conditional is the best fix?

static String access(boolean signedIn, boolean admin) {
    String result = "UNKNOWN";
    if (signedIn)
        if (admin)
            result = "ADMIN";
    else
        result = "GUEST";
    return result;
}

Options:

  • A. ```java if (admin) { result = “ADMIN”; } else if (signedIn) { result = “USER”; } else { result = “GUEST”; }

- B. ```java
if (signedIn) {
    if (admin) {
        result = "ADMIN";
    } else {
        result = "USER";
    }
} else {
    result = "GUEST";
}
  • C. ```java if (signedIn) { if (admin) { result = “ADMIN”; } } else { result = “GUEST”; }

- D. ```java
if (signedIn) {
    result = "USER";
} else if (admin) {
    result = "ADMIN";
} else {
    result = "GUEST";
}

Best answer: B

Explanation: Java pairs an else with the nearest unmatched if, so the original indentation does not describe the actual branch structure. The fix must make the signedIn decision first and nest the admin decision only for signed-in users.

The core issue is tracing nested if/else branches exactly. In the original code, the else belongs to the inner if (admin), not to if (signedIn), so signedIn=true, admin=false assigns GUEST, and signedIn=false leaves the default UNKNOWN. The correct refactor uses braces to make the intended grouping explicit: signed-out users go directly to GUEST, while signed-in users are split into ADMIN or USER based on admin. Because the parameters are independent, checking admin before signedIn can also produce the wrong result for signedIn=false, admin=true.

  • Missing user branch leaves signedIn=true, admin=false as the initial UNKNOWN value.
  • Admin first incorrectly allows signedIn=false, admin=true to return ADMIN.
  • Else-if after signedIn skips the admin check for signed-in admins and mishandles signed-out admins.

Question 5

Topic: Controlling Program Flow

A developer wants to print sums only for rows that do not contain 0. The current Java 21 code compiles, but it prints 5 instead of the expected 5 11 .

class CheckRows {
    public static void main(String[] args) {
        int[][] data = { {2, 3}, {4, 0}, {5, 6} };

        rows:
        for (int[] row : data) {
            int sum = 0;
            for (int n : row) {
                if (n == 0) break rows;
                sum += n;
            }
            System.out.print(sum + " ");
        }
    }
}

Which change is the simplest valid fix?

Options:

  • A. Move rows: to the inner loop and keep break rows;.

  • B. Replace break rows; with continue;.

  • C. Replace break rows; with break;.

  • D. Replace break rows; with continue rows;.

Best answer: D

Explanation: The label rows is attached to the outer loop. A labeled continue rows; jumps to the next iteration of that outer loop, which skips printing the partial sum for the row containing 0 while still processing later rows.

A labeled break exits the labeled statement completely. Here, break rows; exits the outer for loop, so the third row is never processed. The requirement is not to stop all processing; it is to skip only the current outer-loop iteration when a 0 is found. Since rows labels the outer loop, continue rows; is the simplest construct: it skips the remaining body of the current outer iteration, including the print statement, and then continues with the next row. An unlabeled break or continue would affect only the inner loop.

  • Unlabeled break exits only the inner loop, so the partial sum for the bad row would still be printed.
  • Unlabeled continue continues only the inner loop, which does not skip the row-level print.
  • Inner label targets the wrong loop, so it cannot skip the outer loop’s remaining body.

Question 6

Topic: Controlling Program Flow

A method scans a rectangular array with nested loops. If any cell in a row is invalid, it must skip the remaining cells of that same row and continue with the next row. Without moving logic into another method, which construct is the simplest valid Java 21 way to express this behavior?

Options:

  • A. Use return from inside the inner loop

  • B. Label the outer loop and use break label;

  • C. Label the outer loop and use continue label;

  • D. Use an unlabeled continue in the inner loop

Best answer: C

Explanation: The requirement is to abandon the rest of the current outer-loop iteration and move to the next one. In Java, a labeled continue can target an enclosing loop, which makes it the simplest valid construct here.

A labeled continue transfers control to the next iteration of the labeled enclosing loop. In nested loops, placing a label on the outer loop and executing continue label; from the inner loop skips the rest of the current outer-loop body, including any remaining inner-loop work, and begins the next outer iteration. This is different from an unlabeled continue, which affects only the innermost loop that contains it. A labeled break would exit the labeled loop entirely, not continue with the next row.

  • Unlabeled continue only advances the innermost loop, so it would continue with the next cell rather than the next row.
  • Labeled break exits the outer loop, so later rows would not be processed.
  • Return exits the whole method, which is broader than the stated row-skipping requirement.

Question 7

Topic: Controlling Program Flow

In Java 21, assume an enhanced for loop iterates over an array in one case and over a standard ArrayList in another. During the loop body, code changes an array element through the array reference, or structurally changes the ArrayList directly. In the ArrayList case, the loop then attempts to get another element. Which rule is correct?

Options:

  • A. Both modifications are compile-time errors in an enhanced for loop.

  • B. The array change is allowed; the ArrayList iteration throws ConcurrentModificationException.

  • C. Both modifications are allowed because enhanced for copies the source.

  • D. The array change throws ConcurrentModificationException; the ArrayList change is allowed.

Best answer: B

Explanation: An enhanced for loop behaves differently for arrays and collections. Array elements can be changed through the array reference while looping. A standard ArrayList uses a fail-fast iterator, so a direct structural change is detected when the iterator is used again.

The enhanced for statement over an array is based on array access, not an Iterator, so there is no fail-fast concurrent modification check. Changing an element through the array reference is a normal assignment. For an ArrayList, enhanced for uses the list’s Iterator; adding or removing elements directly through the list is a structural modification outside that iterator. When the iterator later tries to obtain another element, it detects the modification and throws ConcurrentModificationException. The key distinction is array element assignment versus collection structural modification during iterator-based traversal.

  • Compile-time error is wrong because modifying the array or list object is not automatically forbidden by the enhanced for syntax.
  • Source copying is wrong because enhanced for does not make a defensive copy of arrays or collections.
  • Reversed behavior is wrong because arrays do not throw ConcurrentModificationException, but ArrayList iterators are fail-fast.

Question 8

Topic: Controlling Program Flow

A nightly cleanup job was changed to the code below. It compiles, but at runtime it throws java.util.ConcurrentModificationException before printing the final list. The goal is to remove all temporary jobs in one traversal.

class Cleanup {
    public static void main(String[] args) {
        var jobs = new ArrayList<>(List.of("keep", "tmp1", "tmp2", "done"));
        for (String job : jobs) {
            if (job.startsWith("tmp")) {
                jobs.remove(job);
            }
        }
        System.out.println(jobs);
    }
}

Which change best fixes the problem?

Options:

  • A. Change ArrayList to LinkedList.

  • B. Add continue after jobs.remove(job).

  • C. Use an index loop that always increments.

  • D. Use explicit Iterator.remove() during traversal.

Best answer: D

Explanation: The exception is caused by structurally modifying the ArrayList while its enhanced-for iterator is active. Enhanced for uses an Iterator behind the scenes, and direct removal through the list invalidates that iterator. Removing through the iterator itself avoids this fail-fast condition.

The core rule is that fail-fast collection iterators detect structural modifications made outside the iterator. In the snippet, jobs.remove(job) changes the list while the enhanced-for loop’s iterator is still controlling traversal. On the next iterator operation, the iterator sees that the list’s modification count has changed unexpectedly and throws ConcurrentModificationException. A safe in-loop removal uses an explicit Iterator<String>, calls next(), and then calls iterator.remove() for the current element. The key distinction is not the loop syntax itself, but whether the structural change is coordinated through the active iterator.

  • continue misconception fails because continuing the loop still reaches the next iterator operation after the list was modified.
  • Changing list type fails because LinkedList iterators are also fail-fast for outside structural changes.
  • Naive index loop fails for the stated goal because removing tmp1 shifts tmp2 left and the next increment skips it.

Question 9

Topic: Controlling Program Flow

Consider this Java 21 fragment. The variables have exactly the values shown. What is the result?

boolean a = true, b = false, c = true;

if (a)
    if (b)
        System.out.print("B");
    else if (c)
        System.out.print("C");
    else
        System.out.print("D");
else
    System.out.print("A");

Options:

  • A. It prints D.

  • B. It prints A.

  • C. It does not compile.

  • D. It prints C.

Best answer: D

Explanation: The code prints C. Since a is true, execution enters the outer if branch. Inside that branch, b is false, so Java evaluates else if (c), which is true.

In Java, an else if is an else whose statement is another if, so its conditions are checked only after earlier conditions in the same chain are false. An else associates with the nearest preceding unmatched if, and braces are not required when the controlled statement is a single statement. Here, a is true, so the outer else that prints A is skipped. Within the nested statement, b is false, then c is true, so the branch printing C runs. The branch printing D would require both b and c to be false after entering the outer if.

  • Outer else confusion treats the final else as something that can run after the inner chain, but it is the alternative to if (a).
  • Inner final else would require c to be false after b is false.
  • Brace requirement is false because Java permits nested single-statement if constructs without braces.

Question 10

Topic: Controlling Program Flow

Which Java 21 rule is correct for loop variables and iteration behavior?

Options:

  • A. A basic-for initializer variable is scoped to the loop, and continue reaches the update step before retesting.

  • B. In a basic for, the update expression executes before the first condition check.

  • C. An enhanced-for element variable remains in scope after the loop finishes.

  • D. In an enhanced for over an array, assigning the loop variable replaces the current array element.

Best answer: A

Explanation: Java’s basic for statement has a defined scope and execution order. A variable declared in the initializer is not visible after the loop, and a continue that targets that loop runs the update before checking the condition again.

In a basic for (init; condition; update), initializer variables are scoped to the entire for statement: condition, body, and update, but not after the statement. The condition is checked before the first iteration. After normal body completion, and after a continue that targets that loop, the update runs before the condition is checked again. In an enhanced for, the loop variable receives each element value for that iteration; reassigning the variable does not write back to the source element.

  • First update is wrong because the condition is checked before the first loop body execution.
  • Enhanced assignment is wrong because reassigning the loop variable changes only that local variable.
  • Post-loop scope is wrong because the enhanced-for element variable is scoped to the loop, not after it.

Continue with full practice

Use the Java 21 1Z0-830 Practice Test page for the full IT Mastery route, mixed-topic practice, timed mock exams, explanations, and web/mobile app access.

Try Java 21 1Z0-830 on Web View Java 21 1Z0-830 Practice Test

Free review resource

Read the Java 21 1Z0-830 Cheat Sheet on Tech Exam Lexicon, then return to IT Mastery for timed practice.

Revised on Thursday, May 14, 2026