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, and switch to execute code based on specific conditions.
  • Iteration: Using for, while, and do-while to repeat tasks until a condition is met.
  • Branching: Using break, continue, and return to alter the loop's natural course.

πŸ“Š Complexity & Performance

  • Decision Trees: if-else chains have $O(n)$ complexity in the worst case, whereas switch statements 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 Standard
public 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

  1. Forget the break: In a switch statement, forgetting a break results in "fall-through," where subsequent cases execute even if their conditions aren't met.
  2. 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.
  3. Floating Point Comparison: Never use == to compare float or double in loop conditions or if statements due to precision errors. Use a threshold (epsilon).
  4. Equality vs. Reference: When comparing Strings in if statements, use .equals() instead of ==. The latter checks memory address, not content.