Core Module
12 min forge
Java Control Flow Basics
Master the logic that drives Java applications. Conditional statements, loops, and branching logic.
Java Control Flow Basics
π‘οΈ What is Control Flow?
Control flow refers to the order in which statements are executed in a program. In Java, logic is controlled using decision-making, looping, and branching statements. Without control flow, programs would execute linearly from top to bottom.
β° When to Use
- Conditional Logic: Using
if,else, andswitchto execute code based on specific conditions. - Iteration: Using
for,while, anddo-whileto repeat tasks until a condition is met. - Branching: Using
break,continue, andreturnto alter the loop's natural course.
π Complexity & Performance
- Decision Trees:
if-elsechains have $O(n)$ complexity in the worst case, whereasswitchstatements can be optimized by the JVM into a branch table ($O(1)$) for dense case values. - Loops: Iterating through a collection of size $N$ is $O(N)$. Nested loops lead to $O(N^2)$ or higher, which should be avoided in performance-critical sections.
π» Code Example: Dynamic Evaluation
java Standardpublic class ControlFlowDemo { public static void main(String[] args) { int score = 85; // 1. Ternary Operator (Sugar for simple if-else) String status = (score >= 60) ? "Pass" : "Fail"; // 2. Structured Choice (Switch-Case) char grade; switch (score / 10) { case 10: case 9: grade = 'A'; break; case 8: grade = 'B'; break; case 7: grade = 'C'; break; default: grade = 'F'; } // 3. Enhanced For-Loop (Iteration) int[] milestones = {10, 20, 30, 40, 50}; for (int m : milestones) { if (m > score) continue; // Skip if milestone not reached System.out.println("Milestone achieved: " + m); } } }
β οΈ Interview Pitfalls
- Forget the
break: In aswitchstatement, forgetting abreakresults in "fall-through," where subsequent cases execute even if their conditions aren't met. - Infinite Loops: Always ensure the loop condition eventually becomes false. A common bug is modifying the iterator inside the loop in a way that prevents termination.
- Floating Point Comparison: Never use
==to comparefloatordoublein loop conditions orifstatements due to precision errors. Use a threshold (epsilon). - Equality vs. Reference: When comparing Strings in
ifstatements, use.equals()instead of==. The latter checks memory address, not content.