29% complete
Control Flow in Java
Control flow statements determine the order in which your code executes. In this tutorial, you'll learn how to use conditional statements, loops, and other control structures to make decisions and repeat actions in your Java programs.
Decision Making with Conditional Statements
Conditional statements allow your program to make decisions based on certain conditions. Java provides several types of conditional statements.
The if Statement
The simplest form of decision making is the if
statement, which executes a block of code only if a specified condition is true:
1// Basic if statement2int age = 18;34if (age >= 18) {5 System.out.println("You are an adult.");6}78// The code inside the curly braces will only execute if age is at least 18
The if-else Statement
The if-else
statement provides an alternative path of execution when the condition is false:
1// if-else statement2int age = 16;34if (age >= 18) {5 System.out.println("You are an adult.");6} else {7 System.out.println("You are a minor.");8}910// Output: "You are a minor." (because age is less than 18)
The if-else-if Ladder
For multiple conditions, you can use the if-else-if
ladder:
1// if-else-if ladder2int score = 85;34if (score >= 90) {5 System.out.println("Grade: A");6} else if (score >= 80) {7 System.out.println("Grade: B");8} else if (score >= 70) {9 System.out.println("Grade: C");10} else if (score >= 60) {11 System.out.println("Grade: D");12} else {13 System.out.println("Grade: F");14}1516// Output: "Grade: B" (because score is 85)
Important Note:
In an if-else-if ladder, as soon as a condition is true, its corresponding block executes and the rest of the conditions are skipped. If none of the conditions are true, the final else block (if present) executes.
Nested if Statements
You can nest if statements inside other if or else blocks:
1// Nested if statements2int age = 25;3boolean hasLicense = true;45if (age >= 18) {6 System.out.println("You are an adult.");78 if (hasLicense) {9 System.out.println("You can drive a car.");10 } else {11 System.out.println("You need a license to drive.");12 }13} else {14 System.out.println("You are a minor.");15 System.out.println("You cannot drive a car.");16}1718// Output:19// "You are an adult."20// "You can drive a car."
Ternary Operator (Conditional Operator)
The ternary operator provides a shorthand way to write simple if-else statements:
1// Ternary operator2int age = 20;34// Syntax: condition ? expression1 : expression25String status = (age >= 18) ? "adult" : "minor";67System.out.println("You are a " + status);8// Output: "You are a adult"910// Equivalent if-else statement:11// if (age >= 18) {12// status = "adult";13// } else {14// status = "minor";15// }
The switch Statement
The switch
statement is an alternative to the if-else-if ladder when you need to test a variable against multiple values:
1// switch statement2int day = 4;34switch (day) {5 case 1:6 System.out.println("Monday");7 break;8 case 2:9 System.out.println("Tuesday");10 break;11 case 3:12 System.out.println("Wednesday");13 break;14 case 4:15 System.out.println("Thursday");16 break;17 case 5:18 System.out.println("Friday");19 break;20 case 6:21 System.out.println("Saturday");22 break;23 case 7:24 System.out.println("Sunday");25 break;26 default:27 System.out.println("Invalid day");28}2930// Output: "Thursday" (because day is 4)
Important:
The break
statement is crucial in a switch statement. Without it, execution will "fall through" to the next case, regardless of whether its condition matches. The default
case is optional and executes when none of the cases match.
Switch Expression (Java 12+)
Java 12 introduced a new form of switch that can be used as an expression:
1// Switch expression (Java 12+)2int day = 4;34String dayName = switch (day) {5 case 1 -> "Monday";6 case 2 -> "Tuesday";7 case 3 -> "Wednesday";8 case 4 -> "Thursday";9 case 5 -> "Friday";10 case 6 -> "Saturday";11 case 7 -> "Sunday";12 default -> "Invalid day";13};1415System.out.println(dayName);16// Output: "Thursday"
The switch expression uses the ->
arrow syntax instead of colons and doesn't require break statements. It automatically yields a value that can be assigned to a variable.
Repetition with Loops
Loops allow you to execute a block of code repeatedly. Java provides several types of loops.
The for Loop
The for
loop is ideal when you know in advance how many times you want to execute a block of code:
1// Basic for loop2for (int i = 1; i <= 5; i++) {3 System.out.println("Count: " + i);4}56// Output:7// Count: 18// Count: 29// Count: 310// Count: 411// Count: 5
The for loop syntax has three parts:
for (initialization; condition; update) { // code to be executed }
- Initialization: Executed once at the beginning (usually initializes a counter variable)
- Condition: Checked before each iteration; loop continues as long as it's true
- Update: Executed after each iteration (usually increments or decrements the counter)
Enhanced for Loop (for-each)
The enhanced for loop (also known as the for-each loop) simplifies iterating over arrays and collections:
1// Enhanced for loop (for-each)2int[] numbers = {1, 2, 3, 4, 5};34for (int num : numbers) {5 System.out.println("Number: " + num);6}78// Output:9// Number: 110// Number: 211// Number: 312// Number: 413// Number: 5
The while Loop
The while
loop executes a block of code as long as a specified condition is true:
1// while loop2int count = 1;34while (count <= 5) {5 System.out.println("Count: " + count);6 count++;7}89// Output is the same as the for loop example above
The while loop checks the condition before entering the loop. If the condition is false initially, the loop body will not execute at all.
The do-while Loop
The do-while
loop is similar to the while loop, but it checks the condition after executing the loop body, ensuring that the loop executes at least once:
1// do-while loop2int count = 1;34do {5 System.out.println("Count: " + count);6 count++;7} while (count <= 5);89// Output is the same as previous examples1011// Even if the condition is initially false, the loop executes once:12int x = 10;13do {14 System.out.println("This will print once");15 x++;16} while (x < 10);
for Loop
Best when you know the number of iterations in advance or need to iterate over a range of values.
while Loop
Best when the number of iterations depends on a condition that may change during execution.
do-while Loop
Best when you need the loop to execute at least once, regardless of the condition.
Loop Control Statements
Java provides statements to alter the normal flow of loops.
The break Statement
The break
statement terminates the loop immediately and continues execution after the loop:
1// break statement in a loop2for (int i = 1; i <= 10; i++) {3 if (i == 6) {4 break; // Exit the loop when i is 65 }6 System.out.println("Count: " + i);7}89// Output:10// Count: 111// Count: 212// Count: 313// Count: 414// Count: 515// (loop terminates when i is 6)
The continue Statement
The continue
statement skips the current iteration and proceeds to the next iteration:
1// continue statement in a loop2for (int i = 1; i <= 10; i++) {3 if (i % 2 == 0) {4 continue; // Skip even numbers5 }6 System.out.println("Odd number: " + i);7}89// Output:10// Odd number: 111// Odd number: 312// Odd number: 513// Odd number: 714// Odd number: 9
Labeled Statements
You can use labels with break
and continue
to control nested loops:
1// Labeled break statement2outerLoop: for (int i = 1; i <= 3; i++) {3 for (int j = 1; j <= 3; j++) {4 if (i == 2 && j == 2) {5 break outerLoop; // Break out of both loops6 }7 System.out.println("i = " + i + ", j = " + j);8 }9}1011// Output:12// i = 1, j = 113// i = 1, j = 214// i = 1, j = 315// i = 2, j = 116// (execution stops when i=2, j=2)
Practical Examples
Let's look at some real-world examples that use control flow statements:
Example 1: Simple ATM Menu
1import java.util.Scanner;23public class ATMMenu {4 public static void main(String[] args) {5 Scanner scanner = new Scanner(System.in);6 double balance = 1000.0;7 boolean isRunning = true;89 while (isRunning) {10 System.out.println("\nATM Menu:");11 System.out.println("1. Check Balance");12 System.out.println("2. Deposit");13 System.out.println("3. Withdraw");14 System.out.println("4. Exit");15 System.out.print("Enter your choice: ");1617 int choice = scanner.nextInt();1819 switch (choice) {20 case 1:21 System.out.println("Your balance is: $" + balance);22 break;23 case 2:24 System.out.print("Enter deposit amount: $");25 double depositAmount = scanner.nextDouble();26 if (depositAmount <= 0) {27 System.out.println("Invalid amount!");28 } else {29 balance += depositAmount;30 System.out.println("Deposit successful. New balance: $" + balance);31 }32 break;33 case 3:34 System.out.print("Enter withdrawal amount: $");35 double withdrawAmount = scanner.nextDouble();36 if (withdrawAmount <= 0) {37 System.out.println("Invalid amount!");38 } else if (withdrawAmount > balance) {39 System.out.println("Insufficient funds!");40 } else {41 balance -= withdrawAmount;42 System.out.println("Withdrawal successful. New balance: $" + balance);43 }44 break;45 case 4:46 System.out.println("Thank you for using our ATM. Goodbye!");47 isRunning = false;48 break;49 default:50 System.out.println("Invalid choice. Please try again.");51 }52 }5354 scanner.close();55 }56}
Example 2: Prime Number Checker
1public class PrimeNumberChecker {2 public static void main(String[] args) {3 // Check numbers from 1 to 204 for (int num = 1; num <= 20; num++) {5 boolean isPrime = true;67 // Check if the number is prime8 if (num == 1) {9 isPrime = false; // 1 is not a prime number10 } else {11 // Check if number is divisible by any integer from 2 to num-112 for (int i = 2; i <= Math.sqrt(num); i++) {13 if (num % i == 0) {14 isPrime = false;15 break; // No need to check further16 }17 }18 }1920 // Print result21 if (isPrime) {22 System.out.println(num + " is a prime number");23 } else {24 System.out.println(num + " is not a prime number");25 }26 }27 }28}
Example 3: Nested Loops for Pattern Printing
1public class PatternPrinting {2 public static void main(String[] args) {3 int rows = 5;45 // Print a pyramid pattern6 for (int i = 1; i <= rows; i++) {7 // Print spaces8 for (int j = 1; j <= rows - i; j++) {9 System.out.print(" ");10 }1112 // Print stars13 for (int k = 1; k <= 2 * i - 1; k++) {14 System.out.print("*");15 }1617 System.out.println(); // Move to the next line18 }1920 // Output:21 // *22 // ***23 // *****24 // *******25 // *********26 }27}
Common Mistakes to Avoid
Mistake | Description | Solution |
---|---|---|
Infinite Loops | Forgetting to update the loop variable or using a condition that never becomes false | Always ensure there's a way for the loop condition to become false |
Off-by-One Errors | Looping one too many or too few times (e.g., using <= instead of <) | Double-check loop boundaries, especially when working with arrays |
Missing Break in Switch | Forgetting to include break statements in switch cases | Always include break statements unless fall-through is intentional |
Using == for String Comparison | Using == to compare strings instead of equals() method | Use str1.equals(str2) for string content comparison |
Practice Exercises
- Create a program that prints the multiplication table for a given number (1 to 10).
- Write a program that finds the factorial of a number using a loop.
- Create a program that checks if a number is a palindrome (reads the same forward and backward).
- Write a program that prints the Fibonacci sequence up to a specified number of terms.
- Create a simple calculator program that performs basic arithmetic operations based on user input.
Summary
In this tutorial, you've learned:
- How to use conditional statements (
if
,if-else
,if-else-if
, ternary operator) to make decisions in your code - How to use the
switch
statement for multi-way branching - How to use different types of loops (
for
,while
,do-while
) to repeat code execution - How to control loop execution with
break
andcontinue
statements - How to apply control flow concepts in practical examples
Control flow is a fundamental aspect of programming that allows you to create dynamic and responsive applications. By mastering these concepts, you'll be able to write more efficient and effective Java programs that can make decisions, respond to different conditions, and process data iteratively.
In the next tutorial, we'll explore object-oriented programming in Java, which builds upon these control flow concepts to create more structured and maintainable code.
Related Tutorials
Learn about different types of data and how to store them in Java.
Learn moreUnderstand the fundamentals of OOP in Java.
Learn moreLearn how to create and use methods in Java.
Learn more