# Java Beginner Guide - Part 2: Control Flow ## Table of Contents - [Introduction](#introduction) - [Conditional Statements](#conditional-statements) - [Switch Statements](#switch-statements) - [Loops - For Loops](#loops---for-loops) - [Loops - While Loops](#loops---while-loops) - [Loops - Do-While Loops](#loops---do-while-loops) - [Loop Control - Break and Continue](#loop-control---break-and-continue) - [Nested Loops](#nested-loops) - [Practice Exercises](#practice-exercises) --- ## Introduction Control flow determines the order in which your code runs. By default, Java executes statements one after another. But what if you want to make decisions? What if you want to repeat something? That's where control flow comes in! In this guide, you'll learn: - How to make decisions with if/else - How to choose between multiple options with switch - How to repeat code with loops --- ## Conditional Statements Conditional statements let your program make decisions based on conditions. ### The if Statement The `if` statement runs code only when a condition is true. ```java int age = 18; if (age >= 18) { System.out.println("You are an adult!"); } ``` ### The if-else Statement Add an `else` block to run code when the condition is false. ```java int age = 16; if (age >= 18) { System.out.println("You are an adult!"); } else { System.out.println("You are a minor!"); } ``` ### The if-else-if Statement Chain multiple conditions together. ```java int score = 85; if (score >= 90) { System.out.println("Grade: A"); } else if (score >= 80) { System.out.println("Grade: B"); } else if (score >= 70) { System.out.println("Grade: C"); } else if (score >= 60) { System.out.println("Grade: D"); } else { System.out.println("Grade: F"); } ``` ### Comparison Operators Remember these from Part 1? | Operator | Meaning | Example | |----------|---------|---------| | `==` | Equal to | `a == b` | | `!=` | Not equal to | `a != b` | | `>` | Greater than | `a > b` | | `<` | Less than | `a < b` | | `>=` | Greater or equal | `a >= b` | | `<=` | Less or equal | `a <= b` | ### Logical Operators Combine multiple conditions: ```java int age = 25; int income = 50000; if (age >= 18 && income >= 30000) { System.out.println("You qualify for the loan!"); } // OR example boolean hasCard = false; boolean hasCash = true; if (hasCard || hasCash) { System.out.println("You can make a purchase!"); } ``` | Operator | Meaning | Example | |----------|---------|---------| | `&&` | AND (both must be true) | `a && b` | | `\|\|` | OR (at least one must be true) | `a \|\| b` | | `!` | NOT (reverses true/false) | `!a` | ### Ternary Operator (Shortcut) A compact if-else in one line: ```java // Instead of: String result; if (age >= 18) { result = "Adult"; } else { result = "Minor"; } // You can write: String result = (age >= 18) ? "Adult" : "Minor"; ``` --- ## Switch Statements When you have many conditions to check, `switch` can be cleaner than if-else. ### Basic Switch ```java int day = 3; String dayName; switch (day) { case 1: dayName = "Monday"; break; case 2: dayName = "Tuesday"; break; case 3: dayName = "Wednesday"; break; case 4: dayName = "Thursday"; break; case 5: dayName = "Friday"; break; case 6: dayName = "Saturday"; break; case 7: dayName = "Sunday"; break; default: dayName = "Invalid day"; } System.out.println(dayName); // Wednesday ``` ### Switch with Multiple Cases Group cases together: ```java char grade = 'B'; switch (grade) { case 'A': case 'B': case 'C': System.out.println("You passed!"); break; case 'D': case 'F': System.out.println("You failed."); break; default: System.out.println("Invalid grade."); } ``` ### Switch Expression (Java 14+) A shorter way to use switch: ```java int day = 3; String dayName = switch (day) { case 1 -> "Monday"; case 2 -> "Tuesday"; case 3 -> "Wednesday"; case 4 -> "Thursday"; case 5 -> "Friday"; case 6 -> "Saturday"; case 7 -> "Sunday"; default -> "Invalid"; }; ``` > **Note:** The `->` syntax requires Java 14 or later. Use the traditional `switch` for older versions. ### Why Use Switch? - Cleaner than long if-else chains - Good for menus and choices - Can be used as an expression (Java 14+) --- ## Loops - For Loops Loops let you repeat code multiple times. The `for` loop is perfect when you know how many times to repeat. ### Basic For Loop ```java for (int i = 1; i <= 5; i++) { System.out.println("Count: " + i); } // Output: // Count: 1 // Count: 2 // Count: 3 // Count: 4 // Count: 5 ``` **The three parts:** 1. `int i = 1` - Start: where to begin 2. `i <= 5` - Condition: when to stop 3. `i++` - Update: what to do each time ### For Loop Breakdown ```java for (int i = 0; i < 10; i++) { // Code runs 10 times (i = 0,1,2,3,4,5,6,7,8,9) } for (int i = 10; i > 0; i--) { // Countdown from 10 to 1 } for (int i = 0; i <= 20; i += 2) { // Even numbers from 0 to 20 } ``` ### For-Each Loop (Enhanced For) Loop through arrays and collections without an index: ```java String[] fruits = {"Apple", "Banana", "Cherry"}; for (String fruit : fruits) { System.out.println(fruit); } // Output: // Apple // Banana // Cherry ``` --- ## Loops - While Loops The `while` loop repeats as long as a condition is true. Use it when you don't know how many times to repeat. ### Basic While Loop ```java int count = 1; while (count <= 5) { System.out.println("Count: " + count); count++; // Don't forget this or it loops forever! } // Output: // Count: 1 // Count: 2 // Count: 3 // Count: 4 // Count: 5 ``` ### While vs For Loop ```java // For loop - when you know the count for (int i = 0; i < 5; i++) { System.out.println(i); } // While loop - when count is unknown Scanner scanner = new Scanner(System.in); int number; System.out.println("Enter a positive number:"); number = scanner.nextInt(); while (number <= 0) { System.out.println("Invalid! Enter positive:"); number = scanner.nextInt(); } System.out.println("Thanks!"); ``` ### Infinite Loop Warning Be careful! If the condition never becomes false, the loop runs forever: ```java // BAD - infinite loop! // while (true) { // System.out.println("This runs forever!"); // } ``` --- ## Loops - Do-While Loops The `do-while` loop runs the code **at least once** before checking the condition. ### Basic Do-While ```java int count = 1; do { System.out.println("Count: " + count); count++; } while (count <= 5); // Output: // Count: 1 // Count: 2 // Count: 3 // Count: 4 // Count: 5 ``` ### While vs Do-While ```java // While - might not run at all int num = 10; while (num < 5) { System.out.println("This won't print"); } // Do-While - runs at least once do { System.out.println("This WILL print once"); } while (num < 5); ``` ### Practical Example: User Input ```java Scanner scanner = new Scanner(System.in); String choice; do { System.out.println("Menu: 1. Play 2. Score 3. Exit"); System.out.print("Enter choice: "); choice = scanner.nextLine(); switch (choice) { case "1": System.out.println("Playing..."); break; case "2": System.out.println("Score: 100"); break; case "3": System.out.println("Goodbye!"); break; default: System.out.println("Invalid choice!"); } } while (!choice.equals("3")); ``` --- ## Loop Control - Break and Continue ### Break - Exit the Loop Immediately ```java for (int i = 1; i <= 10; i++) { if (i == 5) { break; // Exit the loop when i is 5 } System.out.println(i); } // Output: 1, 2, 3, 4 ``` ### Continue - Skip Current Iteration ```java for (int i = 1; i <= 5; i++) { if (i == 3) { continue; // Skip when i is 3 } System.out.println(i); } // Output: 1, 2, 4, 5 (3 is skipped) ``` ### Practical Examples **Break - Finding an item:** ```java String[] names = {"Alice", "Bob", "Charlie", "Diana"}; for (String name : names) { if (name.equals("Charlie")) { System.out.println("Found Charlie!"); break; // No need to keep searching } } ``` **Continue - Filtering:** ```java // Print only even numbers for (int i = 1; i <= 10; i++) { if (i % 2 != 0) { continue; // Skip odd numbers } System.out.println(i); } ``` --- ## Nested Loops A loop inside another loop! This is useful for patterns and grids. ### Basic Nested Loop ```java for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { System.out.println("i=" + i + ", j=" + j); } } // Output: // i=1, j=1 // i=1, j=2 // i=1, j=3 // i=2, j=1 // ... and so on ``` ### Print a Pattern ```java // Print a square of stars for (int row = 1; row <= 4; row++) { for (int col = 1; col <= 4; col++) { System.out.print("* "); } System.out.println(); // New line after each row } // Output: // * * * * // * * * * // * * * * // * * * * ``` ### Multiplication Table ```java // Print 1-5 times table for (int i = 1; i <= 5; i++) { for (int j = 1; j <= 10; j++) { System.out.printf("%2d x %2d = %2d ", i, j, i*j); } System.out.println(); } ``` --- ## Practice Exercises ### Exercise 1: Even or Odd Write a program that asks for a number and tells if it's even or odd. ```java import java.util.Scanner; public class EvenOrOdd { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); int num = scanner.nextInt(); if (num % 2 == 0) { System.out.println("Even!"); } else { System.out.println("Odd!"); } } } ``` ### Exercise 2: Grade Calculator Convert a numeric score to a letter grade. ```java public class GradeCalculator { public static void main(String[] args) { int score = 87; char grade; if (score >= 90) { grade = 'A'; } else if (score >= 80) { grade = 'B'; } else if (score >= 70) { grade = 'C'; } else if (score >= 60) { grade = 'D'; } else { grade = 'F'; } System.out.println("Grade: " + grade); } } ``` ### Exercise 3: Count to Ten Use a for loop to print numbers 1 to 10. ```java public class CountToTen { public static void main(String[] args) { for (int i = 1; i <= 10; i++) { System.out.println(i); } } } ``` ### Exercise 4: Sum of Numbers Calculate the sum of 1 to 100. ```java public class SumNumbers { public static void main(String[] args) { int sum = 0; for (int i = 1; i <= 100; i++) { sum += i; } System.out.println("Sum: " + sum); // 5050 } } ``` ### Exercise 5: Multiplication Table Print the 5 times table using a loop. ```java public class TimesTable { public static void main(String[] args) { int num = 5; for (int i = 1; i <= 10; i++) { System.out.println(num + " x " + i + " = " + (num * i)); } } } ``` ### Exercise 6: Find the Maximum Find the largest number in an array. ```java public class FindMax { public static void main(String[] args) { int[] numbers = {5, 12, 3, 8, 99, 1}; int max = numbers[0]; for (int i = 1; i < numbers.length; i++) { if (numbers[i] > max) { max = numbers[i]; } } System.out.println("Maximum: " + max); // 99 } } ``` ### Exercise 7: FizzBuzz Print numbers 1 to 20, but: - Print "Fizz" for multiples of 3 - Print "Buzz" for multiples of 5 - Print "FizzBuzz" for multiples of both ```java public class FizzBuzz { public static void main(String[] args) { for (int i = 1; i <= 20; i++) { if (i % 3 == 0 && i % 5 == 0) { System.out.println("FizzBuzz"); } else if (i % 3 == 0) { System.out.println("Fizz"); } else if (i % 5 == 0) { System.out.println("Buzz"); } else { System.out.println(i); } } } } ``` --- ## Summary In this guide, you learned: - ✅ How to make decisions with if, else if, and else - ✅ How to use comparison and logical operators - ✅ How to use the ternary operator for short conditions - ✅ How to use switch statements for multiple choices - ✅ How to use for loops when you know the count - ✅ How to use while loops when you don't know the count - ✅ How to use do-while loops for at-least-once execution - ✅ How to control loops with break and continue - ✅ How to use nested loops for patterns **Next Steps:** Move on to [Java Beginner Part 3](./Java-Beginner-Part3.md) to learn about methods and arrays! --- *Great job! Keep practicing! 🎉*