CCNA Control Flow and Loops Questions

52 questions · Control Flow and Loops · 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

Option C is correct because 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

Option A is correct because 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

Option D is correct because continue skips the rest of the loop body for the current iteration. Option A is wrong because return exits the method. Option B is wrong because break exits the loop.

Option C is wrong because exit is not a Java keyword.

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

Options B and D are true. B: break can be used in a switch case. D: break with a label exits the labeled loop.

A is false because break exits the entire loop, not just the iteration. C is false because continue skips iterations. E is false because break requires an enclosing 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

Option B is correct because 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

Option A is correct. In a traditional switch, without break, execution continues into the next case (fall-through). Option B is wrong because compile error occurs only if there is syntax issue.

Option C is wrong because no runtime exception. Option D is wrong because it does not skip.

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

Option B is correct because continue is used to skip the rest of the current iteration and proceed to the next. Option A (exit loop) uses break. Option C (switch fall-through) is not related.

Option D (skip iteration conditionally) is exactly what continue does.

10
MCQhard

What is printed by the program?

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

Break outer exits the outer loop when i=1 and j=1.

Why this answer

The program uses nested for loops: the outer loop runs with variable `i` from 0 to 1 (inclusive), and the inner loop runs with variable `j` from 0 to 2 (inclusive). For each iteration of the outer loop, the inner loop completes all its iterations, printing `i,j` pairs separated by spaces. This produces the sequence: 0,0 0,1 0,2 1,0.

The outer loop stops when `i` becomes 2 (since the condition `i < 2` fails), so only two outer iterations occur.

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 and C are true. A: break exits the loop. C: return exits the method, thus terminating the loop.

B is false because continue only skips the current iteration. D is false because exit is not a Java keyword (System.exit is a method, not a statement). E is false because System.gc() does not affect loop execution.

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

What is the output of the program?

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

The loop increments count for i=0,1,3,4 (i=2 skipped).

Why this answer

Option A is correct. The loop runs for i=0,1,2,3,4. When i=2, continue skips the rest of the body, so count is not incremented.

For i=0,1,3,4, count increments each time: total 4. Option B is wrong because it incorrectly counts 5. Option C is wrong because it assumes break instead of continue.

Option D is wrong because the loop completes normally.

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

Option D is correct. Outer loop i=0: inner j=0-4 (5 times); i=1: j=1-4 (4); i=2: 3; i=3: 2; i=4: 1; total = 5+4+3+2+1 = 15. Option A (5) is only the outer iterations.

Option B (10) is incorrect. Option C (20) would be if both loops ran 5 times each.

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

Option A is correct because adding a counter and breaking after a maximum number of iterations provides a safeguard against infinite loops. Option B is wrong because the exact number of records may not be known in advance. Option C is wrong because a do-while loop does not solve the fundamental issue of missing sentinel.

Option D is wrong because throwing an exception is not a graceful handling and would disrupt the batch job.

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 B and D are correct. A is wrong because deep nesting reduces readability. B is correct: using break in loops for early exit improves efficiency.

C is wrong because using many else-if may indicate need for switch or polymorphism. D is correct: using enhanced for loop reduces errors. E is wrong because goto is not used in Java.

17
MCQmedium

Refer to the exhibit. 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

Option C is correct because the loop condition i <= data.length causes i to become 5, which is an invalid index (valid indices 0-4). This results in an ArrayIndexOutOfBoundsException. Option A is wrong because the exception occurs before sum reaches 15.

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

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

Cisco 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

Option A is correct because 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

Option A is correct because 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

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 TWO statements are true about the switch statement in Java? (Choose two.)

Select 2 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.
AnswersD, E

default can be omitted.

Why this answer

Option D is correct because the default case in a switch statement is optional; if no case matches and no default is present, the switch simply does nothing. Option E is correct because Java supports switch on String objects (since Java 7), comparing the switch expression against case labels using the String.equals() method.

Exam trap

Oracle often tests the misconception that the default case must be at the end, or that switch cannot be used with String, or that boolean expressions are allowed; the trap here is that candidates may incorrectly believe that the default case is mandatory or that String is not supported, while overlooking that fall-through (option C) is actually true but not one of the two required answers.

24
MCQmedium

What is the output of the code?

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 with an if condition that skips the iteration when the loop variable equals 2 using the continue statement. Therefore, the loop prints 0, 1, 3, and 4, but not 2. 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

Option A is correct because 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

Option A is correct. In Java, assignment inside if is allowed only if the type is boolean, but x=10 returns int, which is not boolean, so compilation fails. Option B (uses assignment) is wrong because it doesn't compile.

Option C (runtime error) wrong. Option D (true) wrong.

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

Break is not required; without it, fall-through occurs.

Why this answer

Options A, C, and D are true. A: char can be used as the switch expression. C: the default case executes when no other case matches.

D: a break statement is optional (fall-through is allowed). B is false because boolean is not allowed. E is false because only one default case is allowed.

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

Option A is a standard for loop. Option C is a valid do-while loop with a semicolon. Option B is missing a statement or block after 'while (true)', making it syntactically invalid.

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

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 int, char, String, and enum types. B is false because long is not supported.

C: The default case is optional. D is false because break is optional; fall-through occurs without it. E is false because case labels must be compile-time constants.

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

Option B is correct because precomputing the loop limit (e.g., storing the result of the method call in a variable before the inner loop) reduces redundant method calls. Option A is wrong because changing to a while loop doesn't address the condition recalculation. Option C is wrong because break does not reduce the number of condition evaluations.

Option D is wrong because recursion often adds overhead and is not suitable for this scenario.

31
Multi-Selecteasy

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

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

Condition is checked before each iteration.

Why this answer

Option A is correct because the while loop is a fundamental control flow structure in Java that repeatedly executes a block of code as long as a specified boolean condition evaluates to true. It is a valid loop construct defined in the Java Language Specification (JLS §14.12).

Exam trap

Oracle often tests the distinction between loop constructs and conditional statements, and the trap here is that candidates may incorrectly identify the do-while loop as invalid or forget that it is a legitimate loop, leading them to choose only while and for loops while overlooking that do-while is also valid but not required for the answer.

32
MCQmedium

A developer writes a loop to iterate over an array of integers. The loop must sum all elements and stop early if the sum exceeds 100. Which control flow construct should be used?

A.while(true) { sum += arr[i]; i++; }
B.for(int i=0; i<arr.length; i++) { sum += arr[i]; if(sum > 100) break; }
C.do { sum += arr[i]; i++; } while(i<arr.length && sum <= 100);
D.for(int val : arr) { sum += val; if(sum > 100) break; }
AnswerB

Correctly uses for loop and break to exit early.

Why this answer

Option B is correct because it uses a for loop with an index variable to iterate over the array, and includes an if statement with a break to exit the loop early when the sum exceeds 100. This ensures all elements are summed until the condition is met, and the loop stops immediately, preventing unnecessary iterations.

Exam trap

Oracle often tests the distinction between loop constructs and the correct use of break; the trap here is that candidates may choose the enhanced for loop (Option D) thinking it is simpler, but they overlook that it does not provide an index for array access, or they may incorrectly assume that the do-while loop (Option C) will stop correctly when the sum exceeds 100, when in fact it checks the condition after the body, leading to one extra iteration.

How to eliminate wrong answers

Option A is wrong because while(true) creates an infinite loop with no termination condition; it will cause an ArrayIndexOutOfBoundsException when i exceeds the array length. Option C is wrong because the do-while loop checks the condition after executing the body, so it will always execute at least once, but more critically, the condition sum <= 100 is evaluated after each iteration, which means the loop will stop after adding an element that pushes the sum over 100, but it does not break immediately; it will still execute the next iteration if the condition is false, leading to incorrect behavior. Option D is wrong because the enhanced for loop (for-each) does not provide an index variable, so it cannot be used to iterate over an array of integers in this context; it would require an array of Integer objects or a collection, and the break statement is not allowed in a for-each loop over an array in Java.

33
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

Option A is correct because 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.

34
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

Option A is correct because a labeled break exits both loops efficiently. Option B is wrong because return exits the method, not just the loops. Option C is wrong because continue only skips the inner iteration.

Option D is wrong because break without label only exits the inner loop, requiring additional checks.

35
MCQeasy

Which statement about the for-each loop in Java is true?

A.It cannot remove elements from a collection during iteration without additional logic.
B.It can modify the array elements.
C.It can iterate in reverse order.
D.It cannot be used with arrays.
AnswerA

Correct: removal causes ConcurrentModificationException.

Why this answer

Option A is correct because the for-each loop (enhanced for loop) in Java does not expose the iterator or index, so you cannot safely remove elements from a collection during iteration without using an explicit iterator and its remove() method. Attempting to remove directly will throw a ConcurrentModificationException.

Exam trap

Oracle often tests the misconception that the for-each loop can modify array elements or collections, or that it cannot be used with arrays, leading candidates to incorrectly select options B or D.

How to eliminate wrong answers

Option B is wrong because the for-each loop cannot modify the array elements themselves; it only provides a read-only reference to each element, so assigning a new value to the loop variable does not affect the original array. Option C is wrong because the for-each loop always iterates in the natural order of the array or Iterable (from first to last) and does not support reverse iteration without additional logic like using a ListIterator or a reversed copy. Option D is wrong because the for-each loop can be used with arrays; it is specifically designed to iterate over arrays and collections.

36
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

These are common operators in Java.

37
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.

38
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

Option D is correct because a labeled break is used when you need to exit an outer loop from within an inner loop based on a condition. Option A is wrong because it's not about continuing the outer loop. Option B is wrong because you can also use a flag variable.

Option C is wrong because it's specifically for nested loops, not single loops.

39
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

Option C is correct because a for loop with a break statement allows early termination after finding the target. Option A (enhanced for loop) cannot easily break when conditions are met? Actually enhanced for can use break, but it's less common? The best practice is a traditional for loop with index. Option B (while loop) is also possible but less concise.

Option D (do-while) is not ideal because it guarantees at least one iteration.

40
MCQhard

A developer implements a menu-driven application using a switch statement inside a do-while loop. The menu options are 1-4, and option 4 is supposed to exit the application. However, after selecting option 4, the menu is displayed again before the application exits. The code is structured as follows: do { displayMenu(); choice = scanner.nextInt(); switch(choice) { case 1: // process option 1 break; case 2: // process option 2 break; case 3: // process option 3 break; case 4: break; // intended to exit loop } } while(choice != 4); The developer realizes that the break inside the switch only exits the switch, not the loop. What is the correct fix?

A.Use a labeled break to exit the loop
B.Use a continue statement instead of break
C.Replace the switch with an if-else chain
D.Set a flag variable to true and check it in the loop condition
AnswerA

A labeled break (e.g., 'break outer;') exits the outer loop directly, solving the problem cleanly.

Why this answer

Option D is correct because using a labeled break can directly exit the outer do-while loop. Option A is wrong because an if-else chain would not solve the loop exit issue; it would still require a mechanism to exit the outer loop. Option B is wrong because continue would skip to the next iteration, not exit.

Option C is wrong because setting a flag is unnecessary when labeled break provides a direct solution.

41
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.

42
MCQmedium

Refer to the exhibit. What is the output?

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

As explained, final count is 5.

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.

43
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.

44
MCQhard

What is the value of sum printed?

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

Correct: sum of 1+2=3 before break.

Why this answer

The correct answer is C because the loop iterates from i=0 to i<3, incrementing i by 1 each time. Inside the loop, sum is updated as sum = sum + i, so sum becomes 0+0=0, then 0+1=1, then 1+2=3. After the loop ends, sum is 3.

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.

45
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

Cisco 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.

46
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

Option B is correct because without break, execution falls through to the next case. Option A is wrong because default handles unmatched cases, not fall-through. Option C is wrong because using String in switch is valid.

Option D is wrong because using enum in switch is valid.

47
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

Cisco 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.

48
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 skips processing for cancelled but still logs them, meeting all requirements.

Why this answer

Option C correctly skips only the processing for cancelled orders while still executing the log statement for them. Option A would require index management and still log for cancelled orders, but it changes the loop structure unnecessarily. Option B would skip both process and log for cancelled orders, failing the logging requirement.

Option D modifies the array by removing elements, which is not allowed ('without modifying the array'). Thus C is the best.

49
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.

50
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

Option C is correct because 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.

51
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.

52
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

Option A is correct because break exits the loop when condition met. Option B is wrong because continue skips to next iteration, doesn't stop loop. Option C is wrong because do-while executes at least once but doesn't provide early exit without additional logic.

Option D is wrong because return exits the method, which may not be desired.

Ready to test yourself?

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