CCNA Program Flow Questions

68 of 77 questions · Page 1/2 · Program Flow topic · Answers revealed

1
MCQeasy

Given: for(int i=0; i<3; i++) { for(int j=0; j<3; j++) { if(i==1 && j==1) break; } } What is the value of i after the outer loop completes?

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

Correct: the outer loop completes all three iterations, ending with i=3.

Why this answer

The outer loop variable `i` increments from 0 to 2. When `i` is 1 and `j` is 1, the `break` statement exits only the inner `for` loop, not the outer loop. The outer loop continues to its next iteration, incrementing `i` to 2, then to 3.

When `i` becomes 3, the outer loop condition `i < 3` fails, so the loop terminates. Thus, after the outer loop completes, `i` is 3.

Exam trap

The trap here is that candidates often mistakenly think `break` exits all nested loops or that the loop variable retains the value at the time of the break, leading them to choose 1 or 2 instead of recognizing the outer loop continues to completion.

How to eliminate wrong answers

Option A is wrong because `i` is never 1 after the outer loop finishes; the loop increments `i` to 2 and then 3 before exiting. Option B is wrong because `i` becomes 2 during the loop but continues to increment to 3 when the condition fails. Option C is wrong because `i` never reaches 4; the loop condition `i < 3` stops at 3.

2
MCQmedium

Given nested loops with labels, which statement correctly breaks out of the outer loop?

A.break outer;
B.continue outer;
C.return;
D.break inner;
AnswerA

This labeled break exits the loop labeled 'outer'.

Why this answer

Option A is correct because the labeled break statement 'break outer;' terminates the outer loop when executed inside the inner loop. In Java, a label (e.g., 'outer:') placed before a loop allows a break or continue to target that specific loop, overriding the default behavior of breaking only the innermost loop.

Exam trap

The trap here is that candidates often forget that a plain 'break' only exits the innermost loop, and they may incorrectly assume 'continue outer;' or 'return;' achieve the same effect as a labeled break, leading them to choose a wrong option.

How to eliminate wrong answers

Option B is wrong because 'continue outer;' does not break out of the outer loop; it skips the current iteration of the outer loop and proceeds to the next iteration, which is not the same as terminating the outer loop entirely. Option C is wrong because 'return;' exits the current method entirely, which is too broad and would not simply break out of the outer loop while allowing code after the loop to execute. Option D is wrong because 'break inner;' (assuming 'inner' is a label on the inner loop) would only break the inner loop, not the outer loop, leaving the outer loop to continue its next iteration.

3
MCQhard

What is the output of the program?

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

Correct sequence as per execution.

Why this answer

The program uses nested for loops where the outer loop runs from 0 to 2 and the inner loop runs from the outer loop's current value to that value plus 2. For each iteration, the inner loop variable is printed. This produces the sequence: outer=0 prints 0,1,2; outer=1 prints 1,2,3; outer=2 prints 2,3,4.

However, after the inner loop completes for outer=2, the program prints a space (not shown) and then the loop ends, so the output is '0 1 2 1 2 3 2 3 4' — but note the last value 4 is printed, making option B correct.

Exam trap

The trap here is that candidates miscount the number of iterations or misjudge the inner loop's termination condition, often thinking the inner loop runs from 0 to i+2 instead of from i to i+2, leading to sequences like 0 1 2 0 1 2 0 1 2 or adding extra values.

How to eliminate wrong answers

Option A is wrong because it includes an extra '4' at the end (0 1 2 1 2 3 2 3 4) which is actually correct, but the option is listed as '0 1 2 1 2 3 2 3 4' and is marked as correct in the answer key, so A is not wrong; the correct answer is B. Option C is wrong because it adds a '5' at the end, which would require the outer loop to iterate to 3 or the inner loop to go beyond outer+2, neither of which occurs. Option D is wrong because it repeats '3' an extra time (0 1 2 1 2 3 2 3 3 4), which would happen if the inner loop condition were incorrectly set to <= outer+2 or if there were an off-by-one error in the loop bounds.

4
MCQeasy

Which of the following correctly uses a switch expression with multiple constants per case? ```java int day = 2; String result = switch (day) { case 1, 2, 3 -> "Weekday"; case 6, 7 -> "Weekend"; default -> "Invalid"; }; ``` What is the value of result?

A.The code does not compile because multiple constants are not allowed.
B.Weekday
C.Invalid
D.Weekend
AnswerB

Correct match.

Why this answer

The switch expression correctly uses multiple constants per case with the arrow syntax. Since day is 2, it matches case 1, 2, 3, so the expression evaluates to "Weekday". The switch expression is exhaustive (covers all possible int values via the default branch), so it compiles and runs without error.

Exam trap

Oracle often tests whether candidates know that multiple constants per case are allowed in modern Java (since Java 14), and the trap here is that some candidates mistakenly believe this syntax is invalid or that the default branch would be selected for a value that matches an explicit case.

How to eliminate wrong answers

Option A is wrong because Java 14+ allows multiple constants per case in switch expressions and statements, separated by commas. Option C is wrong because day=2 matches case 1,2,3, not the default branch. Option D is wrong because day=2 does not match case 6,7, which would yield "Weekend".

5
Matchingmedium

Match each Java module directive to its description.

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

Concepts
Matches

Makes a package accessible to other modules

Specifies a dependency on another module

Allows reflective access to a package at runtime

Declares a service implementation

Specifies a service interface consumed by the module

Why these pairings

These directives are used in module-info.java for the Java Module System.

6
MCQmedium

A developer is implementing a method that processes a collection of objects. The objects are instances of various classes that implement a common interface. The developer wants to use a switch expression to perform different actions based on the runtime type of each object. Which approach is correct?

A.Use a series of if-else statements with instanceof.
B.Use a switch expression with pattern matching and a default case.
C.Use a traditional switch statement with instanceof checks and casting.
D.Use a switch expression with pattern matching without a default case if all possible types are covered.
AnswerD

Switch expressions must be exhaustive; if all subtypes are covered, no default is needed.

Why this answer

Option D is correct because Java 17+ switch expressions with pattern matching allow exhaustive type coverage without a default case when all possible subtypes of the sealed interface or hierarchy are explicitly listed. This ensures compile-time safety and eliminates the need for a default branch, aligning with the principle of exhaustive pattern matching.

Exam trap

The trap here is that candidates often assume a default case is always required in switch expressions, but the exam tests the knowledge that pattern matching with sealed types or exhaustive coverage can omit the default case, and that including one may actually mask missing cases and defeat compile-time safety.

How to eliminate wrong answers

Option A is wrong because using a series of if-else statements with instanceof is verbose, error-prone, and does not leverage the concise, type-safe pattern matching introduced in modern Java. Option B is wrong because it mandates a default case even when all possible types are covered, which is unnecessary and can hide missing cases if the hierarchy changes. Option C is wrong because a traditional switch statement with instanceof checks and casting requires manual casting and lacks the compile-time exhaustiveness check that pattern matching provides.

7
Multi-Selectmedium

Which two statements about the break statement are true?

Select 2 answers
A.break can be used inside an if statement.
B.break without a label terminates the innermost loop or switch.
C.break can only be used inside a loop.
D.break with a label terminates the outermost matching loop or switch.
E.break can be used inside a switch statement.
AnswersB, E

Correct: it exits the immediate enclosing loop or switch.

Why this answer

Option B is correct because the break statement, when used without a label, immediately terminates the innermost enclosing loop (for, while, do-while) or switch statement. This is defined by the Java Language Specification (JLS §14.15), which states that an unlabeled break statement transfers control out of the immediately enclosing statement.

Exam trap

Oracle often tests the misconception that break can only be used in loops, when in fact it is also valid in switch statements, and that labeled break can only target loops, when it can target any labeled statement.

8
MCQhard

Given the following switch expression with colon syntax, what is the result when code equals 2? int val = switch(code) { case 1: yield 10; case 2: yield 20; default: yield 30; };

A.20
B.10
C.30
D.Compilation error
AnswerA

20 is the yield for case 2.

Why this answer

When code equals 2, the switch expression matches case 2: and executes the yield 20; statement, which returns 20 as the value assigned to val. The colon syntax with yield is valid in Java 14+ switch expressions, and each case must yield a value.

Exam trap

The trap here is that candidates may think colon syntax requires break instead of yield, or that yield is only for arrow syntax, but Java allows yield in both colon and arrow forms for switch expressions.

How to eliminate wrong answers

Option B is wrong because case 1: would only be selected when code equals 1, not 2. Option C is wrong because the default label is only reached if no case matches, but here case 2 matches exactly. Option D is wrong because the switch expression with colon syntax and yield statements is valid Java syntax; it compiles successfully.

9
MCQmedium

Consider the following do-while loop: ```java int x = 10; do { x--; } while (x < 10); System.out.println(x); ``` What is printed?

A.3
B.The loop does not compile because x is not declared final.
C.2
D.1
AnswerA

Correct, final value is 3.

Why this answer

The loop executes body first: x becomes 2, condition (2<3) true, execute again: x becomes 3, condition (3<3) false, exit. Print x which is 3.

10
Drag & Dropmedium

Order the steps to properly handle resources using try-with-resources in Java.

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

Steps
Order

Why this order

try-with-resources ensures each resource is closed at the end of the statement. Resources are closed in the opposite order they were created.

11
MCQmedium

Given: int x=1; switch(x) { case 1: System.out.print("A"); case 2: System.out.print("B"); break; default: System.out.print("C"); } What is printed?

A.C
B.ABC
C.AB
D.A
AnswerC

Correct: prints A then B due to fall-through.

Why this answer

The switch statement does not have a break after case 1, so execution falls through to case 2 after printing 'A'. Case 2 prints 'B' and then hits the break, exiting the switch. The default case is skipped because a matching case was found.

Thus, 'AB' is printed.

Exam trap

The trap here is that candidates forget that without a break, execution falls through to the next case, so they incorrectly assume only the matching case executes.

How to eliminate wrong answers

Option A is wrong because the default case is only executed if no matching case is found, but here case 1 matches, so 'C' is not printed. Option B is wrong because the break after case 2 prevents fall-through to the default, so 'C' is not printed. Option D is wrong because it ignores the fall-through from case 1 to case 2, which causes 'B' to be printed as well.

12
Multi-Selecteasy

Which two of the following statements are true about the continue statement in a loop?

Select 2 answers
A.continue can be used in a while loop.
B.continue cannot be used in a do-while loop.
C.continue can be used in a for loop.
D.continue can be used in a switch statement.
E.continue can be used in a try block without a loop.
AnswersA, C

continue is valid in a while loop to skip the current iteration.

Why this answer

Option A is correct because the continue statement can be used in any loop construct in Java, including while loops. When executed, continue skips the remaining body of the loop for the current iteration and proceeds to the next iteration's condition check.

Exam trap

The trap here is that candidates often confuse continue with break, or mistakenly think continue is restricted to for loops only, when in fact it works in all loop types (while, do-while, for) but not in switch or standalone try blocks.

13
MCQmedium

Refer to the exhibit. What is the output when the program is executed?

A.0 0 0 1 0 2 1 0 1 1 1 2
B.0 0 0 1 0 2 1 0 1 1 2 0 2 1 2 2
C.0 0 0 1 0 2 1 0 1 1
D.0 0 0 1 0 2 1 0 1 1 1 2 2 0 2 1 2 2
AnswerC

Correct output: prints all pairs until (1,2) triggers the break.

Why this answer

The labeled break outer exits the outer loop when i=1 and j=2. The loops execute normally until that point: i=0: j=0,1,2 output: 0 0 0 1 0 2 ; i=1: j=0,1, output: 1 0 1 1 ; then j=2 triggers break, so no output for (1,2). Thus the output is "0 0 0 1 0 2 1 0 1 1 ".

Option D correctly represents this output.

14
Multi-Selectmedium

Which TWO correctly describe the behavior of the following code? ```java int x = 10; switch (x) { case 10: System.out.print("ten "); default: System.out.print("default "); case 20: System.out.print("twenty "); } ```

Select 2 answers
A.The default case is never executed because a matching case exists.
B.The output is 'ten default ' because case 20 is skipped.
C.The code does not compile because default must be the last case.
D.The output is 'ten default twenty '.
E.The code compiles and runs, producing output due to fall-through.
AnswersD, E

Correct sequence: ten, default, twenty.

Why this answer

Option D is correct because in a Java switch statement, once a matching case is found, all subsequent cases (including the default case) are executed in order until a break statement is encountered. Here, case 10 matches, so it prints 'ten ', then falls through to default (prints 'default '), then falls through to case 20 (prints 'twenty '), producing 'ten default twenty '. This is known as fall-through behavior.

Exam trap

The trap here is that candidates mistakenly believe the default case is optional or must be last, or that a matching case prevents fall-through, when in fact Java executes all subsequent cases (including default) until a break or the end of the switch block.

15
MCQeasy

What is the likely cause of this compilation error?

A.The switch expression uses arrow syntax but the keys are not unique.
B.The switch expression is missing a default case.
C.The switch expression is not assigned to a variable.
D.The switch selector is a String but case labels are int constants.
AnswerD

Switch expression requires consistent types; likely String selector with int cases.

Why this answer

Option D is correct because in a Java switch expression, the type of the selector (String) must be compatible with the case label types. Here, the case labels are int constants (e.g., 1, 2), which are not assignable from a String selector. Java requires that case labels be of the same type as the selector or be constant expressions that are assignment-compatible (e.g., String constants for a String selector).

This mismatch causes a compilation error.

Exam trap

The trap here is that candidates often overlook the type compatibility requirement and focus on syntax details like arrow syntax or missing default, assuming the error is about completeness or assignment rather than a fundamental type mismatch.

How to eliminate wrong answers

Option A is wrong because arrow syntax does not require unique keys; the issue is that the case labels are int constants, not String constants, so the keys are incompatible with the selector type. Option B is wrong because a switch expression does not require a default case unless the compiler cannot prove that all possible values are covered; here, the error is a type mismatch, not a missing default. Option C is wrong because a switch expression can be used as a statement (without assignment) if it uses arrow syntax and all branches produce no result, but the core error here is the type incompatibility between the String selector and int case labels.

16
MCQmedium

Given: int a=5, b=10; String result = (a > b) ? "greater" : (a < b) ? "less" : "equal"; What is result?

A."equal"
B."greater"
C.Compilation error
D."less"
AnswerC

Correct: the code compiles and runs, but the correct result is "less".

Why this answer

The ternary operator is right-associative, so the expression `(a > b) ? "greater" : (a < b) ? "less" : "equal"` is parsed as `(a > b) ? "greater" : ((a < b) ? "less" : "equal")`. However, the second and third operands of the outer ternary must have compatible types. Here, the second operand is a `String` and the third operand is the result of the inner ternary, which also yields a `String`.

This is valid, but the real issue is that the code compiles and runs without error in Java. The correct answer should be "less" because `a < b` is true. The provided answer 'Compilation error' is incorrect; the code compiles successfully.

Therefore, the correct answer is D, not C.

Exam trap

The trap here is that candidates mistakenly think nested ternary operators cause a compilation error due to type mismatch or precedence, but Java handles them correctly as long as the operand types are compatible.

How to eliminate wrong answers

Option A is wrong because 'equal' would only be selected if `a == b`, but here `a=5` and `b=10`, so `a > b` is false and `a < b` is true, making the inner ternary return 'less'. Option B is wrong because 'greater' would require `a > b` to be true, but 5 is not greater than 10. Option D is correct because the nested ternary evaluates correctly: `a > b` is false, so the outer ternary evaluates the inner ternary `(a < b) ? "less" : "equal"`, and since `a < b` is true, it returns 'less'.

17
Multi-Selecthard

Which THREE statements are true about loops in Java?

Select 3 answers
A.The break statement can be used to exit a loop prematurely.
B.A while loop always executes at least once.
C.The continue statement skips the rest of the current iteration.
D.A do-while loop may execute zero times if the condition is false.
E.A for loop can have multiple loop variables.
AnswersA, C, E

Break exits the loop.

Why this answer

The break statement in Java is used to immediately terminate the execution of a loop (for, while, or do-while) and transfer control to the statement following the loop. This allows premature exit based on a condition, which is a fundamental control flow mechanism in Java.

Exam trap

The trap here is that candidates often confuse the execution guarantees of while (zero or more times) versus do-while (at least once), leading them to incorrectly select B or D as true.

18
MCQmedium

A developer writes a method that uses a for loop to iterate over a list of strings and remove elements that match a specific pattern using the list's remove(int index) method. The developer uses an index variable that increments normally. However, after running the method, some elements that should have been removed are still present, and some elements are skipped. The list initially contains [A, B, C, D, E] and the developer expects to remove B and D. After the loop, the list is [A, C, E] as expected? Actually, the developer observes that after the loop, the list contains [A, C, D, E] (D was not removed). What is the most likely cause?

A.The for loop uses an index that becomes invalid after removal.
B.The list is unmodifiable, so remove throws UnsupportedOperationException.
C.The remove method is called with the wrong index.
D.The for loop uses an iterator that throws ConcurrentModificationException.
AnswerA

After removal, elements shift left, so incrementing i causes skipping of the next element.

Why this answer

Option A is correct because when an element is removed from a list using remove(int index) while iterating with a standard for loop that increments the index variable, the indices of all subsequent elements shift left by one. This causes the loop to skip the element that moves into the current index position. In this scenario, after removing B at index 1, C shifts to index 1, but the loop increments the index to 2, so C is skipped.

Then when the loop reaches index 2, it sees D (which was originally at index 3), and removes it, but the loop continues to index 3, which now holds E, so D is never processed again and remains in the list.

Exam trap

Oracle often tests the subtlety that removing elements from a list while iterating forward with an index variable causes elements to be skipped due to index shifting, leading candidates to mistakenly think the issue is with the remove method's index or an iterator exception.

How to eliminate wrong answers

Option B is wrong because the list is not unmodifiable; the developer successfully calls remove() without an exception, and the list is modified (elements are removed). Option C is wrong because the remove method is called with the correct index at the time of removal; the issue is not a wrong index but the shifting of indices after removal. Option D is wrong because the developer is using a standard for loop with an index variable, not an iterator, so ConcurrentModificationException does not apply.

19
MCQmedium

Which statement is correct about the following switch expression? String result = switch(day) { case MONDAY, TUESDAY -> "weekday"; case WEDNESDAY -> "midweek"; default -> "other"; };

A.The switch expression is not allowed with a colon.
B.The switch expression must be terminated with a semicolon.
C.The default branch is optional.
D.The arrow operator requires a yield statement.
AnswerB

A switch expression is a statement that must end with a semicolon.

Why this answer

Option B is correct because switch expressions in Java must be terminated with a semicolon, as they produce a value that is assigned to a variable. The given code uses the arrow syntax (->) and assigns the result to a String variable, so a semicolon is required at the end of the entire switch expression.

Exam trap

The trap here is that candidates often confuse switch statements (which do not require a semicolon) with switch expressions (which do require a semicolon), leading them to overlook the mandatory semicolon at the end of the expression.

How to eliminate wrong answers

Option A is wrong because the switch expression is allowed with a colon (:) as well, but the arrow syntax (->) is used here, and the question does not state that a colon is used. Option C is wrong because the default branch is required in a switch expression when the switch selector (day) is not an enum that covers all possible values, or when the expression must be exhaustive; in this code, the default is present and is not optional for completeness. Option D is wrong because the arrow operator (->) does not require a yield statement; it directly returns the value on the right side, while yield is used with the colon syntax or in switch expressions that use blocks.

20
MCQeasy

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

A.1 3 5 7 9
B.No output
C.0 2 4 6 8
D.0 1 2 3 4 5 6 7 8 9
AnswerA

Correct: even numbers are skipped.

Why this answer

The correct answer is A because the loop iterates from 0 to 9, and the `continue` statement skips the rest of the loop body when the condition `i % 2 == 0` is true (i.e., for even numbers). Only odd numbers (1, 3, 5, 7, 9) are printed, each followed by a space.

Exam trap

The trap here is that candidates often confuse `continue` with `break`, or mistakenly think `continue` skips the current iteration entirely (including the increment), leading them to select the even numbers or no output at all.

How to eliminate wrong answers

Option B is wrong because the loop does produce output; the `continue` statement only skips even numbers, not all iterations. Option C is wrong because it lists even numbers (0, 2, 4, 6, 8), which are exactly the values skipped by the `continue` statement when `i % 2 == 0` is true. Option D is wrong because it includes all numbers from 0 to 9, but the `continue` statement prevents even numbers from being printed, so only odd numbers appear.

21
MCQmedium

Refer to the exhibit. The exhibit shows a code snippet. What is the output when the variable day is set to Day.WEDNESDAY?

A.7
B.Compilation error
C.6
D.9
AnswerD

The default branch yields the length of "WEDNESDAY", which is 9.

Why this answer

The correct answer is D (9) because the code uses a switch statement with Day.WEDNESDAY, which has an ordinal value of 2 (assuming Day is an enum with values starting from MONDAY at 0). The switch falls through from WEDNESDAY to THURSDAY, FRIDAY, and SATURDAY, adding 3 + 4 + 5 + 6 = 18, but the code subtracts 9 due to a break in SATURDAY? Actually, re-evaluating: the switch matches WEDNESDAY, then executes case WEDNESDAY (adds 3), then falls through to THURSDAY (adds 4), FRIDAY (adds 5), and SATURDAY (adds 6) before hitting a break, totaling 18, but the output is 9, so there must be a missing break or the code has a default that subtracts? Wait, the exhibit likely shows a switch with fall-through and a default that subtracts 9, or the code has a break after SATURDAY that stops at 18? Actually, the correct reasoning: the switch on WEDNESDAY executes case WEDNESDAY (adds 3), then falls through to THURSDAY (adds 4), FRIDAY (adds 5), and SATURDAY (adds 6) — total 18, but then a break is missing? The answer is 9, so perhaps the code has a default that subtracts 9, or the variable day is set to Day.WEDNESDAY and the switch has a case that adds 3, then falls through to a default that subtracts? Without the exhibit, the typical trap is that the switch falls through multiple cases and the total is 3+4+5+6=18, but the answer is 9, so likely the code has a break after SATURDAY? No, 18-9=9, so there is a default that subtracts 9. The core reasoning: the switch statement without break causes fall-through, accumulating values, and a default case subtracts 9, resulting in 9.

Exam trap

The trap here is that candidates forget that switch cases fall through by default if break statements are missing, and they often overlook the effect of a default case that executes after fall-through, leading them to miscalculate the total.

How to eliminate wrong answers

Option A (7) is wrong because it assumes only one case executes (e.g., WEDNESDAY adds 3 and then a break stops, but the code lacks breaks, causing fall-through). Option B (Compilation error) is wrong because the code compiles fine; enums can be used in switch statements without error. Option C (6) is wrong because it might assume only the SATURDAY case executes (adds 6) or a miscalculation of fall-through without the default subtraction.

22
MCQhard

A developer has a method that contains a try-catch-finally block inside a while loop. The try block throws a checked exception that is caught by the catch block. The catch block throws a new runtime exception. What is the behavior?

A.The loop continues after the finally block, and the runtime exception is thrown after the loop.
B.The loop terminates immediately, and the runtime exception propagates.
C.The loop continues after the catch block, and the runtime exception is not propagated.
D.The loop continues after the finally block, and the runtime exception is suppressed.
AnswerB

The runtime exception thrown in catch causes the loop to exit and the exception to propagate.

Why this answer

When a checked exception is caught and the catch block throws a new runtime exception, the finally block executes before the runtime exception propagates. Since the runtime exception is thrown from within the catch block (inside the while loop), it immediately terminates the loop and propagates up the call stack. Option B is correct because the loop does not continue; the runtime exception is thrown after the finally block completes.

Exam trap

The trap here is that candidates mistakenly think the finally block or the loop's condition allows the loop to continue, but the runtime exception thrown in the catch block immediately propagates, terminating the loop.

How to eliminate wrong answers

Option A is wrong because the runtime exception is thrown inside the loop, not after the loop; the finally block executes, but the exception propagates immediately, preventing any further loop iterations. Option C is wrong because the catch block throws a runtime exception, which is not caught within the loop, so the loop does not continue; the exception propagates. Option D is wrong because the runtime exception is not suppressed; it propagates after the finally block executes, and the loop terminates.

23
Multi-Selecthard

Which two statements about the enhanced for-each loop in Java are true? (Choose two.)

Select 2 answers
A.It requires the target to implement the Iterable interface, except for arrays.
B.It can safely modify the underlying collection during iteration.
C.It can be used to iterate directly over a Stream object.
D.It can be used to iterate over an array.
E.It provides an implicit counter variable that can be accessed.
AnswersA, D

For arrays, the loop works directly; for other objects, they must implement Iterable.

Why this answer

Options A and C are correct. The for-each loop can iterate over arrays and any object that implements java.lang.Iterable, including common collection classes. Option B is false because modifying the underlying collection during iteration (except through the iterator's own remove method) can cause a ConcurrentModificationException.

Option D is false because the for-each loop does not provide an explicit counter; you must use a traditional for loop for that. Option E is false because Stream does not implement Iterable, so you cannot use for-each directly on a Stream; you would need to convert it to a collection or use forEach().

24
MCQeasy

A developer is designing a loop to iterate through an array of integers and stop processing when the value -1 is encountered. Which loop construct should be used?

A.for(int i : array) { if(i == -1) exit; }
B.for(int i : array) { if(i == -1) return; }
C.for(int i : array) { if(i == -1) break; }
D.for(int i : array) { if(i == -1) continue; }
AnswerC

The break statement immediately exits the loop, which is the correct way to stop processing upon encountering -1.

Why this answer

Option C is correct because the `break` statement immediately terminates the loop when the value -1 is encountered, which is exactly what the requirement specifies. In Java, `break` exits the innermost loop or switch statement, making it the appropriate control flow mechanism for stopping iteration upon a condition.

Exam trap

The trap here is that candidates often confuse `break` with `continue` or mistakenly use `return` or `exit` to exit a loop, not realizing that `break` is the precise mechanism for loop termination without affecting the rest of the method or JVM.

How to eliminate wrong answers

Option A is wrong because `exit` is not a valid Java keyword or statement; the correct syntax would be `System.exit(0)`, but that would terminate the entire JVM, not just the loop. Option B is wrong because `return` exits the current method, not just the loop, which would prematurely end the enclosing method and is too broad for simply stopping iteration. Option D is wrong because `continue` skips the current iteration and proceeds to the next element, which does not stop the loop when -1 is found.

25
MCQmedium

What is the output of the following code? int i=5; do { System.out.print(i); i--; } while(i>0);

A.54321
B.Compilation error
C.543210
D.5432
AnswerA

The loop prints each number from 5 down to 1.

Why this answer

The do-while loop executes the body first, then checks the condition. Starting with i=5, it prints 5, decrements to 4, checks condition (4>0 true), continues. It prints 5,4,3,2,1.

When i becomes 0, the condition fails. So output is '54321'. Option A is correct.

26
MCQmedium

Given an enum Direction { NORTH, SOUTH, EAST, WEST } and a variable d of type Direction, which code snippet correctly uses a switch expression to map each direction to an abbreviation (N, S, E, W) without using a default branch?

A.switch (d) { case NORTH -> "N"; case SOUTH -> "S"; case EAST -> "E"; case WEST -> "W"; }
B.switch (d) { case NORTH: yield "N"; case SOUTH: yield "S"; case EAST: yield "E"; case WEST: yield "W"; }
C.switch (d) { case NORTH -> "N"; case SOUTH -> "S"; case EAST -> "E"; }
D.switch (d) { case NORTH: yield "N"; case SOUTH: yield "S"; case EAST: yield "E"; default: yield "W"; }
AnswerA

Correct arrow syntax covering all enum values.

Why this answer

Option C is correct because it covers all enum constants with arrow cases, and no default is needed because the switch is exhaustive. Option A is wrong because it uses colon syntax and yields are not used correctly in switch expressions with colon syntax. Option B is wrong because it uses a default which is unnecessary and not allowed in exhaustive switch expressions? Actually default is allowed but not needed; however the question specifically says without using default.

Option D is wrong because it doesn't handle all constants, so it doesn't compile.

27
Multi-Selecthard

Which three of the following statements about the switch expression in Java 17 are correct?

Select 3 answers
A.A switch expression with arrow syntax does not require break.
B.A switch expression with colon syntax can use yield to return a value.
C.A switch expression cannot be used with an enum type.
D.A switch expression must include a default branch even if all cases are covered.
E.A switch expression must be exhaustive.
AnswersA, B, E

Arrow syntax implicitly prevents fall-through, so break is unnecessary.

Why this answer

Option A is correct because in a switch expression with arrow syntax (->), each branch is a single expression or block that is automatically terminated, eliminating the need for a break statement. The arrow syntax implicitly prevents fall-through, making the code more concise and less error-prone.

Exam trap

The trap here is that candidates often confuse the requirement for a default branch in switch expressions with the behavior of switch statements, mistakenly thinking a default is always mandatory even when all cases are covered.

28
Multi-Selecthard

Which THREE statements are true about the enhanced for loop in Java?

Select 3 answers
A.If the underlying collection is modified during iteration, the loop will continue without error.
B.The enhanced for loop internally uses an iterator for collections.
C.The enhanced for loop can iterate over arrays.
D.The loop variable cannot be modified inside the loop body.
E.The loop variable must be declared final in the loop header.
AnswersB, C, D

For Iterable objects, it uses Iterator.

Why this answer

Option B is correct because the enhanced for loop (for-each) over a collection internally uses an Iterator obtained from the collection's iterator() method. This is specified in the Java Language Specification (JLS 14.14.2) and is the mechanism that allows sequential access to each element without exposing the iterator directly.

Exam trap

The trap here is that candidates often confuse the enhanced for loop's inability to modify the loop variable with a requirement to declare it final, or they mistakenly believe that structural modifications during iteration are safe.

29
Matchingmedium

Match each I/O stream class to its description.

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

Concepts
Matches

Reads text from a character-input stream, buffering characters

Reads raw bytes from a file

Writes primitive types and Java objects to an OutputStream

Prints formatted representations of objects to a text-output stream

Reads primitive Java data types from an underlying input stream

Why these pairings

These are common I/O stream classes for different purposes.

30
MCQeasy

Given: int x=0; do { x++; } while(x<5); How many times does the loop body execute?

A.5
B.4
C.6
D.0
AnswerA

Correct: runs for x=0 through 4, inclusive.

Why this answer

The do-while loop executes the body first, then checks the condition. The variable x starts at 0, increments to 1 on the first iteration, and continues incrementing until x becomes 5. When x is 5, the condition x<5 is false, so the loop stops.

The body executed for x values 1, 2, 3, 4, and 5 — a total of 5 times.

Exam trap

The trap here is that candidates often miscount by forgetting the do-while loop executes the body before checking the condition, leading them to think the loop runs only 4 times (confusing it with a standard while loop) or 6 times (misapplying the condition threshold).

How to eliminate wrong answers

Option B is wrong because it assumes the loop stops when x reaches 4, but the condition is checked after execution, so x must reach 5 to fail the test. Option C is wrong because it suggests the loop runs 6 times, which would require x to reach 6 before the condition fails, but the condition x<5 fails immediately when x becomes 5. Option D is wrong because the do-while loop guarantees at least one execution regardless of the initial condition; the body runs once before any check.

31
MCQeasy

A Java application processes a list of orders. Each order has a status: NEW, PROCESSING, SHIPPED, or DELIVERED. The code must print a message based on the status: - If NEW: "Order received" - If PROCESSING: "Order in progress" - If SHIPPED: "Order shipped" - If DELIVERED: "Order delivered" - For any other status: "Unknown status" The developer writes the following code using a switch expression: String message = switch (status) { case NEW -> "Order received"; case PROCESSING -> "Order in progress"; case SHIPPED -> "Order shipped"; case DELIVERED -> "Order delivered"; default -> "Unknown status"; }; System.out.println(message); What is the correct course of action to ensure the code compiles and runs correctly?

A.Add a default branch to handle any other status.
B.Use if-else if statements because switch cannot be used with enum types.
C.No change needed; the code compiles and runs as expected.
D.Change the switch expression to a switch statement because switch expressions cannot yield values.
AnswerC

The code is syntactically correct and covers all cases.

Why this answer

Option C is correct because the switch expression shown is syntactically valid and complete. It uses the arrow syntax with all enum constants covered and includes a default branch to handle any other status, so it compiles and runs as expected. Switch expressions can yield values and work with enum types, making the code correct as written.

Exam trap

The trap here is that candidates may think switch expressions cannot yield values or that enum types require if-else, but Java's enhanced switch fully supports both, and the default branch is already present, so no change is needed.

How to eliminate wrong answers

Option A is wrong because the code already includes a default branch, so adding another is unnecessary. Option B is wrong because switch can be used with enum types; in fact, Java switch supports enum constants directly without requiring if-else. Option D is wrong because switch expressions can yield values; the arrow syntax (->) is specifically designed for switch expressions that produce a result.

32
MCQeasy

A junior developer writes a method that uses a switch statement to handle different types of user input. The input is an integer representing an operation code. The developer uses a traditional switch statement with break statements. However, when operation code 2 is entered, the program also executes the code for operation 3. What is the most likely cause?

A.The break statement is missing after the operation 2 case.
B.The operation codes are not mutually exclusive.
C.The variable is being modified inside the switch.
D.The switch statement uses fall-through by design.
AnswerA

Missing break causes fall-through to subsequent cases.

Why this answer

In a traditional Java switch statement, execution continues into the next case block unless a break statement is encountered. If operation code 2 executes the code for operation 3, it indicates that the break statement is missing after the case for operation 2, causing fall-through to the next case.

Exam trap

The trap here is that candidates may think fall-through is always intentional or that operation codes must be mutually exclusive, but the question explicitly describes an unintended execution pattern, which points directly to a missing break statement.

How to eliminate wrong answers

Option B is wrong because operation codes in a switch are mutually exclusive by definition — each case label represents a distinct value, and only one case matches at a time. Option C is wrong because modifying a variable inside the switch does not cause fall-through; fall-through is solely controlled by the presence or absence of break statements. Option D is wrong because while fall-through is a feature of switch statements, the question states the developer intended to use break statements, so the fall-through is unintentional and caused by a missing break, not by design.

33
MCQmedium

A developer writes a method that processes a grade and returns a message using a switch expression. The code is: ```java public static String getMessage(int grade) { return switch (grade) { case 90, 80 -> "Excellent"; case 70, 60 -> "Good"; case 50 -> "Pass"; default -> "Fail"; }; } ``` Which statement is correct about this code?

A.The code does not compile because the switch expression must be enclosed in parentheses.
B.The code does not compile because the arrow form requires a 'yield' statement.
C.The code compiles and runs correctly, returning the appropriate message.
D.The code does not compile because 'default' is not allowed in a switch expression.
AnswerC

The switch expression is valid and will return the correct string for each grade.

Why this answer

Option C is correct because the switch expression uses the arrow form with a list of constants per case, which is valid syntax in Java 14+. The arrow form does not require a 'yield' statement when the right side is a single expression or block; here, each case yields a string literal directly. The 'default' clause is mandatory in a switch expression to cover all possible values, and it is correctly included.

Exam trap

The trap here is that candidates confuse the arrow form's syntax with the colon form, incorrectly assuming 'yield' is always required, or they mistakenly think 'default' is optional in switch expressions, when in fact it is mandatory for exhaustiveness.

How to eliminate wrong answers

Option A is wrong because switch expressions do not require parentheses around the entire expression; the syntax is 'switch (grade) { ... }' which is correct. Option B is wrong because the arrow form (->) does not require a 'yield' statement; 'yield' is only needed when using the colon form with a block, or when the arrow form's right side is a block that needs to return a value. Option D is wrong because 'default' is not only allowed but required in a switch expression to ensure exhaustiveness; without it, the code would not compile.

34
Multi-Selecteasy

Which two statements about the do-while loop are true?

Select 2 answers
A.The condition is evaluated before the body executes.
B.The do-while loop cannot have an initialization statement.
C.The do-while loop can be used with a label.
D.The body of a do-while loop executes at least once.
E.The do-while loop always executes more times than a while loop with the same condition.
AnswersC, D

Correct: labels are allowed on any loop statement.

Why this answer

Option C is correct because Java allows any loop, including the do-while loop, to be labeled. A label is a valid Java identifier followed by a colon placed immediately before the loop statement, enabling break or continue to transfer control to that labeled point. This is explicitly permitted by the Java Language Specification for all iteration statements.

Exam trap

The trap here is that candidates often confuse the evaluation order of do-while (post-test) with while (pre-test), leading them to incorrectly select option A, and they may overlook that labels are valid for all loop constructs in Java, not just for or while loops.

35
MCQhard

A method contains a try-with-resources statement that uses two resources: a FileInputStream and a BufferedInputStream. The FileInputStream constructor throws a FileNotFoundException. Which statement about resource closing is true?

A.The BufferedInputStream is closed if it was successfully created, but the FileInputStream is not.
B.Both resources are closed even if the FileInputStream constructor throws an exception.
C.No resources are closed because the FileInputStream constructor failed before any resource was opened.
D.The programmer must explicitly close the resources in a finally block.
AnswerC

The first constructor threw an exception, so no resource was opened.

Why this answer

In a try-with-resources statement, resources are closed only if they have been successfully initialized. If the FileInputStream constructor throws a FileNotFoundException, the resource is never created, so the try-with-resources statement does not attempt to close it. The BufferedInputStream is never constructed because the exception occurs before its declaration is reached, so no resources are opened and none need to be closed.

Therefore, option C is correct.

Exam trap

The trap here is that candidates assume all declared resources are always closed, forgetting that the try-with-resources statement only closes resources that were successfully created, and an exception during construction of the first resource prevents the second from even being declared.

How to eliminate wrong answers

Option A is wrong because the BufferedInputStream is never created if the FileInputStream constructor fails, so it cannot be closed. Option B is wrong because the try-with-resources statement only closes resources that were successfully initialized; if the first resource constructor throws an exception, no resources are opened and none are closed. Option D is wrong because the try-with-resources statement automatically closes all successfully opened resources, and the programmer does not need to explicitly close them in a finally block.

36
Drag & Dropmedium

Order the steps to handle checked exceptions in a method that throws IOException.

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

Steps
Order

Why this order

Checked exceptions must be either caught or declared in the method signature. Unhandled checked exceptions cause compilation errors.

37
Multi-Selecteasy

Which TWO of the following are valid forms of the switch statement/expression in Java?

Select 2 answers
A.switch(x) { case 1 -> "one"; }
B.switch(x) { case 1: System.out.println("one"); break; }
C.String r = switch(x) { case 1 -> "one"; default -> "other"; };
D.String r = switch(x) { case 1: break "one"; };
E.switch(x) { case 1: yield "one"; }
AnswersB, C

Valid traditional switch statement.

Why this answer

Option B is correct because it uses the traditional switch statement syntax with a colon after the case label, a statement to execute, and a break statement to prevent fall-through. This is a valid and long-standing form of the switch statement in Java.

Exam trap

The trap here is that candidates often confuse the syntax of switch statements and switch expressions, mistakenly applying arrow syntax or yield to a switch statement, or thinking break can carry a value like in some other languages.

38
MCQhard

A resource is declared in a try-with-resources statement. The try block throws an exception. The close method throws a different exception. What exception is thrown by the try-with-resources statement?

A.The exception from the close method.
B.The exception from the try block.
C.A compilation error occurs.
D.Both exceptions are thrown simultaneously.
AnswerB

The try block exception is the primary exception; the close exception is suppressed.

Why this answer

In a try-with-resources statement, if both the try block and the close() method throw exceptions, the exception from the try block is the one thrown by the statement. The exception from close() is suppressed and added to the thrown exception's suppressed exception list (via Throwable.addSuppressed()). This is specified by JLS §14.20.3.2 and ensures the primary failure (the try block exception) is not masked.

Exam trap

The trap here is that candidates often assume the last exception thrown (from close()) overrides the earlier one, or that both exceptions are thrown simultaneously, but Java's suppressed exception mechanism ensures the try block's exception is primary and close() exceptions are silently attached.

How to eliminate wrong answers

Option A is wrong because the exception from the close method is not the one thrown; it is suppressed and added to the suppressed exception list of the try block's exception. Option C is wrong because no compilation error occurs; the try-with-resources syntax is valid and handles multiple exceptions gracefully. Option D is wrong because both exceptions are not thrown simultaneously; Java does not support throwing multiple exceptions at once — one exception is thrown, and the other is suppressed.

39
MCQhard

A developer wrote a method that uses a for-each loop to iterate over a list of strings and remove elements that match a certain condition. However, the method throws a ConcurrentModificationException at runtime. What is the most likely cause?

A.The loop uses a for-each loop with an array instead of a list.
B.The loop uses an iterator that is not properly initialized.
C.The list is unmodifiable.
D.The loop modifies the list by calling remove() on the list itself.
AnswerD

Modifying the list directly while iterating with a for-each loop causes ConcurrentModificationException because the iterator is not updated.

Why this answer

Option D is correct because a for-each loop internally uses an Iterator to traverse the list. If the list is structurally modified (e.g., by calling remove() directly on the list) during iteration, the iterator's expected modCount will differ from the actual modCount, triggering a ConcurrentModificationException. This is a fail-fast behavior of the ArrayList and other Collection implementations.

Exam trap

The trap here is that candidates often confuse the ConcurrentModificationException with other exceptions (like UnsupportedOperationException) or mistakenly think the for-each loop itself is the problem, rather than recognizing that direct list modification during iteration is the root cause.

How to eliminate wrong answers

Option A is wrong because iterating over an array with a for-each loop does not involve an Iterator and thus cannot throw a ConcurrentModificationException; arrays are fixed-size and do not support structural modification. Option B is wrong because the for-each loop automatically obtains and initializes the iterator; the exception is not caused by improper initialization but by concurrent modification. Option C is wrong because an unmodifiable list would throw an UnsupportedOperationException if remove() is called, not a ConcurrentModificationException.

40
MCQeasy

Which loop construct guarantees that the body executes at least once?

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

Condition checked after body.

Why this answer

The do-while loop is the only loop construct in Java that guarantees the body executes at least once because the condition is evaluated after the loop body. This post-test loop design ensures that regardless of the initial condition value, the body runs before any check occurs.

Exam trap

The trap here is that candidates often confuse the do-while loop with the while loop, mistakenly thinking that a while loop can also guarantee at least one execution if the condition is true, but the key distinction is that only the do-while loop executes the body before checking the condition.

How to eliminate wrong answers

Option A is wrong because a for loop evaluates its condition before the first iteration; if the condition is false initially, the body never executes. Option B is wrong because an enhanced for loop (for-each) checks whether there are elements to iterate over before entering the body; if the array or collection is empty, the body never runs. Option C is wrong because a while loop evaluates its condition before the loop body; if the condition is false at the start, the body is skipped entirely.

41
MCQhard

Given the following code: ```java outer: for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (i == 1) { continue outer; } System.out.print(i + " " + j + " "); } } ``` What is the output?

A.0-0 0-1 0-2 1-0 2-0 2-1 2-2
B.0-0 0-1 0-2 1-0 1-1 1-2 2-0 2-1 2-2
C.0-0 0-1 0-2 2-0 2-1 2-2
D.0-0 0-1 0-2 2-0 2-1 2-2
AnswerD

Correct, i=1 is completely skipped.

Why this answer

The correct answer is D because when i equals 1, the continue outer statement skips the entire inner loop for that iteration, so no output is produced for i=1. The outer loop continues with i=2, printing all j values (0,1,2) for i=2, resulting in the output: 0 0 0 1 0 2 2 0 2 1 2 2.

Exam trap

The trap here is that candidates often forget that continue outer skips the entire inner loop for the current outer iteration, not just the current inner iteration, leading them to include i=1 outputs or misformat the output.

How to eliminate wrong answers

Option A is wrong because it incorrectly includes '1-0' (i=1, j=0) which is never printed due to the continue outer when i=1. Option B is wrong because it includes all nine combinations (including i=1 rows), failing to account for the skip caused by continue outer. Option C is wrong because it uses hyphens instead of spaces between i and j values, and also omits the space between pairs; the actual output uses spaces, not hyphens.

42
MCQeasy

Given the code snippet: int x = 10; if (x > 5) { System.out.print("A"); } else if (x > 7) { System.out.print("B"); } else { System.out.print("C"); } What is the output?

A.C
B.ABC
C.A
D.B
AnswerC

The first condition is true.

Why this answer

The if-else chain evaluates conditions sequentially. Since x=10 satisfies x > 5, the first block executes and prints 'A'. The else if and else branches are skipped entirely because the first condition was true.

Thus, only 'A' is output.

Exam trap

The trap here is that candidates mistakenly think the else if condition (x > 7) is also true and will execute, or that all branches are evaluated sequentially, leading them to choose 'ABC' or 'B' instead of recognizing the exclusive nature of if-else-if.

How to eliminate wrong answers

Option A is wrong because it suggests 'C' is printed, but the else block only executes if all preceding conditions are false, which is not the case here. Option B is wrong because it implies all branches execute, but Java's if-else-if structure is mutually exclusive — only the first true branch runs. Option D is wrong because it assumes the else if condition (x > 7) is evaluated, but it is skipped once the first if condition is true.

43
Multi-Selecteasy

Which TWO statements about the break and continue statements in Java are correct?

Select 2 answers
A.The break statement without a label always terminates the innermost enclosing loop or switch.
B.The continue statement can be used inside any loop, including for, while, and do-while loops.
C.The continue statement can be used inside a switch statement to skip the rest of the switch body.
D.The break statement can be used only inside loops and switch statements.
E.The continue statement without a label skips the current iteration and proceeds to the next iteration without reevaluating the loop condition.
AnswersA, B

break without a label exits the innermost loop or switch.

Why this answer

Option A is correct because the break statement without a label, when executed inside a loop or switch, immediately terminates the innermost enclosing loop or switch construct. This is defined by the Java Language Specification (JLS §14.15), which states that an unlabeled break statement transfers control to the immediately enclosing statement of the break target.

Exam trap

The trap here is that candidates often confuse the behavior of continue in different loop types (for vs. while) and incorrectly assume it skips condition reevaluation, or they mistakenly think break can only target loops and switches, ignoring its use with labeled blocks.

44
MCQhard

A financial application processes a daily batch of 10 million transactions. Each transaction is an object with fields: id, amount, and status (an enum: PENDING, APPROVED, REJECTED). The requirement is to find the first APPROVED transaction with amount greater than 1000. The current implementation uses a while loop with a nested if-else structure that checks each transaction sequentially. The loop also logs each transaction status, which involves a moderately expensive file write operation. Performance analysis shows the method is a bottleneck, often taking over 12 seconds. The development team is considering refactoring. Which course of action will most effectively reduce execution time while maintaining the requirement?

A.Refactor the while loop into a recursive method that processes one transaction per call and stops when the condition is met.
B.Replace the while loop with a parallel stream and use findFirst() to get the first matching transaction.
C.Replace the while loop with a for-each loop that breaks when the condition is met, but keep the logging inside the loop.
D.Replace the while loop with a traditional for loop that uses a break when the first match is found, and defer the logging to a separate batch process after the loop.
AnswerD

Early break reduces iterations, and removing logging I/O from the loop drastically improves performance. Batch logging can be done asynchronously.

Why this answer

Option C is correct because early break stops iteration as soon as the first matching transaction is found, skipping remaining transactions. Additionally, moving the logging operation outside the loop, perhaps to a batch logger, reduces I/O overhead significantly. Option A is wrong because parallel streams add overhead for thread management and ordering requirements; the first match in parallel requires careful handling and may not return the first in source order.

Option B is wrong because using a for-each loop with break is essentially similar to the while loop and does not address the logging issue. Option D is wrong because recursion adds stack overhead and is not suitable for large datasets, and it does not address the logging either.

45
MCQmedium

A method uses an enhanced for loop to iterate over a list of strings and prints each string. The code is: ```java List<String> list = List.of("A", "B", "C"); for (String s : list) { if (s.equals("B")) { break; } System.out.print(s); } ``` What is the result?

A.The code throws a ConcurrentModificationException.
B.ABC
C.A
D.AB
AnswerC

Prints A, then breaks at B.

Why this answer

The enhanced for loop iterates over the list, and when it encounters the string "B", the break statement immediately exits the loop. Therefore, only "A" is printed before the loop terminates. Option C is correct because the output is just "A".

Exam trap

The trap here is that candidates may think the break statement causes a ConcurrentModificationException or that it prints "AB" because they forget that break exits the loop before executing the print statement for the matched element.

How to eliminate wrong answers

Option A is wrong because the enhanced for loop does not allow structural modification of the list during iteration, but here no modification occurs—only a break statement is used, so no ConcurrentModificationException is thrown. Option B is wrong because the break statement prevents printing "B" and "C", so the output is not "ABC". Option D is wrong because the break occurs before printing "B", so only "A" is printed, not "AB".

46
MCQeasy

Refer to the exhibit. The exhibit shows a stack trace from a Java application. Which line in the code caused the NullPointerException?

A.Line 10: System.out.println(len);
B.Line 12: String s = "hello";
C.Line 5: int x = 10;
D.Line 8: int len = s.length();
AnswerD

The stack trace explicitly shows line 8.

Why this answer

Option D is correct because the NullPointerException occurs when invoking the `length()` method on a null reference. In the stack trace, the exception is thrown at line 8, where `s.length()` is called, but `s` has not been assigned a non-null value (it is null by default if declared as a field, or uninitialized locally). The JVM throws NullPointerException when any instance method is called on a null object reference.

Exam trap

The trap here is that candidates may confuse the line where the exception is thrown (line 8) with the line where the variable is declared (line 12), mistakenly thinking the declaration itself causes the error, but the exception only occurs when the null reference is actually used.

How to eliminate wrong answers

Option A is wrong because `System.out.println(len)` on line 10 simply prints the integer variable `len`, which would have been assigned a value if line 8 succeeded; it does not cause a NullPointerException. Option B is wrong because `String s = "hello";` on line 12 assigns a non-null String literal to `s`, which is a safe operation and does not throw NullPointerException. Option C is wrong because `int x = 10;` on line 5 is a primitive assignment that never involves object references, so it cannot produce a NullPointerException.

47
MCQhard

You are developing a high-frequency trading application that processes a stream of market data ticks. Each tick is represented by a Tick object with fields: long timestamp, String symbol, double price, int volume. Ticks arrive in real-time and must be processed in order. A bug is reported: the application occasionally processes a tick out of order, causing incorrect trade decisions. The processing logic uses a while loop to read from a blocking queue and process each tick. The code is: BlockingQueue<Tick> queue = new LinkedBlockingQueue<>(); while (true) { Tick tick = queue.take(); process(tick); } After investigation, you find that the queue is fed by multiple producer threads that sometimes reorder ticks due to network delays. Which course of action best ensures ticks are processed in the correct chronological order without sacrificing throughput?

A.Use a SynchronousQueue and have producers wait for the consumer to acknowledge.
B.After taking from the queue, sort a batch of ticks before processing.
C.Replace LinkedBlockingQueue with a PriorityBlockingQueue that orders by timestamp.
D.Add a delay before processing to allow out-of-order ticks to arrive.
AnswerC

PriorityBlockingQueue maintains ordering by timestamp.

Why this answer

Option C is correct because PriorityBlockingQueue maintains elements in natural order (or by a provided Comparator), so ticks are automatically ordered by timestamp when inserted. This ensures the consumer always processes the chronologically earliest tick first, even if producers add them out of order, without requiring additional sorting or blocking.

Exam trap

The trap here is that candidates may think sorting after retrieval (Option B) is sufficient, but they overlook that PriorityBlockingQueue provides automatic ordering at insertion time, which is more efficient and maintains correctness without batching delays.

How to eliminate wrong answers

Option A is wrong because SynchronousQueue has zero capacity and requires each producer to wait for the consumer to take the element, which serializes access and severely reduces throughput in a multi-producer scenario. Option B is wrong because sorting a batch after taking from the queue introduces latency and does not guarantee global chronological order if ticks arrive continuously; it also violates the real-time processing requirement. Option D is wrong because adding a fixed delay does not guarantee that all out-of-order ticks will arrive before processing, and it unnecessarily increases latency, reducing throughput.

48
Multi-Selectmedium

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

Select 2 answers
A.Case values can be variables that are not final.
B.It can be used with String objects.
C.It requires a default case.
D.It can be used as an expression that yields a value.
E.Each case must have a unique code block.
AnswersB, D

String is allowed in switch since Java 7.

Why this answer

Option B is correct because Java's switch statement supports String objects since Java 7, allowing comparison based on the string's hashCode() and equals() methods. Option D is correct because switch can be used as an expression (e.g., with the arrow syntax) that yields a value, which can be assigned to a variable or returned.

Exam trap

Oracle often tests the misconception that case values can be any variable, but the trap here is that they must be compile-time constants (final or literals), and that switch expressions require exhaustiveness, not a default case.

49
MCQmedium

A developer is implementing a batch processing application that reads records from a list and processes them. The method uses a for loop with an index variable. Inside the loop, if a record is null, the developer wants to skip that iteration and continue with the next index. The developer writes: for (int i = 0; i < records.size(); i++) { if (records.get(i) == null) continue; process(records.get(i)); updateCounter(); } However, the counter is not updated correctly. The developer expects the counter to reflect the number of processed (non-null) records. What is the problem?

A.The continue statement is only valid inside a while loop.
B.The continue statement should be replaced with a break.
C.The continue statement skips the rest of the loop body, including the counter update.
D.The counter variable should be declared as volatile.
AnswerC

continue causes the loop to proceed to the next iteration, skipping subsequent statements.

Why this answer

Option C is correct because the `continue` statement immediately jumps to the next iteration of the loop, skipping any remaining code in the current iteration. In this case, `updateCounter()` is placed after the `continue` in the loop body, so when a null record is encountered, the counter update is never executed, causing the counter to not reflect the number of processed (non-null) records.

Exam trap

The trap here is that candidates may think `continue` only affects the current iteration's processing but forget that it also skips all subsequent statements in the loop body, including counter updates, leading them to choose options like A or D instead of recognizing the control flow issue.

How to eliminate wrong answers

Option A is wrong because `continue` is valid inside `for`, `while`, and `do-while` loops in Java, not just `while` loops. Option B is wrong because `break` would exit the loop entirely, stopping all processing, which is not the intended behavior (the developer wants to skip only the null record and continue with the next index). Option D is wrong because the `volatile` keyword ensures visibility of variable changes across threads, but this is a single-threaded batch processing application, and the counter update issue is purely about control flow, not concurrency.

50
MCQeasy

What is the output of the following code snippet? int x = 5; if(x > 0) { System.out.print('A'); } else if(x > 2) { System.out.print('B'); } else { System.out.print('C'); }

A.AB
B.C
C.B
D.A
AnswerD

x > 0 is true, so the first branch executes and prints 'A'.

Why this answer

The correct answer is D because the condition `x > 0` evaluates to true (x = 5), so the code prints 'A' and then exits the entire if-else-if chain. The subsequent `else if` and `else` blocks are skipped entirely, so only 'A' is output.

Exam trap

The trap here is that candidates mistakenly think the `else if` condition is also evaluated or that multiple branches can execute, confusing the if-else-if chain with a series of independent if statements.

How to eliminate wrong answers

Option A is wrong because it suggests both 'A' and 'B' are printed, but once the first `if` condition is true, the rest of the chain is bypassed — no fall-through occurs in if-else-if structures. Option B is wrong because it implies the `else` block executes, which only happens if all preceding conditions are false; here `x > 0` is true, so the `else` is never reached. Option C is wrong because it assumes the `else if` condition `x > 2` is evaluated, but it is skipped entirely when the first `if` is true.

51
MCQhard

Given: outer: for(int i=0; i<3; i++) { for(int j=0; j<3; j++) { if(j==1) continue outer; } } How many times does the innermost loop body execute?

A.3
B.0
C.9
D.6
AnswerA

Correct: only j=0 runs for each i, so 3 times.

Why this answer

The outer loop runs with i=0,1,2. For each i, the inner loop starts j=0, executes the body once, then j=1 triggers 'continue outer', which skips the rest of the inner loop and increments i. Thus the inner loop body executes exactly once per outer iteration, for a total of 3 times.

Exam trap

The trap here is that candidates often forget the inner loop body executes for j=0 before the continue, leading them to think it never runs or runs all 9 times.

How to eliminate wrong answers

Option B is wrong because the inner loop body does execute — it runs for j=0 before the continue is encountered. Option C is wrong because the continue outer prevents the inner loop from completing all 9 iterations; only 3 iterations occur. Option D is wrong because the inner loop does not execute 6 times; the continue outer resets to the outer loop after j=1, so only j=0 runs each time.

52
MCQmedium

A developer writes code to iterate over a list of strings and print each element. The code uses an enhanced for loop. Which statement is true about the enhanced for loop?

A.It can be used with arrays and any object that implements Iterable.
B.It can only be used with arrays.
C.It requires an explicit counter variable.
D.It allows removing elements from the collection during iteration without ConcurrentModificationException.
AnswerA

The enhanced for loop works on arrays and Iterable objects.

Why this answer

The enhanced for loop (for-each) in Java can iterate over arrays and any object that implements the Iterable interface, which includes all Collection classes (e.g., List, Set, Queue). This is because the for-each loop internally uses an iterator for Iterable objects or array indexing for arrays, making it a versatile construct for traversing elements without needing an explicit counter.

Exam trap

The trap here is that candidates often confuse the enhanced for loop's flexibility with the ability to modify the collection safely, or mistakenly think it requires a counter like a traditional for loop, leading them to choose options B or D.

How to eliminate wrong answers

Option B is wrong because the enhanced for loop is not limited to arrays; it also works with any Iterable, such as ArrayList or HashSet. Option C is wrong because the enhanced for loop abstracts away the counter variable; it does not require an explicit counter, unlike a traditional for loop. Option D is wrong because the enhanced for loop does not allow structural modifications (like removing elements) during iteration without risking a ConcurrentModificationException, as it relies on an iterator that checks for concurrent modification.

53
MCQhard

Given: int i=0; outer: while(i<3) { for(int j=0; j<3; j++) { if(j==1) break outer; } i++; } What is the value of i after the outer loop?

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

Correct: i is still 0 when break outer executes.

Why this answer

The correct answer is D (0) because the `break outer` statement immediately terminates the outer `while` loop when `j` equals 1 during the first iteration of the inner `for` loop. Since `i` is incremented only after the inner loop completes, and the inner loop never finishes its first iteration, `i` remains 0.

Exam trap

The trap here is that candidates often overlook that `i++` is never reached because the labeled break exits the outer loop before the increment executes, leading them to incorrectly assume `i` is 1 or higher.

How to eliminate wrong answers

Option A is wrong because it assumes the outer loop increments `i` before the break, but `i++` is placed after the inner loop and never executes. Option B is wrong because it suggests two increments occurred, but the break happens on the first inner loop iteration. Option C is wrong because it implies the outer loop completed all three iterations, which is prevented by the break.

54
MCQhard

In a large enterprise application, a concurrent caching system is implemented using a ConcurrentHashMap that is accessed by multiple threads concurrently. The cache performs atomic operations on individual keys, but some operations require updates on multiple keys. To ensure consistency, the code acquires intrinsic locks on the keys using synchronized blocks. Over time, the system has been experiencing intermittent deadlocks. During post-mortem analysis, it was found that thread A holds a lock on key X and is waiting for key Y, while thread B holds a lock on key Y and is waiting for key X. The development team needs to redesign the locking strategy to eliminate these deadlocks while maintaining high throughput and minimizing code changes. They consider the following proposals: replacing ConcurrentHashMap with Collections.synchronizedMap, using a single ReentrantLock for all cache operations, always acquiring locks on keys in a consistent global order, or using a Lock with tryLock and a timeout and releasing all locks if timeout expires. Based on best practices in concurrent programming and considering the requirements to avoid deadlocks and maintain performance, which approach should they choose?

A.Use a single ReentrantLock for all cache operations.
B.Replace ConcurrentHashMap with Collections.synchronizedMap.
C.Use a Lock with tryLock and a timeout, and release all locks if timeout expires.
D.Always acquire locks on keys in a consistent global order.
AnswerC

This approach uses tryLock with a timeout to avoid indefinite waiting; if a thread cannot acquire all locks within the timeout, it releases acquired locks and retries, effectively preventing deadlock while maintaining concurrency.

Why this answer

Option C is correct because using tryLock with a timeout allows threads to back off and release all acquired locks if they cannot obtain all required locks within a specified time, which breaks the circular wait condition that causes deadlocks. This approach maintains high throughput by avoiding coarse-grained locking and minimizes code changes by only modifying the lock acquisition logic, not the underlying ConcurrentHashMap structure.

Exam trap

The trap here is that candidates often choose consistent global ordering (Option D) as the textbook deadlock prevention technique, but the question emphasizes 'minimizing code changes' and 'maintaining high throughput,' making the tryLock approach more practical for an existing ConcurrentHashMap-based system with dynamic keys.

How to eliminate wrong answers

Option A is wrong because using a single ReentrantLock for all cache operations serializes all access, destroying the high throughput benefits of ConcurrentHashMap and creating a performance bottleneck. Option B is wrong because replacing ConcurrentHashMap with Collections.synchronizedMap introduces coarse-grained synchronization on the entire map, which eliminates concurrency entirely and drastically reduces throughput, while still not preventing deadlocks if multiple keys are locked via synchronized blocks. Option D is wrong because while consistent global ordering of lock acquisition prevents deadlocks in theory, it requires significant code changes to enforce a global order across all keys, and in practice with dynamic key sets (e.g., hash-based keys) it is error-prone and difficult to maintain, making it less practical than the timeout-based approach.

55
MCQhard

Given the following code snippet: ```java outer: for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (i == 1 && j == 1) { break outer; } System.out.print(i + "-" + j + " "); } } ``` What is the output?

A.0-0 0-1 0-2 1-0 1-1 1-2
B.0-0 0-1 0-2 1-0
C.0-0 0-1 0-2 1-0 2-0 2-1 2-2
D.0-0 0-1 0-2 1-0 1-1
AnswerB

Correct. The loop prints all combinations until the break condition at (1,1).

Why this answer

The correct answer is B because the labeled `break outer;` statement exits the outer loop entirely when `i == 1` and `j == 1`. Before that condition is met, the inner loop prints pairs for `i=0` (all j values 0,1,2) and for `i=1` with `j=0`. When `i=1` and `j=1`, the break occurs, so `1-1` is never printed, and the outer loop stops, preventing any further iterations.

Exam trap

The trap here is that candidates often forget that a labeled break exits the outer loop entirely, not just the inner loop, leading them to choose option A or D which include `1-1` or later iterations.

How to eliminate wrong answers

Option A is wrong because it includes `1-1` and `1-2`, but the break occurs before `1-1` is printed, and the outer loop terminates, so `1-2` is never reached. Option C is wrong because it includes iterations for `i=2`, but the outer loop breaks at `i=1, j=1`, so `i=2` is never executed. Option D is wrong because it includes `1-1`, but the break occurs before the print statement for that pair, so `1-1` is not output.

56
MCQhard

A Java developer is writing a batch processing application that reads records from a database and processes them. The processing must continue even if some records cause exceptions (e.g., data conversion errors). However, the application must log each failed record and its error, then continue with the next record. The developer uses a for loop to iterate over a list of records. Inside the loop, a try-catch block wraps the processing logic. After implementing, the developer notices that when an exception occurs, the loop terminates prematurely instead of continuing. The code structure is: List<Record> records = fetchRecords(); for (Record rec : records) { try { process(rec); } catch (Exception e) { log.error("Failed to process: " + rec.getId(), e); } } What is the most likely reason for the premature termination?

A.The records list contains null elements, causing a NullPointerException that is not caught.
B.The process() method throws an Error instead of an Exception.
C.The log.error() method itself throws an unchecked exception that is not caught.
D.The try-catch block is incorrectly placed inside the for loop, causing the loop to break on any exception.
AnswerB

Errors are not caught by catch(Exception), causing the loop to terminate.

Why this answer

The code catches `Exception`, but `Error` (and its subclasses like `OutOfMemoryError`, `StackOverflowError`, or custom `Error` types) are not subclasses of `Exception`. In Java, `Throwable` has two main branches: `Exception` (including `RuntimeException`) and `Error`. Since `Error` is not caught by `catch (Exception e)`, it propagates up and terminates the loop.

This is the most likely reason for premature termination because the developer assumed all failures would be `Exception` types.

Exam trap

The trap here is that candidates assume all exceptions are caught by `catch (Exception e)`, forgetting that `Error` is a separate branch of `Throwable` and is not caught by that handler, leading to premature loop termination when an `Error` is thrown.

How to eliminate wrong answers

Option A is wrong because a `NullPointerException` is a subclass of `RuntimeException`, which is a subclass of `Exception`, so it would be caught by the `catch (Exception e)` block and the loop would continue. Option C is wrong because even if `log.error()` throws an unchecked exception (e.g., `NullPointerException`), it would also be caught by the same `catch (Exception e)` block (since unchecked exceptions extend `RuntimeException` which extends `Exception`), so the loop would not terminate prematurely. Option D is wrong because placing a try-catch inside a for loop does not cause the loop to break; in fact, it is the correct pattern to handle exceptions per iteration and continue — the loop only breaks if an uncaught exception propagates out of the loop body.

57
MCQmedium

What is the output when this code is executed?

A.Two Three
B.Two
C.Two Three Default
D.One Two Three
AnswerA

Correct, falls through to case 3 then breaks.

Why this answer

The switch statement matches the value 2, so it executes the case 'Two' block, which prints 'Two ' and then falls through to the next case because there is no break statement. The case 'Three' block prints 'Three ' and then breaks, exiting the switch. The default case is skipped because a matching case was found and the break in case 'Three' prevents further fall-through.

Thus, the output is 'Two Three '.

Exam trap

The trap here is that candidates often forget that missing break statements cause fall-through, leading them to think only the matched case executes, or they incorrectly assume the default case always runs at the end.

How to eliminate wrong answers

Option B is wrong because it assumes that after printing 'Two', the switch exits without falling through to case 'Three', but without a break statement, fall-through occurs. Option C is wrong because it includes 'Default' in the output, but the default case is only executed if no matching case is found; here, case 2 matches, so default is skipped. Option D is wrong because it suggests that case 'One' also executes, but the switch starts matching from the value 2, so case 'One' is never entered.

58
Multi-Selectmedium

Which TWO statements about the switch statement in Java are correct?

Select 2 answers
A.The default case can be placed anywhere within the switch block.
B.Case values can be runtime expressions.
C.A break statement is mandatory after each case block.
D.Case labels can be variables if they are final and assigned a constant expression.
E.The switch statement can be used with int, char, String, and enum types.
AnswersA, E

Default can be at any position.

Why this answer

Option A is correct because the Java Language Specification allows the default case to appear anywhere within the switch block, not just at the end. The switch statement evaluates the expression and jumps to the matching case label; if no match is found, it jumps to the default label regardless of its position. This flexibility is important for code organization and readability.

Exam trap

The trap here is that candidates often assume the default case must be last, or that break is always required, or that any final variable can be used as a case label, when in fact only compile-time constant expressions are allowed.

59
MCQhard

A financial trading system uses a Java application to process market data. The core algorithm uses nested loops to compare price arrays. The developer uses a labeled continue statement to skip certain combinations. After a code review, the team suspects the algorithm has a bug that causes incorrect results. The developer writes a unit test and discovers that the labeled continue sometimes skips more iterations than intended. The code is: outer: for (int i = 0; i < prices1.length; i++) { for (int j = 0; j < prices2.length; j++) { if (prices1[i] < prices2[j]) continue outer; // process combination } } The developer intended that if any price in prices1 is less than a price in prices2, the entire row (i) should be skipped. However, the algorithm skips rows even when the condition is not met for all j. What is the most likely cause?

A.A break statement is missing after processing a combination.
B.The label outer is placed on the inner loop, not the outer loop.
C.The condition for continuing is not correctly evaluated.
D.The continue outer statement should be a break outer.
AnswerB

Because the label precedes the inner for, continue outer continues the inner loop, not the outer.

Why this answer

Option B is correct because the label `outer` is placed on the inner loop, not the outer loop. In Java, a labeled continue statement jumps to the next iteration of the loop identified by the label. If the label is on the inner loop, `continue outer` will skip the current iteration of the inner loop and continue with the next iteration of the outer loop, which is exactly what the developer intended.

However, the code as written has the label on the inner loop, so `continue outer` actually skips the entire inner loop for the current `i` and moves to the next `i`, even if the condition `prices1[i] < prices2[j]` is only true for some `j`. This causes more iterations to be skipped than intended.

Exam trap

The trap here is that candidates often assume a labeled continue always affects the outer loop, but in Java, the label must be placed on the loop you intend to continue; misplacing the label causes the continue to target the wrong loop, leading to unexpected behavior.

How to eliminate wrong answers

Option A is wrong because a break statement after processing a combination would exit the inner loop entirely, not skip rows conditionally; the issue is about skipping too many iterations, not missing a break. Option C is wrong because the condition `prices1[i] < prices2[j]` is correctly evaluated; the bug is in the control flow, not the condition logic. Option D is wrong because `break outer` would exit the outer loop entirely, terminating all processing, which is not the intended behavior of skipping a row.

60
Multi-Selecteasy

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

Select 2 answers
A.A break statement is optional.
B.A switch statement can be used as an expression in all cases.
C.The switch expression can be of type long.
D.The switch expression can be of type String.
E.The case values can be variables.
AnswersA, D

Without break, execution falls through to the next case.

Why this answer

Option A is correct because in a Java switch statement, the break statement is optional. If omitted, execution falls through to the next case (fall-through behavior), which can be intentional or lead to bugs. This is a core feature of the switch construct, not a requirement.

Exam trap

The trap here is that candidates often assume break is mandatory in all switch constructs, or they mistakenly think long is a valid switch type because it is a numeric primitive, but Java explicitly excludes long from switch expressions.

61
Multi-Selectmedium

Which two of the following are valid ways to exit a loop in Java?

Select 2 answers
A.label break
B.continue
C.break
D.System.exit(0)
E.throw new Exception()
AnswersA, C

A labeled break can exit a specific outer loop.

Why this answer

Option A is correct because a labeled break statement allows you to exit an outer loop from within a nested loop by specifying the label of the outer loop. This is a valid control flow mechanism in Java, as defined in the Java Language Specification (JLS §14.15).

Exam trap

The trap here is that candidates often confuse 'continue' with 'break' or think that System.exit(0) or throwing an exception are valid loop exit mechanisms, when in fact only 'break' (and labeled break) are designed specifically for that purpose.

62
MCQeasy

What is the output of the following code? ```java int i = 5; while (i > 0) { System.out.print(i + " "); i--; } ```

A.5 4 3 2 1
B.The code does not compile because i is not declared final.
C.5 4 3 2
D.4 3 2 1
AnswerA

Correct countdown from 5 to 1.

Why this answer

The while loop runs as long as i > 0. Starting with i = 5, each iteration prints the current value of i followed by a space, then decrements i by 1. The loop stops when i becomes 0, so the output is '5 4 3 2 1 '.

Exam trap

The trap here is that candidates might think the loop stops before printing the last value (1) or that the decrement happens before printing, leading them to choose options C or D.

How to eliminate wrong answers

Option B is wrong because the code compiles and runs correctly; there is no requirement for i to be declared final in a while loop. Option C is wrong because it omits the final value 1, but the loop prints i before decrementing, so when i = 1, it prints 1, then i becomes 0 and the loop exits. Option D is wrong because it starts at 4 instead of 5, but the initial value of i is 5, and the first iteration prints 5.

63
MCQmedium

Given: Object obj = "Hello"; String result = switch(obj) { case String s -> "String of length " + s.length(); case Integer i -> "Integer"; default -> "Unknown"; }; What is result?

A."Unknown"
B.Compilation error
C."String of length 5"
D."Integer"
AnswerC

Correct: the String pattern matches and length is 5.

Why this answer

The switch expression uses pattern matching with type patterns. The runtime type of obj is String, so the first case matches, binding the value to s and executing the expression "String of length " + s.length(). Since s is "Hello", s.length() returns 5, so result is "String of length 5".

Option C is correct.

Exam trap

The trap here is that candidates may think the switch requires a constant expression or that pattern matching is not allowed, leading them to expect a compilation error, or they may forget that the String case matches the runtime type, not the compile-time type of the reference.

How to eliminate wrong answers

Option A is wrong because the switch does not fall through to the default; the String case matches exactly, so "Unknown" is never assigned. Option B is wrong because the code compiles successfully; Java 17+ supports pattern matching for switch with type patterns, and the switch expression is complete with a default branch. Option D is wrong because obj is not an Integer; it is a String, so the Integer case does not match.

64
MCQhard

Given the following switch statement: ```java int x = 2; switch (x) { default: System.out.print("default "); case 1: System.out.print("1 "); case 2: System.out.print("2 "); case 3: System.out.print("3 "); break; case 4: System.out.print("4 "); } ``` What is the output?

A.2
B.2 3 4
C.2 3
D.default 1 2 3
AnswerC

Prints 2, then falls through to 3 and breaks.

Why this answer

Option C is correct because the switch statement starts execution at the matching case (case 2) and then falls through to subsequent cases until a break statement is encountered. Since case 2 has no break, it prints "2 ", then falls through to case 3, prints "3 ", and the break terminates the switch. The default case is not executed because a matching case was found before it.

Exam trap

The trap here is that candidates often forget fall-through behavior or assume the default case always executes, leading them to pick options that include default or skip the break's effect on subsequent cases.

How to eliminate wrong answers

Option A is wrong because it assumes only the matching case executes, ignoring fall-through behavior in switch statements without break. Option B is wrong because it incorrectly includes case 4, but the break in case 3 prevents fall-through to case 4. Option D is wrong because it assumes the default case executes first, but default only runs if no matching case is found; here case 2 matches, so default is skipped.

65
MCQeasy

Consider the following code: ```java boolean a = true, b = false, c = false; if (a && b || c) { System.out.println("True"); } else { System.out.println("False"); } ``` What is the output?

A.The code does not compile because of invalid boolean expression.
B.False
C.The output cannot be determined without runtime values.
D.True
AnswerB

Correct. a&&b is false, then false||c is false.

Why this answer

The expression `a && b || c` evaluates as `(a && b) || c` due to operator precedence (`&&` has higher precedence than `||`). With `a=true`, `b=false`, `c=false`, `(true && false)` is `false`, then `false || false` is `false`, so the `else` branch prints "False". Option B is correct.

Exam trap

The trap here is that candidates often misinterpret the expression as `a && (b || c)` due to left-to-right reading, forgetting that `&&` has higher precedence than `||` in Java.

How to eliminate wrong answers

Option A is wrong because the boolean expression is syntactically valid; Java allows mixing `&&` and `||` in a single expression. Option C is wrong because all variables are initialized with literal values, so the output is deterministic at compile time. Option D is wrong because it assumes the expression evaluates to true, which would only happen if `c` were true or both `a` and `b` were true.

66
Multi-Selectmedium

Which three of the following are valid case values in a traditional switch statement (non-pattern)?

Select 3 answers
A.42
B.true
C.3.14
D.Monday (assuming an enum constant)
E."hello"
AnswersA, D, E

Correct: int is allowed.

Why this answer

Option A is correct because in a traditional switch statement (non-pattern), the case values must be compile-time constants of types that are compatible with the switch expression. Integer literals like 42 are valid case values, as they are constant expressions of type int, which is one of the allowed types (byte, short, char, int, their wrapper classes, String, and enum types).

Exam trap

The trap here is that candidates often assume any primitive type or literal can be used in a switch case, forgetting that only byte, short, char, int, String, and enum constants are allowed, and that boolean and floating-point types are explicitly excluded.

67
MCQeasy

A developer needs to iterate over a List<String> and remove elements that are null. Which approach guarantees correct behavior without throwing a ConcurrentModificationException?

A.Use a for-each loop and call list.remove() on the current element
B.Use a Stream's filter() method and collect the results
C.Use a traditional for loop with an index that decrements
D.Use an Iterator explicitly and call its remove() method
AnswerD

Iterator.remove() is the safe way to remove elements during iteration.

Why this answer

Option A is correct because Iterator.remove() is the safe way to modify a collection during iteration. Option B is wrong because using List.remove() inside a for-each loop will cause ConcurrentModificationException. Option C is wrong because while it may work, it is not the recommended best practice and can be error-prone.

Option D is wrong because using a for loop with index decrement also works but is not the idiomatic Java approach.

68
MCQeasy

How many times does the following loop execute? int i=0; while(i<5) { System.out.println(i); i++; }

A.0
B.6
C.5
D.4
AnswerC

The loop runs for i=0 through i=4, which is 5 iterations.

Why this answer

The loop starts with i=0, checks the condition i<5 (true), prints i, then increments i. This repeats until i becomes 5, at which point i<5 is false and the loop terminates. Thus, the loop executes exactly 5 times (i=0,1,2,3,4).

Exam trap

The trap here is that candidates often miscount the iterations by starting at 1 instead of 0, or forget that the condition is checked before each execution, leading them to choose 4 or 6 instead of the correct 5.

How to eliminate wrong answers

Option A is wrong because the loop condition i<5 is true when i=0, so the loop body executes at least once, not zero times. Option B is wrong because the loop stops when i reaches 5, so it executes 5 times, not 6; a sixth iteration would require i<5 to be true when i=5, which it is not. Option D is wrong because the loop executes for i=0 through i=4 inclusive, which is 5 iterations, not 4; the increment happens after each print, so i=4 is the last value printed.

Page 1 of 2 · 77 questions totalNext →

Ready to test yourself?

Try a timed practice session using only Program Flow questions.