Control Flow in Java
Learn how to make decisions and repeat actions in your programs
Think of control flow like a choose-your-own-adventure book! Sometimes you make decisions (if this happens, go to page 10), sometimes you repeat things (do this 5 times), and sometimes you skip parts. Control flow lets your program make choices and repeat actions just like you do in real life!
🤔 Conditional Statements (Making Decisions)
Like choosing which path to take
if Statement
Executes code only if condition is true
💡 If it's raining, take an umbrella
if (condition) { /* code */ }if-else Statement
Chooses between two options
💡 If it's hot, wear shorts, else wear pants
if (condition) { /* code1 */ } else { /* code2 */ }if-else if-else
Chooses from multiple options
💡 If A grade, celebrate; else if B, good job; else study more
if (c1) { } else if (c2) { } else { }Nested if
if statements inside other if statements
💡 If it's weekend, if it's sunny, go to beach
if (c1) { if (c2) { /* code */ } }📝 Code Examples: Conditional Statements
public class ConditionalDemo { public static void main(String[] args) { // Simple if int temperature = 30; if (temperature > 25) { System.out.println("It's hot! Wear shorts."); } // if-else int age = 16; if (age >= 18) { System.out.println("You can vote!"); } else { System.out.println("Too young to vote."); } // if-else if-else int score = 85; if (score >= 90) { System.out.println("Grade: A - Excellent!"); } else if (score >= 80) { System.out.println("Grade: B - Good job!"); // This runs } else if (score >= 70) { System.out.println("Grade: C - Fair"); } else if (score >= 60) { System.out.println("Grade: D - Needs improvement"); } else { System.out.println("Grade: F - Study more!"); } // Nested if boolean hasTicket = true; boolean hasID = true; if (hasTicket) { if (hasID) { System.out.println("Welcome to the concert!"); // This runs } else { System.out.println("Need ID to enter."); } } else { System.out.println("Need a ticket first!"); } // Logical operators in conditions int money = 50; boolean isWeekend = true; if (money >= 30 && isWeekend) { System.out.println("Let's go to the movies!"); // This runs } if (money < 20 || !isWeekend) { System.out.println("Stay home and relax."); } }}🔁 Loops (Repeating Actions)
Like doing something over and over
for Loop
Repeat a specific number of times
💡 Do 10 pushups (you know exactly how many)
for (init; condition; update) { }When you know how many times to repeat
while Loop
Repeat while condition is true
💡 Keep eating while you're hungry
while (condition) { }When you don't know how many times
do-while Loop
Do first, then check condition
💡 Try the food first, then decide if you want more
do { } while (condition);When you want to run at least once
Enhanced for Loop
Loop through collections easily
💡 Check each item in your backpack
for (Type item : collection) { }When iterating through arrays/collections
📝 Code Examples: Loops
public class LoopDemo { public static void main(String[] args) { // FOR LOOP - Know exact number of iterations System.out.println("Counting 1 to 5:"); for (int i = 1; i <= 5; i++) { System.out.println(i); } // Loop through array int[] numbers = {10, 20, 30, 40, 50}; System.out.println("\nArray elements:"); for (int i = 0; i < numbers.length; i++) { System.out.println("Index " + i + ": " + numbers[i]); } // WHILE LOOP - Don't know exact iterations System.out.println("\nGuessing game:"); int target = 7; int guess = 1; while (guess != target) { System.out.println("Guessing: " + guess); guess += 2; } System.out.println("Found it! " + guess); // Reading input (conceptual example) int countdown = 5; while (countdown > 0) { System.out.println("Launch in: " + countdown); countdown--; } System.out.println("Blast off!"); // DO-WHILE LOOP - Run at least once System.out.println("\nDo-while example:"); int password = 1234; int attempt; do { attempt = 5678; // Simulating user input System.out.println("Trying password: " + attempt); if (attempt != password) { System.out.println("Wrong! Try again."); } } while (attempt != password && attempt > 0); // ENHANCED FOR LOOP (for-each) - Easy iteration String[] fruits = {"Apple", "Banana", "Orange", "Mango"}; System.out.println("\nFruits in basket:"); for (String fruit : fruits) { System.out.println("- " + fruit); } // Nested loops - Multiplication table System.out.println("\n5x5 Multiplication Table:"); for (int row = 1; row <= 5; row++) { for (int col = 1; col <= 5; col++) { System.out.print((row * col) + "\t"); } System.out.println(); // New line after each row } }}⏭️ Jump Statements (Skipping and Stopping)
Like taking shortcuts or saying 'I'm done!'
break
Exit the loop immediately
💡 Stop searching once you find what you need
continue
Skip to next iteration
💡 Skip this song and go to the next one
return
Exit the method immediately
💡 Leave the building and go home
📝 Code Examples: Jump Statements
public class JumpDemo { public static void main(String[] args) { // BREAK - Exit loop immediately System.out.println("Finding first even number:"); int[] numbers = {1, 3, 5, 8, 9, 10, 11}; for (int num : numbers) { if (num % 2 == 0) { System.out.println("Found: " + num); break; // Stop searching once found } System.out.println("Checking: " + num); } // CONTINUE - Skip to next iteration System.out.println("\nPrint only positive numbers:"); int[] values = {-2, 3, -5, 7, -8, 10}; for (int val : values) { if (val < 0) { continue; // Skip negative numbers } System.out.println(val); // Only prints: 3, 7, 10 } // Skip multiples of 3 System.out.println("\nNumbers from 1-10 (skip multiples of 3):"); for (int i = 1; i <= 10; i++) { if (i % 3 == 0) { continue; // Skip 3, 6, 9 } System.out.print(i + " "); // Prints: 1 2 4 5 7 8 10 } // RETURN - Exit method int result = findFirstNegative(values); System.out.println("\n\nFirst negative: " + result); // Labeled break (advanced) System.out.println("\nLabeled break example:"); outerLoop: for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { System.out.println("i=" + i + ", j=" + j); if (i == 2 && j == 2) { break outerLoop; // Breaks out of both loops! } } } } // Method demonstrating return public static int findFirstNegative(int[] arr) { for (int num : arr) { if (num < 0) { return num; // Exit method and return value } } return 0; // No negative found }}🎛️ Switch Statement (Multiple Choices)
Like a menu with many options
public class SwitchDemo { public static void main(String[] args) { // Basic switch int day = 3; switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); // This runs break; case 4: System.out.println("Thursday"); break; case 5: System.out.println("Friday"); break; default: System.out.println("Weekend!"); } // Multiple cases, same action char grade = 'B'; switch (grade) { case 'A': case 'B': System.out.println("Excellent!"); // This runs break; case 'C': System.out.println("Good"); break; case 'D': System.out.println("Passed"); break; case 'F': System.out.println("Failed"); break; default: System.out.println("Invalid grade"); } // Switch with String String fruit = "Apple"; switch (fruit) { case "Apple": System.out.println("Red and sweet"); // This runs break; case "Banana": System.out.println("Yellow and soft"); break; case "Orange": System.out.println("Orange and juicy"); break; default: System.out.println("Unknown fruit"); } // Switch expression (Java 12+) String season = "Summer"; String activity = switch (season) { case "Spring" -> "Plant flowers"; case "Summer" -> "Go swimming"; case "Fall" -> "Collect leaves"; case "Winter" -> "Build snowman"; default -> "Stay inside"; }; System.out.println("Activity: " + activity); // Calculator example int a = 10, b = 5; char operator = '+'; int result; switch (operator) { case '+': result = a + b; System.out.println("Result: " + result); // 15 break; case '-': result = a - b; System.out.println("Result: " + result); break; case '*': result = a * b; System.out.println("Result: " + result); break; case '/': result = a / b; System.out.println("Result: " + result); break; default: System.out.println("Invalid operator"); } }}🌟 Real-World Examples
public class RealWorldExamples { public static void main(String[] args) { // Example 1: Validate password strength String password = "Pass123!"; boolean hasUpper = false, hasLower = false, hasDigit = false; for (int i = 0; i < password.length(); i++) { char ch = password.charAt(i); if (Character.isUpperCase(ch)) hasUpper = true; if (Character.isLowerCase(ch)) hasLower = true; if (Character.isDigit(ch)) hasDigit = true; } if (hasUpper && hasLower && hasDigit && password.length() >= 8) { System.out.println("Strong password!"); } else { System.out.println("Weak password. Needs improvement."); } // Example 2: Find prime numbers System.out.println("\nPrime numbers from 1 to 20:"); for (int num = 2; num <= 20; num++) { boolean isPrime = true; for (int i = 2; i <= Math.sqrt(num); i++) { if (num % i == 0) { isPrime = false; break; // Not prime, stop checking } } if (isPrime) { System.out.print(num + " "); } } // Example 3: Calculate sum of array int[] scores = {85, 92, 78, 95, 88}; int sum = 0; for (int score : scores) { sum += score; } double average = (double) sum / scores.length; System.out.println("\n\nAverage score: " + average); // Example 4: Pattern printing System.out.println("\nRight triangle:"); for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) { System.out.print("* "); } System.out.println(); } // Example 5: Reverse a string String text = "Hello"; String reversed = ""; for (int i = text.length() - 1; i >= 0; i--) { reversed += text.charAt(i); } System.out.println("\nOriginal: " + text); System.out.println("Reversed: " + reversed); }}💼 Interview Tips
- 💡Know the difference between for, while, and do-while loops
- 💡Understand when to use break vs continue
- 💡Remember: do-while runs at least once, while may not run at all
- 💡Be careful with infinite loops (condition always true)
- 💡Switch works with int, char, String, and enums
- 💡Enhanced for loop (for-each) can't modify the collection
- 💡Nested loops: understand time complexity (O(n²) for double loop)
⚠️ Common Mistakes
- ✗Using = instead of == in conditions (if (x = 5) assigns, not compares)
- ✗Forgetting break in switch statements (causes fall-through)
- ✗Creating infinite loops accidentally (while(true) without break)
- ✗Off-by-one errors in for loops (starting at 1 instead of 0)
- ✗Modifying loop variable inside enhanced for loop
- ✗Using semicolon after if/while condition: if (x > 5); { }
- ✗Not considering edge cases (empty arrays, null values)