Control Flow
Branching with if and switch, looping with for, while and do-while, jumping with break and continue, and the compiler's unreachable-code analysis. Modern switch expressions and pattern matching make this a livelier area than it used to be.
part ofJavaoverview, primer and where to startread it →on this pageshowhide
explore
- if / if-else5 questions
- Traditional switch Statement4 questions
- Switch Expressions5 questions
- Pattern Matching in switch5 questions
- for Loop5 questions
- Enhanced for-each Loop5 questions
- while & do-while Loops5 questions
- break, continue & Labels5 questions
- Unreachable Code Detection5 questions
questions
page 2 of 2How do break and continue affect while and do-while loops, including labeled forms?
basics
~20 sbreak exits the loop immediately. continue skips the rest of the current iteration and jumps to the next condition check. A label like outer: lets break/continue target an outer loop instead of the innermost one.
Describe an idiomatic use of a while loop for reading input or iterating, such as the sentinel-controlled read pattern.
basics
~20 sA common pattern is reading until a stop signal: while ((line = reader.readLine()) != null) { ... }. The loop keeps going until the read returns a special value (a sentinel, like null or -1) that means there is no more data.
When should you prefer break/continue versus an early return or extracted method for controlling loop flow?
basics
~20 sUse break/continue when the loop's work belongs in the current method and you just need to stop or skip. Prefer extracting the loop into its own method and using return when the loops are deeply nested or the logic is complex, because return exits everything cleanly and reads better.
How would you make your own class usable in a for-each loop?
basics
~10 sMake the class implement Iterable<T> and provide an iterator() method that returns an Iterator<T> with working hasNext() and next() methods. Then it can be used directly in for-each.
When should you NOT use a for-each loop, and what should you use instead?
basics
~20 sAvoid for-each when you need the index, want to go in reverse or skip elements, must remove items, or must walk two collections together. Use a classic indexed for loop, an explicit Iterator, or removeIf instead.
In a Java for loop, what is the scope of a counter declared in the header, and what common off-by-one and update pitfalls should you watch for?
basics
~20 sA counter declared in the for header only exists inside the loop. Common bugs are using < vs <= wrongly (off-by-one), modifying the counter inside the body, and changing the collection size while looping by index.
When should you favor guard clauses (early returns) over deeply nested if statements?
basics
~10 sA guard clause checks an invalid or special case early and returns immediately, so the main logic stays unindented. Prefer it over deep nesting because it keeps code flat and easier to read.
How does exhaustiveness work in a pattern switch, and how do sealed types let you write a switch with no default?
basics
~20 sA pattern switch must handle every possible value (be exhaustive). If you switch over a sealed type, the compiler knows all its allowed subtypes, so once you cover each one you don't need a default — and if someone adds a new subtype later, the switch stops compiling until you handle it.
Walk through refactoring an `if-else` chain of `instanceof` + cast into a pattern switch. What are the pitfalls (dominance, fall-through, null) to watch for?
basics
~20 sReplace each if (x instanceof T t) branch with a case T t -> label in a switch over x. Use guards (when) for the extra conditions, keep the most specific cases first, add case null if null is possible, and make it exhaustive with a default or full subtype coverage.
What are the special unreachability rules for catch blocks and checked exceptions?
basics
~20 sA catch block is a compile error if its exception type can never be thrown by the try body. For checked exceptions, you can't catch a type the try can't throw; but you can always catch RuntimeException, Error, or Exception, because those can occur anywhere.
What are the exact semantics of how Java evaluates a while loop's condition, including side effects, short-circuiting, and choosing while vs for?
basics
~20 sJava evaluates the while condition before each iteration as a boolean expression. The condition can have side effects (like assignment) and uses short-circuit && / || so later parts may not run. Choose while when iteration count is unknown and for when it is known.
How does the Java compiler implement a traditional switch in bytecode, and what scoping subtlety exists for variables declared inside a switch block?
basics
~20 sThe compiler turns a switch into one of two jump instructions: tableswitch (a dense jump table) or lookupswitch (a sorted list of key/offset pairs). All cases share one scope, so a variable declared in one case is visible (but maybe uninitialized) in the others.
Why is Java's reachability analysis conservative, and what kinds of obviously-dead code does it NOT reject?
basics
~20 sThe compiler only flags code it can prove unreachable using fixed rules — it doesn't run your program. So code that's effectively dead because of runtime values (like 'if (x > 0) return;' followed by code when x is always positive) is not rejected; only structurally-impossible code is.
How do null selectors and adoption tradeoffs affect choosing arrow switch expressions in a codebase?
basics
~20 sA traditional switch throws NullPointerException if the selector is null. Classic arrow switch expressions over enums/strings do the same unless you guard for null first. Adopting them widely improves safety but needs a recent Java version.
showing 31–44 of 44