Progress4 of 14 topics

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:

java
1// Basic if statement
2int age = 18;
3
4if (age >= 18) {
5 System.out.println("You are an adult.");
6}
7
8// 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:

java
1// if-else statement
2int age = 16;
3
4if (age >= 18) {
5 System.out.println("You are an adult.");
6} else {
7 System.out.println("You are a minor.");
8}
9
10// 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:

java
1// if-else-if ladder
2int score = 85;
3
4if (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}
15
16// 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:

java
1// Nested if statements
2int age = 25;
3boolean hasLicense = true;
4
5if (age >= 18) {
6 System.out.println("You are an adult.");
7
8 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}
17
18// 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:

java
1// Ternary operator
2int age = 20;
3
4// Syntax: condition ? expression1 : expression2
5String status = (age >= 18) ? "adult" : "minor";
6
7System.out.println("You are a " + status);
8// Output: "You are a adult"
9
10// 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:

java
1// switch statement
2int day = 4;
3
4switch (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}
29
30// 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:

java
1// Switch expression (Java 12+)
2int day = 4;
3
4String 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};
14
15System.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:

java
1// Basic for loop
2for (int i = 1; i <= 5; i++) {
3 System.out.println("Count: " + i);
4}
5
6// Output:
7// Count: 1
8// Count: 2
9// Count: 3
10// Count: 4
11// 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:

java
1// Enhanced for loop (for-each)
2int[] numbers = {1, 2, 3, 4, 5};
3
4for (int num : numbers) {
5 System.out.println("Number: " + num);
6}
7
8// Output:
9// Number: 1
10// Number: 2
11// Number: 3
12// Number: 4
13// Number: 5

The while Loop

The while loop executes a block of code as long as a specified condition is true:

java
1// while loop
2int count = 1;
3
4while (count <= 5) {
5 System.out.println("Count: " + count);
6 count++;
7}
8
9// 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:

java
1// do-while loop
2int count = 1;
3
4do {
5 System.out.println("Count: " + count);
6 count++;
7} while (count <= 5);
8
9// Output is the same as previous examples
10
11// 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:

java
1// break statement in a loop
2for (int i = 1; i <= 10; i++) {
3 if (i == 6) {
4 break; // Exit the loop when i is 6
5 }
6 System.out.println("Count: " + i);
7}
8
9// Output:
10// Count: 1
11// Count: 2
12// Count: 3
13// Count: 4
14// Count: 5
15// (loop terminates when i is 6)

The continue Statement

The continue statement skips the current iteration and proceeds to the next iteration:

java
1// continue statement in a loop
2for (int i = 1; i <= 10; i++) {
3 if (i % 2 == 0) {
4 continue; // Skip even numbers
5 }
6 System.out.println("Odd number: " + i);
7}
8
9// Output:
10// Odd number: 1
11// Odd number: 3
12// Odd number: 5
13// Odd number: 7
14// Odd number: 9

Labeled Statements

You can use labels with break and continue to control nested loops:

java
1// Labeled break statement
2outerLoop: 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 loops
6 }
7 System.out.println("i = " + i + ", j = " + j);
8 }
9}
10
11// Output:
12// i = 1, j = 1
13// i = 1, j = 2
14// i = 1, j = 3
15// i = 2, j = 1
16// (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

java
1import java.util.Scanner;
2
3public 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;
8
9 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: ");
16
17 int choice = scanner.nextInt();
18
19 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 }
53
54 scanner.close();
55 }
56}

Example 2: Prime Number Checker

java
1public class PrimeNumberChecker {
2 public static void main(String[] args) {
3 // Check numbers from 1 to 20
4 for (int num = 1; num <= 20; num++) {
5 boolean isPrime = true;
6
7 // Check if the number is prime
8 if (num == 1) {
9 isPrime = false; // 1 is not a prime number
10 } else {
11 // Check if number is divisible by any integer from 2 to num-1
12 for (int i = 2; i <= Math.sqrt(num); i++) {
13 if (num % i == 0) {
14 isPrime = false;
15 break; // No need to check further
16 }
17 }
18 }
19
20 // Print result
21 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

java
1public class PatternPrinting {
2 public static void main(String[] args) {
3 int rows = 5;
4
5 // Print a pyramid pattern
6 for (int i = 1; i <= rows; i++) {
7 // Print spaces
8 for (int j = 1; j <= rows - i; j++) {
9 System.out.print(" ");
10 }
11
12 // Print stars
13 for (int k = 1; k <= 2 * i - 1; k++) {
14 System.out.print("*");
15 }
16
17 System.out.println(); // Move to the next line
18 }
19
20 // Output:
21 // *
22 // ***
23 // *****
24 // *******
25 // *********
26 }
27}

Common Mistakes to Avoid

MistakeDescriptionSolution
Infinite LoopsForgetting to update the loop variable or using a condition that never becomes falseAlways ensure there's a way for the loop condition to become false
Off-by-One ErrorsLooping one too many or too few times (e.g., using <= instead of <)Double-check loop boundaries, especially when working with arrays
Missing Break in SwitchForgetting to include break statements in switch casesAlways include break statements unless fall-through is intentional
Using == for String ComparisonUsing == to compare strings instead of equals() methodUse str1.equals(str2) for string content comparison

Practice Exercises

  1. Create a program that prints the multiplication table for a given number (1 to 10).
  2. Write a program that finds the factorial of a number using a loop.
  3. Create a program that checks if a number is a palindrome (reads the same forward and backward).
  4. Write a program that prints the Fibonacci sequence up to a specified number of terms.
  5. 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 and continue 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 more

Understand the fundamentals of OOP in Java.

Learn more

Learn how to create and use methods in Java.

Learn more