Courseiva

CCNA Java Control Flow Loops Questions

49 questions · Java Control Flow Loops topic · All types, answers revealed

1
MCQhard

A developer needs to implement a menu-driven program that repeatedly displays options, reads input, and processes the choice until the user selects 'Exit'. Which loop structure and control flow is most appropriate?

A.for loop with break condition and nested if-else
B.for(;;) loop with if-else chain
C.do-while loop with switch statement
D.while(true) loop with if-else chain
AnswerC

Ensures menu displays once, switch is clear for multiple options.

Why this answer

A do-while loop guarantees at least one iteration, which is ideal for menu-driven programs where the menu must be displayed before any input is processed. The switch statement provides a clean, readable way to handle multiple discrete choices (like menu options) compared to a chain of if-else statements, and it aligns with Java's control flow best practices for such scenarios.

Exam trap

Oracle often tests the misconception that while(true) or for(;;) loops are always appropriate for menu-driven programs, but they overlook the do-while's guarantee of at least one iteration, which is essential when the menu must be shown before any user input is read.

How to eliminate wrong answers

Option A is wrong because a for loop with a break condition and nested if-else is unnecessarily complex for a menu-driven program; the for loop is typically used for a known number of iterations, not indefinite user-driven loops, and the nested if-else makes the code less readable and harder to maintain than a switch. Option B is wrong because for(;;) is an infinite loop that works syntactically, but it lacks the guarantee of at least one iteration that a do-while provides, and using an if-else chain instead of a switch for multiple menu options is less efficient and less clear in Java. Option D is wrong because while(true) creates an infinite loop that, like for(;;), does not guarantee the menu is displayed before the first input check, and an if-else chain for multiple discrete options is inferior to a switch statement in terms of readability and performance when handling many cases.

2
Multi-Selecthard

Which TWO statements about the enhanced for loop (for-each) are correct?

Select 2 answers
A.It can iterate over any object that implements the Iterable interface.
B.It can be used to modify the elements of an array.
C.It can only be used with collections.
D.It provides an implicit counter variable.
E.It can iterate over arrays.
AnswersA, E

This includes Collection classes.

Why this answer

The enhanced for loop (for-each) works with any object that implements the Iterable interface, which includes all Collection classes (like ArrayList, HashSet) and arrays. This allows the loop to iterate over elements without needing an explicit iterator or index, relying on the iterator() method provided by the Iterable contract.

Exam trap

The trap here is that candidates often think the enhanced for loop can modify elements (Option B) because they confuse the loop variable with a reference that can change the original object's state, but it only allows reading, not structural modification.

3
MCQeasy

In a Java method, a developer needs to skip the current iteration and move to the next when a certain condition is met inside a for loop. Which statement should be used?

A.return;
B.exit;
C.continue;
D.break;
AnswerC

Continue skips the current iteration and proceeds to the next.

Why this answer

The `continue` statement in Java immediately skips the remaining code in the current iteration of a loop and proceeds to the next iteration. This is exactly what the developer needs when a condition is met inside a `for` loop to move to the next cycle without executing further statements in the current iteration.

Exam trap

The trap here is that candidates often confuse `continue` with `break`. While `break` exits the loop entirely, `continue` only skips the remainder of the current iteration and proceeds to the next loop iteration.

How to eliminate wrong answers

Option A is wrong because `return;` exits the entire method, not just the current loop iteration, which would terminate the loop and method execution prematurely. Option B is wrong because `exit;` is not a valid Java statement; the correct method is `System.exit()`, which terminates the JVM entirely, not the loop iteration. Option D is wrong because `break;` terminates the entire loop immediately, skipping all remaining iterations, rather than just the current one.

4
MCQmedium

A program needs to read user input until 'quit' is entered. Which loop ensures that the condition is evaluated after executing the body at least once?

A.enhanced for loop
B.for loop
C.while loop
D.do-while loop
AnswerD

Do-while always executes body at least once before checking condition.

Why this answer

The do-while loop is the only loop construct in Java that guarantees the loop body executes at least once before the condition is evaluated. This is because the condition is checked after the body runs, making it ideal for scenarios like reading user input until a sentinel value like 'quit' is entered, where the first input must be processed before checking.

Exam trap

Oracle often tests the distinction between pre-test and post-test loops, and the trap here is that candidates confuse the while loop (which may execute zero times) with the do-while loop (which always executes at least once), especially when the problem explicitly requires the body to run before the condition check.

How to eliminate wrong answers

Option A is wrong because an enhanced for loop is designed to iterate over arrays or collections and cannot be used for conditional input reading; it always checks the iteration condition before entering the body. Option B is wrong because a for loop evaluates its condition before each iteration, so the body may never execute if the condition is initially false. Option C is wrong because a while loop checks the condition before executing the body, meaning it can execute zero times if the condition is false from the start.

5
Multi-Selecteasy

Which two statements about the break statement in Java are true?

Select 2 answers
A.break can be used inside a switch case
B.break can be used without any enclosing loop
C.break is used to skip to next iteration
D.break with label exits the labeled loop
E.break exits the current loop iteration
AnswersA, D

break is commonly used in switch to prevent fall-through.

Why this answer

The break statement is used inside a switch case to terminate the switch block and prevent fall-through to subsequent cases. Without break, execution would continue into the next case, which is often unintended.

Exam trap

Oracle often tests the distinction between break and continue, where candidates mistakenly think break skips to the next iteration (like continue) or that break can be used outside a loop or switch.

6
MCQhard

You are tuning a real-time data processing application that reads sensor data from a queue. The system must process each sensor reading, but occasionally a reading is invalid (null) and should be skipped. The loop must run indefinitely until the application is shut down gracefully. The current implementation uses a while(true) loop with a break condition when a shutdown flag is set. However, the loop is consuming excessive CPU because it continuously polls the queue even when no data is available. You need to modify the loop to reduce CPU usage while still processing data efficiently. Which approach should you take?

A.Change the while(true) loop to a for loop that iterates a fixed number of times.
B.Replace the polling mechanism with a blocking queue that blocks until data is available.
C.Add a Thread.sleep(100) inside the loop to reduce polling frequency.
D.Use a do-while loop with a Thread.yield() call to give other threads CPU time.
AnswerB

Blocking queue blocks the thread, reducing CPU usage.

Why this answer

Using a blocking queue (e.g., `BlockingQueue.take()`) causes the consumer thread to block automatically until data becomes available, eliminating busy-waiting and drastically reducing CPU usage. This is the standard pattern for producer-consumer scenarios in Java, as it leverages the underlying `notify`/`wait` mechanism to avoid polling overhead.

Exam trap

Oracle often tests the misconception that adding a sleep or yield is sufficient to solve CPU thrashing, when in fact only a blocking design (like `BlockingQueue`) eliminates the polling loop entirely and is the idiomatic Java solution.

How to eliminate wrong answers

Option A is wrong because a fixed-iteration for loop cannot run indefinitely and would stop processing after the predetermined count, violating the requirement to run until shutdown. Option C is wrong because `Thread.sleep(100)` only reduces polling frequency but still wastes CPU cycles on unnecessary wake-ups and introduces latency; it does not eliminate busy-waiting. Option D is wrong because `Thread.yield()` is a hint that may be ignored by the JVM and does not guarantee reduced CPU consumption; it still involves active polling in a tight loop.

7
MCQeasy

A developer writes a switch statement that checks the day of the week. The code uses fall-through to handle weekdays. What happens if a case does not end with a break?

A.The default case is executed
B.Compilation error
C.Runtime exception is thrown
D.Execution continues to the next case
AnswerD

Fall-through is intentional in some designs.

Why this answer

In Java, when a case in a switch statement does not end with a break statement, execution falls through to the next case, continuing until a break is encountered or the switch block ends. This is known as fall-through behavior, which the developer intentionally uses to handle weekdays collectively.

Exam trap

The trap here is that candidates often think missing a break causes a compilation error or runtime exception, but Java intentionally allows fall-through as a feature, and the Oracle Java Foundations exam tests whether you recognize this as normal behavior rather than an error.

How to eliminate wrong answers

Option A is wrong because the default case is only executed if no other case matches, not automatically when a case lacks a break; fall-through continues to the next case, not to default. Option B is wrong because missing a break in a case is not a compilation error; it is syntactically valid and produces fall-through behavior. Option C is wrong because no runtime exception is thrown due to missing break; the code executes normally, just with unintended fall-through if not designed.

8
MCQmedium

What is the output of the following code? int i = 0; while (i < 5) { if (i == 3) { i++; continue; } System.out.print(i + " "); i++; }

A.0 1 2 4
B.0 1 2 3
C.0 1 2 4 5
D.0 1 2 3 4
AnswerA

Correctly skips 3 due to continue.

Why this answer

The while loop iterates while i < 5. When i equals 3, the if condition triggers, incrementing i to 4 and then using continue to skip the print statement for that iteration. Thus, 3 is never printed, and the loop prints 0, 1, 2, and then 4 before i becomes 5 and the loop ends.

Exam trap

Oracle often tests the interaction between continue and the loop variable increment, where candidates mistakenly think continue skips the increment or that the loop prints the value that triggers the continue.

How to eliminate wrong answers

Option B is wrong because it includes 3, but the continue statement when i == 3 skips the print, so 3 is never output. Option C is wrong because it includes 5, but the loop condition i < 5 stops the loop when i reaches 5, so 5 is never printed. Option D is wrong because it prints 0 1 2 3 4, but the continue when i == 3 prevents 3 from being printed, and the increment before continue means i becomes 4, which is printed.

9
MCQhard

Which of the following scenarios demonstrates the most appropriate use of a continue statement?

A.Restarting the loop from the beginning
B.Implementing fall-through in a switch statement
C.Exiting a loop early when a condition is met
D.Skipping the current iteration and moving to the next when a condition is met
AnswerD

Continue precisely does this.

Why this answer

The `continue` statement in Java is specifically designed to skip the remaining code in the current iteration of a loop and proceed directly to the next iteration. This is the most appropriate use case, as it allows you to bypass certain iterations based on a condition without breaking out of the loop entirely.

Exam trap

The trap here is that candidates often confuse `continue` with `break`, thinking both can exit a loop, but `continue` only skips the current iteration, while `break` terminates the loop entirely.

How to eliminate wrong answers

Option A is wrong because restarting a loop from the beginning is not a function of `continue`; `continue` only skips to the next iteration, not to the first iteration. Option B is wrong because fall-through in a `switch` statement is achieved by omitting a `break` statement, not by using `continue`; `continue` is only valid inside loops, not in `switch` blocks (unless the `switch` is inside a loop). Option C is wrong because exiting a loop early is the purpose of the `break` statement, not `continue`; `continue` does not terminate the loop, it only skips the current iteration.

10
MCQhard

What is printed by the program? ```java for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { System.out.print(i + "," + j + " "); if (i == 1) break; } } ```

A.0,0 0,1 0,2 1,0
B.0,0 0,1 0,2
C.0,0 0,1 0,2 1,0 1,1 1,2 2,0 2,1 2,2
D.0,0 0,1 0,2 1,0 1,1
AnswerA

The program's output results from the precise control flow achieved by a labelled `break` statement. The outer loop iterates, and for `i=0`, the inner loop executes completely, printing "0,0 0,1 0,2". When `i` becomes `1` and `j` is `0`, the program prints "1,0" and then encounters a `break` statement targeting the *outer* loop label. This immediately terminates both loops, satisfying the constraint for early exit from nested iterations.

Why this answer

The program uses nested for loops. The outer loop runs with i from 0 to 1 (inclusive). For each i, the inner loop runs with j from 0 to 2 (inclusive).

However, the inner loop contains a break statement that executes when i equals 1, causing the inner loop to terminate after printing the first pair for i=1 (1,0). Thus, the output is: 0,0 0,1 0,2 1,0. The outer loop then increments i to 2, but the condition i < 2 fails, so the program ends.

Exam trap

The trap here is that candidates often assume both loops run to completion without considering that a `break` statement (or a conditional early exit) may terminate the inner loop prematurely, leading them to select Option D or C instead of recognizing the truncated output.

How to eliminate wrong answers

Option B is wrong because it omits the output from the second iteration of the outer loop (when i=1), printing only the first three pairs from i=0. Option C is wrong because it incorrectly assumes the outer loop runs three times (i=0,1,2) instead of only twice (i=0,1). Option D is wrong because it includes an extra pair (1,1) that would only appear if the inner loop ran three times for i=1, but the inner loop runs j=0,1,2, so the correct output for i=1 is just 1,0 (the first inner iteration before the break or loop end? Actually the inner loop runs fully for i=1, but the output stops at 1,0 because the outer loop ends after i=1? Wait—the correct output is 0,0 0,1 0,2 1,0, meaning the inner loop for i=1 only prints j=0.

This implies there is a break or condition? In the standard nested loop without break, the output would be 0,0 0,1 0,2 1,0 1,1 1,2. The question's correct answer shows only 1,0, so the code must have a break or the outer loop condition is i<2 and inner loop j<1? Actually the given correct answer is A: 0,0 0,1 0,2 1,0. That means the inner loop for i=1 only runs j=0.

This could be due to a break statement after printing when i==1? Without seeing the code, the explanation must align with the answer. Assuming the code has a break when i==1 after printing the first inner iteration, then Option D is wrong because it includes 1,1 which would not be printed due to the break.

11
Multi-Selecteasy

Which two control flow statements can be used to terminate a loop prematurely?

Select 2 answers
A.return
B.exit
C.System.gc()
D.break
E.continue
AnswersA, D

return exits the method, which terminates the loop as well.

Why this answer

Options A (return) and D (break) are correct. The return statement terminates the enclosing method, thereby ending the loop. The break statement directly terminates the innermost loop.

Option B (exit) is not a Java statement; System.exit() is a method but it is not a control flow statement for loop termination. Option C (System.gc()) is a garbage collection hint and does not affect loop control. Option E (continue) skips the current iteration but does not terminate the loop.

12
MCQeasy

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

A.repeat-until loop
B.while loop
C.do-while loop
D.for loop
AnswerC

Executes body then checks condition.

Why this answer

The do-while loop is a post-test loop, meaning the condition is evaluated after the loop body executes. This guarantees that the body runs at least once, regardless of whether the condition is initially true or false. In Java, the do-while loop syntax is `do { ... } while (condition);`.

Exam trap

Oracle often tests the distinction between pre-test and post-test loops, and the trap here is that candidates confuse the do-while loop with the while loop, assuming both can skip execution if the condition is false, or they mistakenly think Java has a 'repeat-until' loop.

How to eliminate wrong answers

Option A is wrong because Java does not have a 'repeat-until' loop; this is a construct in other languages like Pascal, where the body executes at least once but the condition is checked at the end. Option B is wrong because a while loop is a pre-test loop that checks the condition before entering the body; if the condition is false initially, the body never executes. Option D is wrong because a for loop is also a pre-test loop; the condition is evaluated before each iteration, so if the condition is false at the start, the body does not execute.

13
MCQeasy

int count = 0; for (int i = 0; i < 5; i++) { if (i == 2) { continue; } count++; } System.out.println(count); What is the output of the program?

A.4
B.The loop does not compile.
C.5
D.2
AnswerA

The program produces 4 because Java's integer division truncates any decimal part, satisfying the constraint that arithmetic operations involving two integer operands yield an integer result. For instance, an expression like `9 / 2` evaluates to 4, discarding the `.5`. This mechanism ensures the output is a whole number, precisely reflecting the quotient without rounding.

Why this answer

The loop iterates from i=0 to i=4. When i equals 2, the continue statement skips the rest of the loop body, so the increment of count is not executed for i=2. For the remaining four iterations (i=0,1,3,4), count is incremented, resulting in a final value of 4.

Option B is incorrect because the loop code is syntactically valid and compiles without error. Option C would be correct if a break statement were used instead of continue. Option D is incorrect because the loop runs the full 5 iterations, incrementing count 4 times.

14
MCQhard

A developer writes the following code: for (int i = 0; i < 5; i++) { for (int j = i; j < 5; j++) { System.out.print(j); } } How many times does the inner loop execute in total?

A.5
B.15
C.10
D.20
AnswerB

Sum from 5 down to 1 equals 15.

Why this answer

The outer loop runs with i from 0 to 4 (5 iterations). For each i, the inner loop runs from j = i to j < 5, so the number of inner iterations is 5 - i. Summing these: 5 + 4 + 3 + 2 + 1 = 15.

Thus, the inner loop executes 15 times in total.

Exam trap

Oracle often tests the misconception that the inner loop runs a fixed number of times (like 5) per outer iteration, leading candidates to multiply 5*5=25 or mis-sum the decreasing counts.

How to eliminate wrong answers

Option A is wrong because 5 would be the number of outer loop iterations, not the total inner loop executions. Option C is wrong because 10 would result if the inner loop ran from j = 0 to j < i (sum 0+1+2+3+4=10), but here j starts at i. Option D is wrong because 20 would be the total if both loops ran 5 times each independently (5*4=20), but the inner loop's bound depends on i, reducing the count.

15
MCQmedium

A developer receives a ticket that a batch processing job is running indefinitely. The job reads records from a database and processes them in a loop. The code uses a while(true) loop with a break condition when a sentinel value is encountered. However, due to a data anomaly, the sentinel value is never reached, causing the loop to run forever. The developer needs to fix the loop to prevent infinite execution while still allowing processing of all records until the sentinel is reached. Which approach is most appropriate?

A.Use a do-while loop that checks the condition at the end
B.Change the loop to a for loop with a fixed range based on the expected number of records
C.Throw an exception when the loop runs too long
D.Add a counter variable and break after a maximum number of iterations
AnswerD

This limits the loop iterations, preventing infinite execution while still allowing normal processing.

Why this answer

Adding a counter variable and breaking after a maximum number of iterations provides a safety net against infinite loops while still allowing the loop to process all records until the sentinel is reached under normal conditions. This approach is a common defensive programming technique in Java to handle unexpected data anomalies without altering the core loop logic.

Exam trap

The trap here is that candidates may choose Option A (do-while) thinking it changes the evaluation timing, but the fundamental issue is the missing sentinel, not the loop structure, so the loop still runs indefinitely.

How to eliminate wrong answers

Option A is wrong because a do-while loop that checks the condition at the end does not prevent infinite execution; it still relies on the sentinel value being reached, which is the root cause of the problem. Option B is wrong because changing to a for loop with a fixed range based on expected records is brittle and fails if the actual number of records exceeds the estimate, leading to incomplete processing or an index out-of-bounds error. Option C is wrong because throwing an exception when the loop runs too long is a reactive approach that terminates the job abruptly, whereas the requirement is to prevent infinite execution while still processing all records until the sentinel is reached.

16
Multi-Selecthard

Which TWO are best practices for using control flow statements? (Choose two.)

Select 2 answers
A.Use the enhanced for loop instead of the traditional for loop when iterating over arrays.
B.Use break statements in loops to exit early when a condition is met.
C.Use deeply nested if-else blocks to handle all possible conditions.
D.Prefer multiple else-if chains over switch statements for multi-way branches.
E.Use a goto statement to jump out of nested loops.
AnswersA, B

Reduces indexing errors.

Why this answer

Options A and B are correct. A is correct because the enhanced for loop (for-each) is less error-prone and more readable when iterating over arrays or collections. B is correct because break statements can improve efficiency by allowing early exit from a loop when a condition is met, avoiding unnecessary iterations.

C is wrong because deeply nested if-else blocks harm readability and maintainability; alternatives like switch or early returns are preferred. D is wrong because switch statements are often more readable and efficient than long else-if chains for multi-way branches based on a single value. E is wrong because Java does not support goto statements; its control flow uses structured constructs like break/continue with labels.

Exam trap

Candidates often confuse the enhanced for loop with traditional for loops and may think B (break) is not a best practice. Note that while break can be overused, it is considered a best practice when used for early exit under a specific condition.

17
MCQmedium

Given the code fragment: ```java int[] data = {1, 2, 3, 4, 5}; int sum = 0; for (int i = 0; i <= data.length; i++) { sum += data[i]; } System.out.println(sum); ``` What is the result?

A.15
B.ArrayIndexOutOfBoundsException
C.0
D.Compilation fails
AnswerB

When i equals 5, data[5] is out of bounds, throwing an exception.

Why this answer

The loop condition i <= data.length causes i to become 5 when data.length is 5, but valid indices are 0-4. This results in an ArrayIndexOutOfBoundsException. Option A is wrong because the exception occurs before sum reaches 15.

Option C is wrong because sum is not 0. Option D is wrong because the code compiles successfully.

18
MCQmedium

A programmer writes a switch statement to handle different cases. The code compiles and runs, but the output is unexpected: 'A' prints when the input is 'B'. Which is the most likely cause?

A.A break statement is missing after the case 'B'.
B.The switch variable type is char but should be String.
C.The switch statement is missing a default case.
D.The default case is executed instead of the matched case.
AnswerA

Fall-through from case 'B' to case 'A' occurs without break.

Why this answer

In a switch statement, when a case matches, execution continues sequentially through subsequent cases (fall-through) unless a break statement is encountered. If case 'B' lacks a break, after executing its code, the program falls through to the code for case 'A' (or the next case), printing 'A' even though the input was 'B'. This is the classic fall-through behavior in Java.

Exam trap

Oracle often tests the fall-through behavior of switch statements, where candidates mistakenly assume each case automatically exits after its code, overlooking the need for an explicit break statement.

How to eliminate wrong answers

Option B is wrong because the switch variable type being char is perfectly valid for a switch statement; changing it to String is not required and would not cause the described symptom. Option C is wrong because a missing default case does not cause a matched case to produce output from a different case; it simply means no code runs if no match occurs. Option D is wrong because the default case is only executed when no other case matches; if the input is 'B', the matched case 'B' executes first, and the default would only run if fall-through occurs (which is not the issue here).

19
MCQeasy

A programmer wants to iterate over a list of strings and print each that starts with 'A'. Which loop construct is best suited?

A.Do-while loop
B.Enhanced for loop
C.Traditional for loop with index
D.While loop with iterator
AnswerB

Simplest for iterating over all elements.

Why this answer

The enhanced for loop (for-each) is best suited because it provides a clean, concise syntax for iterating over a collection like a List<String> without needing an explicit index or iterator. It directly yields each element, allowing a simple if-statement to check if the string starts with 'A' and print it, making the code more readable and less error-prone.

Exam trap

The 1Z0-811 exam often tests the misconception that a traditional for loop with an index is always the most flexible or efficient choice, but for simple element access without index manipulation, the enhanced for loop is the idiomatic and recommended construct in Java.

How to eliminate wrong answers

Option A is wrong because a do-while loop is a post-test loop that always executes the body at least once, which is unnecessary and less readable for iterating over a list where the number of elements is known. Option C is wrong because a traditional for loop with an index requires manual index management and bounds checking, adding complexity and potential off-by-one errors without any benefit for simple element access. Option D is wrong because a while loop with an iterator, while functional, requires explicit calls to hasNext() and next(), introducing more boilerplate and the risk of NoSuchElementException if not handled correctly, making it less elegant than the enhanced for loop.

20
MCQmedium

A developer is writing a method to find the first occurrence of a negative number in an array and return its index, or -1 if none found. The current implementation uses a for loop with an if condition and a return when found. However, the method throws a NullPointerException when the array is null. The developer wants to handle this edge case gracefully and still return -1. Which approach is most appropriate?

A.Add a null check at the beginning of the method and return -1 if null
B.Use an enhanced for loop with a null check
C.Use a try-catch block inside the loop
D.Use a while loop with a null check inside
AnswerA

This handles the null case elegantly and prevents the exception.

Why this answer

It directly checks if the array reference is null before any iteration, returning -1 immediately. This is the simplest and most efficient way to handle a null input, avoiding any attempt to access the array's length or elements, which would throw a NullPointerException. The method's contract is preserved by returning -1 when no negative number is found, including the case of a null array.

Exam trap

Oracle often tests the misconception that a null check inside a loop (or using a try-catch) can handle a null array, but the NullPointerException occurs before the loop body executes, making any inside-loop handling ineffective.

How to eliminate wrong answers

Option B is wrong because an enhanced for loop still requires the array reference to be non-null to iterate; if the array is null, the loop will throw a NullPointerException before any null check inside the loop can execute. Option C is wrong because using a try-catch block inside the loop is inefficient and poor practice; it would catch the NullPointerException only after the loop attempts to access the null array, and the exception would occur before the loop even starts, not inside it. Option D is wrong because a while loop with a null check inside still requires the array reference to be non-null to evaluate the loop condition (e.g., index < array.length), which throws a NullPointerException before the null check inside the loop body can execute.

21
Multi-Selectmedium

Which THREE are valid loop constructs in Java? (Choose three.)

Select 3 answers
A.while (condition) { }
B.repeat { } until (condition);
C.do { } while (condition);
D.loop (condition) { }
E.for (initialization; condition; update) { }
AnswersA, C, E

Standard while loop.

Why this answer

The `while` loop is a standard Java construct that repeatedly executes a block of code as long as the specified boolean condition evaluates to `true`. The syntax `while (condition) { }` is valid even with an empty body, as the condition is checked before each iteration.

Exam trap

Oracle often tests the recognition of valid Java syntax versus constructs from other languages, so candidates may mistakenly select `repeat-until` or `loop` if they are familiar with other programming languages or do not recall Java's exact loop keywords.

22
Drag & Dropmedium

Arrange the steps to define a class with a main method in Java in the correct order.

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order
1Step 1
2Step 2
3Step 3
4Step 4

Why this order

First declare the class, then define the main method, add other members, write code in main, and finally compile and run.

23
Multi-Selectmedium

Which THREE statements are true about the switch statement in Java? (Choose three.)

Select 3 answers
A.It can be used with boolean expressions.
B.The default case must be placed at the end of the switch block.
C.Without a break statement, execution falls through to the next case.
D.The default case is optional.
E.It can be used with String objects.
AnswersC, D, E

True. Without a break, execution falls through to the next case (fall-through behavior).

Why this answer

Options C, D, and E are true. Option C correctly describes fall-through behavior: without a break statement, execution continues to the next case. Option D correctly states that the default case is optional.

Option E is true because, since Java 7, the switch statement can be used with String objects. Options A and B are false: A is incorrect because switch does not support boolean expressions; B is incorrect because the default case can appear anywhere in the switch block.

Exam trap

Candidates often mistakenly believe that switch can be used with boolean expressions or that the default case must be at the end. Also, many think that switch supports String objects in older Java versions.

24
MCQmedium

What is the output of the code? ```java for (int i = 0; i < 5; i++) { if (i == 2) { continue; } System.out.print(i + " "); } ```

A.0 1 2 3 4
B.1 3 4
C.0 1 2 3
D.0 1 3 4
AnswerD

Correct output.

Why this answer

The code uses a for loop that iterates from i = 0 to i < 5 (i.e., 0 through 4). Inside the loop, there is an if condition that checks if i equals 2. When i == 2, the continue statement is executed, which skips the rest of that iteration, so the System.out.print statement is not executed for i = 2.

Therefore, the loop prints 0, 1, 3, and 4, each followed by a space. Option D correctly lists this output.

Exam trap

The trap here is that candidates may forget that continue skips only the current iteration, not the entire loop, leading them to think the loop stops entirely or to misplace the starting value.

How to eliminate wrong answers

Option A is wrong because it includes 2, which is skipped by the continue statement when i == 2. Option B is wrong because it omits 0, which is printed before the continue condition is met, and also omits 2 but incorrectly includes 1, 3, 4 without 0. Option C is wrong because it stops at 3, missing 4, as the loop condition i < 5 would continue to i = 4.

25
Multi-Selecthard

Which THREE statements are true about the break and continue statements in Java? (Choose three.)

Select 3 answers
A.A labeled break can be used to exit an outer loop.
B.The continue statement skips the current iteration and proceeds to the next iteration.
C.The break statement terminates the innermost enclosing loop or switch.
D.The continue statement can be used to exit a loop entirely.
E.The break statement cannot be used outside a loop.
AnswersA, B, C

Correct: labeled break exits outer loop.

Why this answer

A labeled break in Java allows you to specify a label on an outer loop and then use 'break label;' to exit that outer loop directly, not just the innermost loop. This is useful for breaking out of nested loops when a condition is met in an inner loop.

Exam trap

The trap here is that candidates often confuse the behavior of 'continue' (which only skips the current iteration) with 'break' (which terminates the loop), and they may forget that 'break' is also valid in switch statements, not just loops.

26
MCQmedium

A novice developer wrote a condition: if (x = 10) { ... } What is the result?

A.The condition always evaluates to true
B.It executes the block if x equals 10
C.Runtime exception thrown
D.Compilation error
AnswerD

x=10 is an assignment expression, returning int, which cannot be used as boolean.

Why this answer

In Java, the assignment operator `=` is used to assign a value, not to compare values. The condition `if (x = 10)` attempts to assign 10 to `x` within an `if` statement, which is not a boolean expression. Java requires the condition in an `if` statement to evaluate to a `boolean`, so this code will not compile.

Option D is correct because the compiler will report an error, typically stating 'incompatible types: int cannot be converted to boolean'.

Exam trap

The trap here is that candidates from other programming backgrounds (like C or JavaScript) may expect the assignment to be treated as a truthy value, but Java strictly requires a boolean condition, making this a compilation error.

How to eliminate wrong answers

Option A is wrong because the condition does not evaluate to true; it is not a valid boolean expression and causes a compilation error. Option B is wrong because the code does not execute the block when x equals 10; the assignment operator `=` changes the value of x to 10, but the expression `x = 10` is an int, not a boolean, so the if statement is invalid. Option C is wrong because no runtime exception occurs; the error is caught at compile time, not at runtime.

27
Multi-Selecthard

Which three statements about the switch statement in Java are true?

Select 3 answers
A.a break statement is optional
B.switch can use char as the expression type
C.the switch statement can have multiple default cases
D.the default case is executed when no other case matches
E.switch can use boolean as the expression type
AnswersA, B, D

A `break` statement is indeed optional within a Java `switch` block, satisfying the 'true' constraint. Its omission results in "fall-through" behaviour, where execution continues into subsequent `case` blocks until a `break` is encountered or the `switch` block ends. This deliberate design allows for scenarios where multiple `case` labels should execute the same code, making `break` a control flow choice rather than a mandatory syntax element.

Why this answer

Options A, B, and D are true. A: The break statement is optional; without it, execution falls through to the next case. B: char can be used as the switch expression type because char is an integer-compatible type.

D: The default case executes when no other case matches. C is false because only one default case is allowed. E is false because boolean is not allowed as a switch expression.

28
Multi-Selecteasy

Which TWO of the following are valid loop constructs in Java? (Choose two.)

Select 2 answers
A.do {} while (false);
B.while (true)
C.for each (int i : array) {}
D.loop (int i = 0; i < 10; i++) {}
E.for (int i = 0; i < 10; i++) {}
AnswersA, E

Correct do-while loop syntax, including the required semicolon.

Why this answer

A valid do-while loop; the semicolon after the condition is required. Option E is a standard for loop. Option B is invalid because 'while (true)' lacks a loop body (statement or block).

Option C uses incorrect syntax: 'for each' is not Java; the correct syntax is 'for (int i : array)'. Option D uses 'loop' which is not a Java keyword; the correct keyword is 'for'.

29
Multi-Selecteasy

Which TWO statements are true about the switch statement in Java? (Choose two.)

Select 2 answers
A.It can be used with char variables.
B.The break statement is mandatory at the end of each case.
C.The default case is optional.
D.Case labels can be runtime expressions.
E.It can be used with long variables.
AnswersA, C

char is supported in switch.

Why this answer

Options A and C are correct. A: Switch supports char, int, short, byte, String, and enum types, so char is valid. B is false because the break statement is optional; without it, execution falls through to the next case.

C is true: the default case is optional. D is false because case labels must be compile-time constant expressions, not runtime expressions. E is false because long variables are not allowed in switch statements.

30
MCQhard

A developer is troubleshooting a performance issue in a reporting application. A nested loop iterates over a large dataset: the outer loop processes each row, and the inner loop performs a complex computation on each column. The application is taking longer than expected. Upon reviewing the code, the developer notices that the inner loop's termination condition is recalculated each iteration, which involves a costly method call. Which optimization should the developer implement to improve performance?

A.Use the break statement to exit early based on a precomputed value
B.Move the inner loop's condition calculation outside the outer loop
C.Convert the loops to recursive calls
D.Change the inner loop to use a while loop
AnswerB

By storing the result of the costly method in a variable before the inner loop, the method is called only once per outer iteration.

Why this answer

Moving the condition calculation outside the outer loop (e.g., storing the result of the costly method call in a variable before the inner loop) eliminates redundant calls, improving performance. Option A is incorrect because using a break statement based on a precomputed value would not address the condition recalculation; the break would exit early but the condition is still recalculated each iteration unless moved outside. Option C is incorrect because converting to recursive calls would typically add overhead (stack frames) and is not a performance optimization for this specific issue.

Option D is incorrect because simply changing to a while loop does not change the fact that the condition is recalculated each iteration; the costly method call would still be made each time unless the limit is precomputed.

31
Multi-Selecteasy

Which THREE of the following are valid loop constructs in Java?

Select 3 answers
A.while loop
B.for loop
C.switch statement
D.if statement
E.do-while loop
AnswersA, B, E

Correct: The while loop is a standard loop construct in Java.

Why this answer

The correct answers are A (while loop), B (for loop), and E (do-while loop) because all three are valid loop constructs in Java. The while loop repeats as long as a condition is true, the for loop provides a compact iteration mechanism, and the do-while loop guarantees at least one execution.

Exam trap

A common trap is forgetting that do-while is a valid loop construct. Candidates often select only while and for, but do-while is also a legitimate loop in Java.

32
MCQmedium

A junior developer wrote a while loop that never terminates. What is the most likely cause?

A.The loop condition is always true
B.The loop variable is incremented correctly
C.The loop uses a for structure
D.The loop body contains a break statement
AnswerA

If the condition never evaluates to false, the loop continues indefinitely.

Why this answer

A while loop terminates only when its boolean condition evaluates to false. If the condition is always true, the loop will run indefinitely, causing an infinite loop. In Java, this typically happens when the loop variable is not updated or the condition logic is flawed.

Exam trap

The trap here is that candidates may think a break statement always causes termination, but in this context, a break would actually prevent an infinite loop, not cause it.

How to eliminate wrong answers

Option B is wrong because correctly incrementing the loop variable would help the loop terminate, not cause it to never terminate. Option C is wrong because the loop structure (while vs for) does not inherently cause infinite loops; a for loop can also be infinite if its condition is always true. Option D is wrong because a break statement inside the loop body would provide an exit mechanism, preventing an infinite loop.

33
MCQhard

A developer needs to iterate over a 2D array row by row and exit early if a specific value is found in any cell. Which nested loop structure with control statements is most efficient?

A.Outer for with inner for, use return
B.Outer while with inner for, use continue
C.Outer do-while with inner while, use break without label
D.Outer for with inner for, use labeled break
AnswerD

Labeled break can exit the outer loop directly, making it efficient.

Why this answer

A labeled break allows the developer to exit both the inner and outer loops immediately when the target value is found. This is the most efficient approach for a row-by-row search in a 2D array, as it avoids unnecessary iterations after the value is located. Using a labeled break provides precise control over nested loop termination without requiring additional flags or method extraction.

Exam trap

Oracle often tests the distinction between break (unlabeled) and labeled break in nested loops, trapping candidates who assume break exits all loops when it only exits the innermost one.

How to eliminate wrong answers

Option A is wrong because using return inside a nested loop will exit the entire method, which is not appropriate if the method needs to continue executing after the loop (e.g., to process other logic). Option B is wrong because continue only skips the current iteration of the innermost loop, not the entire nested structure, so it cannot exit early when the value is found. Option C is wrong because break without a label only exits the innermost loop (the inner while), leaving the outer do-while to continue iterating, which fails to achieve early exit from both loops.

34
Matchingmedium

Match each Java operator to its description.

Drag a concept onto its matching description — or click a concept then click the description.

Concepts
Matches

Increment by 1

Modulo (remainder) operator

Logical AND (short-circuit)

Checks if an object is of a certain type

Ternary conditional operator

Why these pairings

The correct matches are: == for equality, && for logical AND. Common confusions include mixing assignment (=) with comparison (==) and misunderstanding the ternary operator vs. logical operators.

35
MCQhard

A developer writes: for(int i=0; i<10; i++) { if(i%2==0) continue; System.out.print(i); }. What is the output?

A.0123456789
B.13579
C.02468
D.123456789
AnswerB

Correctly prints odd numbers.

Why this answer

The loop iterates from i=0 to i=9. The `continue` statement skips the rest of the loop body when the condition `i%2==0` is true (i.e., when i is even). Therefore, only odd values of i (1, 3, 5, 7, 9) are printed, producing the output '13579'.

Option B is correct.

Exam trap

The trap here is that candidates often confuse the `continue` statement with `break` or misread the condition `i%2==0` as selecting odd numbers, leading them to choose the even-number output (02468) or the full range.

How to eliminate wrong answers

Option A is wrong because it prints all digits 0-9, which would occur only if the `continue` statement were removed or never executed. Option C is wrong because it prints even digits (0,2,4,6,8), which would result from skipping odd numbers (i%2!=0) instead of even numbers. Option D is wrong because it prints 1-9 but omits 0, which would happen if the loop started at i=1 or if the condition checked i%2==1, but the given code starts at i=0 and skips evens, so 0 is skipped and 1-9 are printed only for odds.

36
MCQhard

Consider a method that processes a two-dimensional array (matrix). It uses nested for loops. The inner loop uses a label 'outer' to break out of the outer loop. Under what condition is this label beneficial?

A.When you want to skip the current iteration of the outer loop
B.When you need to exit the outer loop from inside the inner loop
C.When you have a single loop and need to break to a specific point
D.When you want to exit the inner loop only
AnswerB

Labeled break allows jumping out of the outer loop directly.

Why this answer

In Java, a labeled break statement allows you to exit an outer loop from within a nested inner loop. The label 'outer' is placed before the outer loop, and when the break outer; statement executes inside the inner loop, control jumps directly to the statement after the outer loop. This is beneficial specifically when you need to terminate the entire outer loop based on a condition detected inside the inner loop.

Exam trap

Oracle exams often test the distinction between labeled break and labeled continue; the trap here is that candidates confuse 'breaking out of the outer loop' with 'skipping the current iteration of the outer loop,' which is the function of a labeled continue.

How to eliminate wrong answers

Option A is wrong because skipping the current iteration of the outer loop is done with a labeled continue statement, not a labeled break. Option C is wrong because labels are only useful with nested loops; a single loop does not need a label to break—a simple break suffices. Option D is wrong because exiting only the inner loop is the default behavior of an unlabeled break; a label is unnecessary for that purpose.

37
MCQmedium

A team is implementing a search algorithm that iterates over an array of integers. The loop should stop as soon as the target value is found. Which loop construct is most appropriate?

A.While loop with a flag variable
B.Enhanced for loop with continue
C.Do-while loop
D.For loop with break
AnswerD

A for loop with break is the most direct way to iterate and stop on condition.

Why this answer

The most appropriate loop construct for this scenario is a for loop with a break statement. A for loop provides a concise way to iterate over an array by index, and the break statement allows the loop to terminate immediately once the target value is found, avoiding unnecessary iterations. While a while loop with a flag variable could also work, the for loop is more idiomatic and less error-prone.

An enhanced for loop supports break as well, but it lacks access to the loop index, which may be needed. A do-while loop is not suitable because it guarantees at least one iteration even if the array is empty or the target is found early. Therefore, option D is correct.

38
MCQmedium

Which loop best suits a scenario where the number of iterations is unknown and depends on user input?

A.for loop
B.while loop
C.for-each loop
D.do-while loop
AnswerB

Condition checked before each iteration, suitable for unknown iterations.

Why this answer

The while loop is best when the number of iterations is unknown and depends on user input because it evaluates a boolean condition before each iteration, allowing the loop to continue as long as the condition remains true. This is ideal for scenarios like reading user input until a sentinel value is entered, where the exact number of iterations cannot be predetermined.

Exam trap

The trap here is that candidates often choose the do-while loop thinking it is better for user input because it always runs at least once, but the question specifies the number of iterations is unknown, and the while loop is more appropriate when the loop may need to be skipped entirely based on initial input.

How to eliminate wrong answers

Option A is wrong because a for loop is typically used when the number of iterations is known or can be calculated before the loop begins, such as iterating over a fixed range of values. Option C is wrong because a for-each loop is designed to iterate over all elements in a collection or array, and it does not allow dynamic termination based on user input. Option D is wrong because a do-while loop guarantees at least one execution, which may not be appropriate if the loop should not run at all when the user input immediately satisfies the exit condition.

39
MCQmedium

Refer to the exhibit. What is the output?

A.3
B.6
C.4
D.5
AnswerD

The output '5' arises from correctly evaluating the `length` property of the array presented in the exhibit. Java arrays provide a public `length` field, not a method, which precisely indicates the total number of elements they can hold. This scenario tests the fundamental understanding of array instantiation and how to determine its size, satisfying the constraint of correctly accessing array properties.

Why this answer

The loop iterates i=0,1,2. For i=0: count becomes 1, then 2. For i=1: count becomes 3, continue skips second increment, so count stays 3.

For i=2: count becomes 4, then 5. Output is 5.

40
MCQeasy

A developer writes the following code: if (score >= 90) { grade = 'A'; } else if (score >= 80) { grade = 'B'; } else if (score >= 70) { grade = 'C'; } else { grade = 'D'; } What is the value of grade if score is 75?

A.'B'
B.'C'
C.'D'
D.'A'
AnswerB

score >= 70 is true, so grade is assigned 'C'.

Why this answer

The code uses a cascading if-else-if structure that evaluates conditions from top to bottom. When score is 75, the first condition (score >= 90) is false, the second (score >= 80) is false, and the third (score >= 70) is true, so grade is assigned 'C'. The else block is only reached if all prior conditions are false.

Exam trap

Oracle often tests the candidate's understanding that the else-if chain stops at the first true condition, so a score of 75 correctly falls into the 'C' range, not 'D' or 'B'.

How to eliminate wrong answers

Option A is wrong because 'B' would require score >= 80, but 75 is less than 80, so the second condition fails. Option C is wrong because 'D' is assigned only if all conditions are false (score < 70), but 75 is >= 70, so the third condition is true and grade becomes 'C'. Option D is wrong because 'A' requires score >= 90, but 75 is less than 90, so the first condition fails.

41
MCQhard

What is the value of sum printed? int sum = 0; for (int i = 0; i < 3; i++) { sum = sum + i; } System.out.println(sum);

A.6
B.0
C.3
D.1
AnswerC

The value 3 is printed because the code correctly implements an arithmetic operation or a loop that iterates precisely three times. For instance, if a `for` loop is initialised to `i = 0` and its condition is `i < 3`, the loop body will execute for `i = 0, 1, 2`, resulting in three increments to the `sum` variable. This satisfies the constraint of the loop's termination condition accurately determining the final accumulated value.

Why this answer

The loop initializes sum to 0 and iterates i from 0 to 2 inclusive. In the first iteration, sum = 0 + 0 = 0; second iteration, sum = 0 + 1 = 1; third iteration, sum = 1 + 2 = 3. After the loop, sum is printed, so the output is 3.

Option C is correct.

Exam trap

Oracle often tests the off-by-one error where candidates mistakenly include the final value (i=3) or start counting from 1 instead of 0, leading to incorrect sums like 6 or 1.

How to eliminate wrong answers

Option A is wrong because 6 would be the result if the loop ran from i=1 to i=3 inclusive (summing 1+2+3), but the loop starts at i=0 and stops when i<3, so i never reaches 3. Option B is wrong because 0 would be the result if sum was never updated (e.g., if the loop body was empty or sum was reset each iteration), but sum accumulates the values of i. Option D is wrong because 1 would be the result if only the first iteration (i=0) contributed to sum, but the loop runs three times (i=0,1,2) and sum accumulates all three values.

42
Multi-Selectmedium

Which THREE of the following are valid types that can be used as a switch expression in Java (as of Java 8)?

Select 3 answers
A.long
B.String
C.char
D.int
E.boolean
AnswersB, C, D

String is valid since Java 7.

Why this answer

In Java 8, a switch expression can use `String`, `char`, and `int` as valid types. `String` was added in Java 7, and `char` and `int` are among the original primitive types supported. `long` and `boolean` are not allowed because `long` is a 64-bit type not supported by the switch statement's underlying `tableswitch` or `lookupswitch` bytecode instructions, and `boolean` has only two values, making it unsuitable for switch's multi-branch logic.

Exam trap

The 1Z0-811 exam often tests the misconception that `long` is a valid switch type because it is a numeric primitive, but the JVM's switch bytecode only supports 32-bit integer types, making `long` invalid.

43
MCQmedium

A company's application uses a switch statement to handle different user roles. The code currently has a bug where after processing one role, it unintentionally executes the next role's logic. Which concept is being misused?

A.Missing break statements causing fall-through
B.Incorrect default case
C.Using enum in switch
D.Using string in switch (Java 7+)
AnswerA

Missing break allows execution to continue into subsequent cases.

Why this answer

In Java, a switch statement without break statements causes fall-through, where execution continues into subsequent case blocks even after a match is found. This is exactly the bug described: after processing one role, the code unintentionally executes the next role's logic because no break terminates the case.

Exam trap

The trap here is that candidates may confuse the cause of fall-through with other switch features, such as the default case or valid types, when the core issue is simply the absence of break statements.

How to eliminate wrong answers

Option B is wrong because an incorrect default case would affect only unmatched values, not cause fall-through between matched cases. Option C is wrong because using an enum in a switch is valid and does not inherently cause fall-through; the bug is independent of the type used. Option D is wrong because using a String in a switch (introduced in Java 7) is also valid and does not cause fall-through; the issue is missing break statements, not the data type.

44
MCQhard

A developer implements a loop that processes a list of transactions. The loop must ensure that at least one transaction is processed even if the list is empty. Which loop construct guarantees this?

A.while loop
B.enhanced for loop
C.do-while loop
D.for loop
AnswerC

do-while executes body once before checking condition, guaranteeing at least one execution.

Why this answer

The do-while loop is the correct choice because it guarantees that the loop body executes at least once, regardless of the condition. In Java, the do-while loop evaluates its boolean condition after executing the loop body, so even if the list is empty (e.g., size 0), the transaction processing code inside the loop will run once before the condition is checked.

Exam trap

The 1Z0-811 exam often tests the distinction between entry-controlled (while, for) and exit-controlled (do-while) loops, trapping candidates who assume all loops can guarantee at least one execution without considering when the condition is evaluated.

How to eliminate wrong answers

Option A is wrong because a while loop evaluates its condition before the first iteration; if the list is empty, the condition (e.g., while(index < list.size())) is false initially, so the loop body never executes. Option B is wrong because an enhanced for loop iterates over elements of a collection or array; if the list is empty, there are no elements to iterate over, so the loop body never runs. Option D is wrong because a for loop (traditional) evaluates its condition before each iteration; if the list is empty, the condition (e.g., for(int i=0; i<list.size(); i++)) is false initially, so the loop body never executes.

45
MCQhard

A developer is writing a batch processing application that reads a list of orders and processes each one. The orders are stored in an array of Order objects. The processing logic is complex and involves multiple conditional checks. The developer uses a for-each loop to iterate over the array. However, during testing, the application throws an IndexOutOfBoundsException when processing orders that have a status of "CANCELLED". The developer wants to skip the processing of cancelled orders but still record that the order was skipped in a log. The current code is: for (Order order : orders) { if (order.getStatus().equals("CANCELLED")) { // Skip } // process order process(order); log(order); } The developer considers four options: A. Change the for-each loop to a traditional for loop with an index and increment only when order is not cancelled. B. Add a continue statement inside the if block. C. Change the if condition to check for non-cancelled orders and wrap only the process(order) call inside the if block, leaving log(order) outside. D. Use a while loop with an iterator and remove cancelled orders from the array. Which option best solves the problem without modifying the array and while still logging all orders?

A.Change the if condition to check for non-cancelled orders and wrap only the process(order) call inside the if block, leaving log(order) outside.
B.Change the for-each loop to a traditional for loop with an index and increment only when order is not cancelled.
C.Add a continue statement inside the if block.
D.Use a while loop with an iterator and remove cancelled orders from the array.
AnswerA

This option logs all orders, including cancelled ones, but it does not skip processing correctly; it still calls process(order) for cancelled orders if the condition is not properly set. The explanation in the stem misstates this option's effect.

Why this answer

Option A correctly logs all orders, including cancelled ones, by placing log(order) outside the if block. It processes only non-cancelled orders, avoiding the exception. Option C (continue) would skip both process and logging, failing to log cancelled orders.

Option B unnecessarily complicates the loop and may still encounter index issues, while Option D modifies the array, which is prohibited. Therefore, A is the best choice.

46
MCQeasy

A developer needs to iterate over an array of integers and compute the sum of its elements. Which loop construct is most appropriate for this task?

A.while loop
B.Enhanced for loop
C.switch statement
D.do-while loop
AnswerB

Simplest and clearest for iterating over all elements.

Why this answer

The enhanced for loop (for-each) is the most appropriate construct for iterating over an array of integers to compute a sum because it provides a concise, read-only traversal without needing an explicit index or iterator. It directly accesses each element in sequence, reducing boilerplate and the risk of off-by-one errors, which is ideal for aggregation operations like summation.

Exam trap

Oracle often tests the misconception that a while or do-while loop is always required for array iteration, leading candidates to overlook the enhanced for loop's suitability for simple, index-free traversal tasks like summation.

How to eliminate wrong answers

Option A is wrong because a while loop requires manual initialization, condition checking, and increment of an index variable, making it more verbose and error-prone for simple array iteration. Option C is wrong because a switch statement is a selection construct for branching based on a single value, not a loop, and cannot iterate over array elements. Option D is wrong because a do-while loop, like the while loop, requires explicit index management and guarantees at least one execution, which is unnecessary overhead when the array may be empty.

47
MCQhard

In a nested loop structure, a developer wants to exit completely from the outer loop when a certain condition is met inside the inner loop. Which approach is correct?

A.Use a return statement within the inner loop.
B.Use a continue statement with a label.
C.Use a labeled break statement (e.g., break outerLabel;).
D.Use a break statement inside the inner loop.
AnswerC

Exits the outer loop immediately.

Why this answer

Java's labeled break statement allows a developer to specify an outer loop label and break out of that loop entirely from within an inner loop. This is the only control flow mechanism designed to exit multiple nested loops at once, as a plain break only exits the innermost loop.

Exam trap

Oracle often tests the distinction between break, continue, and labeled versions, trapping candidates who think a plain break exits all loops or that continue can exit a loop.

How to eliminate wrong answers

Option A is wrong because a return statement would exit the entire method, not just the outer loop, which is too drastic and may leave resources unclosed or skip necessary cleanup. Option B is wrong because a continue statement with a label skips the current iteration of the labeled loop and continues with the next iteration, rather than exiting the loop entirely. Option D is wrong because a plain break statement inside the inner loop only terminates that inner loop, not the outer loop, so the outer loop continues executing.

48
MCQmedium

What is the output of the program?

A.Two
B.Two Three Default
C.Compilation fails because case 2 is missing a break.
D.Two Three
AnswerD

Fall-through from case 2 to case 3, then break.

Why this answer

The switch statement matches the value 2, executing the case 2 block which prints 'Two'. Since there is no break statement, execution falls through to case 3, printing 'Three'. The default case is not executed because fall-through stops at the end of the switch block.

Thus, the output is 'Two Three'.

Exam trap

Oracle often tests the concept of fall-through in switch statements, where candidates mistakenly assume that each case is isolated and requires a break to avoid compilation errors, or that the default case always executes regardless of a match.

How to eliminate wrong answers

Option A is wrong because it ignores the fall-through from case 2 to case 3, which prints 'Three' as well. Option B is wrong because the default case is only executed if no matching case is found; here case 2 matches, so default is skipped. Option C is wrong because a missing break does not cause compilation failure; it is syntactically valid and results in fall-through behavior.

49
MCQeasy

A developer writes a loop that iterates over an array of integers. The loop should stop when it encounters a negative number. Which control flow construct best achieves this?

A.do-while loop
B.for loop with break inside if condition
C.enhanced for loop with return
D.while loop with continue
AnswerB

Correctly exits the loop when negative number is encountered.

Why this answer

A for loop with a break statement allows the developer to iterate over an array of integers and immediately exit the loop when a negative number is encountered. The break statement terminates the loop's execution unconditionally, making it the most direct and readable control flow construct for this requirement.

Exam trap

Candidates often confuse 'continue' (which skips to the next iteration) with 'break' (which exits the loop entirely), leading them to incorrectly select Option D when they need to stop the loop upon encountering a negative number.

How to eliminate wrong answers

Option A is wrong because a do-while loop guarantees at least one iteration before checking the condition, which is unnecessary and could cause the loop to process a negative number before stopping. Option C is wrong because an enhanced for loop with return would exit the entire method, not just the loop, which is an overly broad and incorrect control flow for this scenario. Option D is wrong because a while loop with continue would skip the current iteration and proceed to the next, not stop the loop entirely when a negative number is found.

Ready to test yourself?

Try a timed practice session using only Java Control Flow Loops questions.