Table of contents
1.
Introduction
2.
Java Control Statements 
3.
Decision-Making statements
3.1.
1) If Statement
3.1.1.
1) Simple if statement:
3.2.
2) if-else statement
3.3.
3) if-else-if ladde
3.4.
4. Nested if-statement
4.
Switch Statement
5.
Loop Statements
5.1.
1. `for` loop:
5.2.
2. `while` loop
5.3.
3. `do-while` loop:
6.
Java for loop
6.1.
Java for-each loop
7.
Java while loop
8.
Java do-while loop
9.
Jump Statements
9.1.
1. `break` statement
9.2.
2. `continue` statement
9.3.
3. `return` statement
10.
Java break statement
10.1.
1. Exiting a loop based on a condition
10.2.
2. Breaking out of nested loops
10.3.
3. Exiting a switch statement
11.
Java continue statement
11.1.
1. Skipping specific iterations based on a condition:
11.2.
2. Skipping iterations based on a complex condition
11.3.
3. Using `continue` with labeled statement
12.
Frequently Asked Questions
12.1.
Can we use break & continue statements with if-else statements?
12.2.
What happens if we don't use break statements in a switch case?
12.3.
Can we use the return statement instead of break to exit a loop?
13.
Conclusion
Last Updated: Nov 16, 2024

Control Statements in Java

Author Gaurav Gandhi
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In any programming language, control statements play a very important role in directing the flow of a program. They allow users to make decisions, repeat actions, and control the execution of code based on specific conditions. Java, which is one of the most popular programming languages, also offers a variety of control statements that help programmers to create dynamic and responsive applications. 

Control Statements in Java

In this article, we will discuss the different types of control statements in Java and understand how they can be used. We will cover decision-making statements like if, if-else, if-else-if ladder, and switch and loop statements like for, for-each, while, & do-while. Moreover, we will discuss jump statements like break & continue, which help in altering the normal flow of execution. 

Java Control Statements 

Control statements in Java control the flow of execution in a program. They allow you to make decisions, repeat actions, and alter the normal flow of code execution based on specific conditions. Java provides several types of control statements, including decision-making statements, loop statements, and jump statements.

Decision-making statements, such as if, if-else, if-else-if ladder, & switch, enable you to execute different blocks of code based on certain conditions. These statements evaluate a condition & then execute the corresponding code block if the condition is true. They help in creating branching logic within your program

Loop statements, like for, for-each, while, & do-while, are used to repeat a block of code multiple times. They allow you to iterate over a collection of elements or execute a code block until a specific condition is met. Loop statements are essential for performing repetitive tasks & processing large amounts of data.

Jump statements, like break and continue, alter the normal execution flow. The break statement prematurely exits a loop or switch statement, while the continue statement skips the current iteration of a loop and moves to the next iteration.

Decision-Making statements

Decision-making statements in Java allow you to execute different blocks of code based on specific conditions. These statements evaluate a condition and then execute the corresponding code block if the condition is true. Java provides several decision-making statements, including if, if-else, if-else-if ladder, and switch.

The if statement is the most basic decision-making statement. It checks a condition and executes a block of code if the condition is true. If the condition is false, the code block is skipped, and the program continues with the next statement.

The if-else statement is an extension of the if statement. It allows you to specify a block of code to be executed if the condition is true & another block of code to be executed if the condition is false. This enables you to handle both the true & false cases of a condition.

The if-else-if ladder is used when you have multiple conditions to evaluate. It allows you to chain multiple if-else statements together, where each condition is checked in order until a true condition is found. Once a true condition is encountered, the corresponding code block is executed, & the rest of the ladder is skipped.

The switch statement is used when you have a single expression with multiple possible values. It allows you to specify different code blocks to be executed based on the value of the expression. Each case in the switch statement represents a possible value, & the corresponding code block is executed when the expression matches that value.

1) If Statement

The if statement is the most basic decision-making statement in Java. It allows you to execute a block of code if a specified condition is true. The syntax of an if statement is:

 

if (condition) {
    // code block to be executed if the condition is true
}

 

The condition is an expression that evaluates to either true or false. If the condition is true, the code block inside the curly braces `{}` is executed. If the condition is false, the code block is skipped, & the program continues with the next statement after the if block.

For example : 

public class Main {
   public static void main(String[] args) {
       int age = 18;
       if (age >= 18) {
           System.out.println("You are eligible to vote!");
       }
   }
}
 
You can also try this code with Online Java Compiler
Run Code


Output

You are eligible to vote!


In this example, the if statement checks if the value of the `age` variable is greater than or equal to 18. If the condition is true, the message "You are eligible to vote!" is printed to the console. If the condition is false, the code block is skipped, & the program continues with the next statement.

Note: The if statement is helpful when you want to execute a specific block of code only if a certain condition is met. It allows you to make decisions based on the values of variables or the results of expressions.

1) Simple if statement:

A simple if statement is the most basic form of the if statement. It allows you to execute a block of code if a specified condition is true. The syntax of a simple if statement is:

if (condition) {
    // code block to be executed if the condition is true
}

 

The condition is an expression that evaluates to either true or false. If the condition is true, the code block inside the curly braces `{}` is executed. If the condition is false, the code block is skipped, & the program continues with the next statement after the if block.

 

For example : 

public class Main {
   public static void main(String[] args) {
       int num = 10;
       if (num > 0) {
           System.out.println("The number is positive.");
       }
   }
}
 
You can also try this code with Online Java Compiler
Run Code


In this example, the if statement checks if the value of the `num` variable is greater than 0. If the condition is true, the message "The number is positive" is printed to the console. If the condition is false, the code block is skipped, and the program continues with the next statement.

Note: The simple if statement is helpful when you want to execute a specific block of code only if a certain condition is met. It allows you to make decisions based on the values of variables or the results of expressions.

2) if-else statement

The if-else statement is an extension of the if statement that allows you to specify a block of code to be executed if the condition is true & another block of code to be executed if the condition is false. The syntax of an if-else statement is

if (condition) {
    // code block to be executed if the condition is true
} else {
    // code block to be executed if the condition is false
}

 

If the condition is true, the code block inside the first set of curly braces `{}` is executed. If the condition is false, the code block inside the second set of curly braces `{}`, following the `else` keyword, is executed.

For example : 

public class Main {
   public static void main(String[] args) {
       int num = -5;
       if (num >= 0) {
           System.out.println("The number is non-negative.");
       } else {
           System.out.println("The number is negative.");
       }
   }
}
 
You can also try this code with Online Java Compiler
Run Code

 

Output

The number is negative.

 

In this example, the if-else statement checks if the value of the `num` variable is greater than or equal to 0. If the condition is true, the message "The number is non-negative." is printed to the console. If the condition is false, the code block following the `else` keyword is executed, & the message "The number is negative." is printed to the console.

 

Note: The if-else statement is useful when you want to execute different blocks of code based on the outcome of a condition. It allows you to handle both the true and false cases of a condition and take appropriate actions accordingly.

3) if-else-if ladde

The if-else-if ladder is used when you have multiple conditions to evaluate. It allows you to chain multiple if-else statements together, where each condition is checked in order until a true condition is found. Once a true condition is encountered, the corresponding code block is executed, & the rest of the ladder is skipped. 

The syntax of an if-else-if ladder is :

if (condition1) {
    // code block to be executed if condition1 is true
} else if (condition2) {
    // code block to be executed if condition2 is true
} else if (condition3) {
    // code block to be executed if condition3 is true
} else {
    // code block to be executed if all conditions are false
}

 

The conditions are evaluated in the order they appear. If `condition1` is true, the code block following it is executed, & the rest of the ladder is skipped. If `condition1` is false, the program moves to the next `else if` block & checks `condition2`. If `condition2` is true, its corresponding code block is executed, & the rest of the ladder is skipped. This process continues until a true condition is found or until all conditions are evaluated. If none of the conditions are true, the code block following the final `else` keyword is executed.

 

For example : 

public class Main {
   public static void main(String[] args) {
       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 {
           System.out.println("Grade: D");
       }
   }
}
 
You can also try this code with Online Java Compiler
Run Code

 

Output

Grade: B 


In this example, the if-else-if ladder checks the value of the `score` variable. If the score is greater than or equal to 90, the message "Grade: A" is printed to the console. If the score is between 80 & 89 (inclusive), the message "Grade: B" is printed. If the score is between 70 & 79 (inclusive), the message "Grade: C" is printed. If the score is less than 70, the message "Grade: D" is printed.

When to use: The if-else-if ladder is useful when you have multiple conditions to evaluate and want to execute different blocks of code based on the first true condition encountered. It allows you to handle various scenarios and take appropriate actions based on the values of variables or the results of expressions.

4. Nested if-statement

A nested if statement is an if statement that is placed inside another if statement. It allows you to create more complex decision-making structures where the execution of a certain block of code depends on multiple conditions. 

The syntax of a nested if statement is:

if (condition1) {
    // code block to be executed if condition1 is true
    if (condition2) {
        // code block to be executed if both condition1 & condition2 are true
    }
}

 

In a nested if statement, the inner if statement is only evaluated if the condition of the outer if statement is true. If the condition of the outer if statement is false, the inner if statement is skipped entirely.

For example : 


public class Main {
   public static void main(String[] args) {
       int num = 25;
       if (num > 0) {
           System.out.println("The number is positive.");
           if (num % 2 == 0) {
               System.out.println("The number is even.");
           } else {
               System.out.println("The number is odd.");
           }
       } else {
           System.out.println("The number is non-positive.");
       }
   }
}
 
You can also try this code with Online Java Compiler
Run Code

 

Output

The number is positive.
The number is odd.
 

 

In this example, the outer if statement checks if the value of the `num` variable is greater than 0. If the condition is true, the message "The number is positive." is printed to the console. Then, the inner if statement is evaluated. If `num` is divisible by 2 (i.e., if `num % 2` is equal to 0), the message "The number is even." is printed. Otherwise, the message "The number is odd." is printed.

If the value of `num` is not greater than 0, the outer else block is executed, & the message "The number is non-positive." is printed. In this case, the inner if statement is not evaluated at all.

When to use: Nested-if statements allow you to create more complex decision-making structures where the execution of certain code blocks depends on multiple conditions. They are helpful when you must make decisions based on a combination of conditions.

Switch Statement

The switch statement is used when you have a single expression that can have multiple possible values. It allows you to specify different code blocks to be executed based on the value of the expression. 

 

The syntax of a switch statement is:

switch (expression) {
    case value1:
        // code block to be executed if expression matches value1
        break;
    case value2:
        // code block to be executed if expression matches value2
        break;
    // more cases...
    default:
        // code block to be executed if expression doesn't match any case
}

 

The `expression` is evaluated, and its value is compared against each `case` value. If a match is found, the corresponding code block is executed. The `break` statement at the end of each case is used to exit the switch statement and prevent the execution from falling through to the next case. If no match is found, the code block following the `default` keyword is executed.

For example : 

public class Main {
   public static void main(String[] args) {
       int dayNumber = 3;
       String dayName;
       switch (dayNumber) {
           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 number";
       }
       System.out.println("The day is: " + dayName);
   }
}
 
You can also try this code with Online Java Compiler
Run Code


Output

The day is: Wednesday
 

 

In this example, the `dayNumber` variable holds the value 3. The switch statement compares the value of `dayNumber` against each case. Since `dayNumber` matches the case value of 3, the code block associated with `case 3` is executed, and the `dayName` variable is assigned the value "Wednesday." The `break` statement then exits the switch statement, and the program continues with the next line, printing "The day is: Wednesday" to the console.

If the value of `dayNumber` doesn't match any of the case values, the code block following the `default` keyword is executed, & `dayName` is assigned the value "Invalid day number".

When to use: The switch statement is useful when you have a single expression that can have multiple possible values and want to execute different code blocks based on those values. It provides a more readable and concise way to handle multiple cases than using a series of if-else statements.

Loop Statements

Loop statements in Java are used to repeatedly execute a code block until a certain condition is met. They allow you to automate repetitive tasks and iterate over collections of data. Java provides different types of loop statements, which are `for`, `while`, and `do-while` loops.

1. `for` loop:

The `for` loop is used when you know the exact number of times you want to iterate. It has three parts: initialization, condition, & increment/decrement. 

The syntax of a `for` loop is:

for (initialization; condition; increment/decrement) {
    // code block to be executed
}

 

The initialization part is executed only once, at the beginning of the loop. The condition is checked before each iteration, & if it evaluates to true, the code block is executed. After each iteration, the increment/decrement part is executed, modifying the loop variable.

Example:

public class Main {
   public static void main(String[] args) {
       for (int i = 1; i <= 5; i++) {
           System.out.println(i);
       }
   }
}
 
You can also try this code with Online Java Compiler
Run Code

 

Output:

1
2
3
4
5

2. `while` loop

The `while` loop is used when you want to repeat a block of code as long as a certain condition is true. The syntax of a `while` loop is:

while (condition) {
    // code block to be executed
}

 

The condition is checked before each iteration. If it evaluates to true, the code block is executed. This process continues until the condition becomes false.

Example:

public class Main {
   public static void main(String[] args) {
       int i = 1;
       while (i <= 5) {
           System.out.println(i);
           i++;
       }
   }
}
 
You can also try this code with Online Java Compiler
Run Code

 

Output:

1
2
3
4
5

3. `do-while` loop:

The `do-while` loop is similar to the `while` loop, but the condition is checked after each iteration. This means that the code block is always executed at least once, even if the condition is initially false. The syntax of a `do-while` loop is:

do {
    // code block to be executed
} while (condition);

 

Example:

public class Main {
   public static void main(String[] args) {
       int i = 1;
       do {
           System.out.println(i);
           i++;
       } while (i <= 5);
   }
}
 
You can also try this code with Online Java Compiler
Run Code

 

Output:

1
2
3
4
5

 

Note: Loop statements are useful when you are performing repetitive tasks and iterating over collections of data. They allow you to automate processes & work with large amounts of data efficiently.

Java for loop

The `for` loop is a powerful loop statement in Java that allows you to iterate over a block of code a specific number of times. It provides a concise way to initialize, check the condition, & update the loop variable all in a single line. 

The syntax of a `for` loop is:

for (initialization; condition; update) {
    // code block to be executed
}

 

In this syntax : 

  • `initialization`: This part is executed only once, at the beginning of the loop. It is used to initialize the loop variable or perform any setup required for the loop.
     
  • `condition`: This part is evaluated before each iteration of the loop. If the condition is true, the code block is executed. If the condition is false, the loop terminates.
     
  • `update`: This part is executed after each iteration of the loop. It is used to update the loop variable or perform any necessary modifications.
     

For example : 

public class Main {
   public static void main(String[] args) {
       for (int i = 1; i <= 5; i++) {
           System.out.println(i);
       }
   }
}
 
You can also try this code with Online Java Compiler
Run Code

 

In this example, the loop variable `i` is initialized to 1. The condition `i <= 5` is checked before each iteration. If the condition is true, the code block is executed, which prints the value of `i`. After each iteration, the update part `i++` is executed, incrementing the value of `i` by 1.

The output of this loop will be:

1
2
3
4
5

 

The `for` loop is commonly used when you know the exact number of iterations needed. It provides a concise & readable way to write loops with a specific range or condition.

 

Let’s discuss a few important points about the `for` loop:

  • The initialization, condition, & update parts are optional. You can omit any of them if they are not needed.
     
  • The initialization part can declare & initialize multiple variables, separated by commas.
     
  • The condition part can include any valid Boolean expression.
     
  • The update part can perform any necessary modifications, not just incrementing or decrementing the loop variable.

Java for-each loop

The `for-each` loop, also known as the enhanced `for` loop, is a simplified version of the traditional `for` loop in Java. It provides a more concise & readable way to iterate over arrays or collections. 

The syntax of a `for-each` loop is:

for (dataType element : collection) {
    // code block to be executed
}

 

  • `dataType`: The data type of the elements in the array or collection.
     
  • `element`: A variable that represents each element in the array or collection during the iteration.
     
  • `collection`: The array or collection to be iterated over.

 

The `for-each` loop automatically iterates over each element in the array or collection, assigning each element to the `element` variable in each iteration. This eliminates the need for an explicit loop variable & condition.

For example : 

public class Main {
   public static void main(String[] args) {
       String[] fruits = {"apple", "banana", "orange"};
       for (String fruit : fruits) {
           System.out.println(fruit);
       }
   }
}
 
You can also try this code with Online Java Compiler
Run Code

 

In this example, the `for-each` loop iterates over each element in the `fruits` array. In each iteration, the current element is assigned to the `fruit` variable, which is then used within the loop body to print the value of each fruit.

The output of this loop will be:

apple
banana
orange

 

The `for-each` loop can also be used with collections, such as `ArrayList` or `HashSet`. 

For example : 

import java.util.ArrayList;
public class Main {
   public static void main(String[] args) {
       ArrayList<Integer> numbers = new ArrayList<>();
       numbers.add(1);
       numbers.add(2);
       numbers.add(3);
       for (int num : numbers) {
           System.out.println(num);
       }
   }
}
 
You can also try this code with Online Java Compiler
Run Code

 

In this example, the `for-each` loop iterates over each element in the `numbers` ArrayList. In each iteration, the current element is assigned to the `num` variable, which is then used within the loop body to print the value of each number.

The output of this loop will be:

1
2
3

 

The `for-each` loop provides a more readable & concise way to iterate over arrays & collections compared to the traditional `for` loop. It eliminates the need for an explicit loop variable & condition, making the code cleaner & less error-prone.

Note: It's important to remember that the `for-each` loop is read-only and cannot be used to modify the elements of the array or collection during iteration. If you need to modify the elements or require more control over the iteration process, you should use the traditional `for` loop instead.

Java while loop

The `while` loop is a control flow statement in Java that allows you to repeatedly execute a block of code as long as a specified condition is true. It is used when you don't know the exact number of iterations needed beforehand. 

The syntax of a `while` loop is:

while (condition) {
    // code block to be executed
}

 

- `condition`: A Boolean expression that is evaluated before each iteration of the loop. If the condition is true, the code block is executed. If the condition is false, the loop terminates.

 

The `while` loop begins by evaluating the condition. If the condition is true, the code block inside the loop is executed. After the code block is executed, the condition is evaluated again. This process continues until the condition becomes false, at which point the loop terminates, & the program continues with the next statement after the loop.

For example : 

public class Main {
   public static void main(String[] args) {
       int count = 0;
       while (count < 5) {
           System.out.println("Count: " + count);
           count++;
       }
   }
}
 
You can also try this code with Online Java Compiler
Run Code

 

In this example, the `count` variable is initialized to 0. The `while` loop condition checks if `count` is less than 5. If the condition is true, the code block is executed, which prints the current value of `count` & then increments it by 1. The loop continues until `count` reaches 5, at which point the condition becomes false, & the loop terminates.

The output of this loop will be:

Count: 0
Count: 1
Count: 2
Count: 3
Count: 4

 

It's important to ensure that the condition in a `while` loop eventually becomes false; otherwise, the loop will continue indefinitely, resulting in an infinite loop. To avoid infinite loops, you should make sure that the code inside the loop modifies the variables used in the condition, leading to the condition becoming false at some point.

When to use: The `while` loop is useful when you want to repeat a block of code based on a condition that may change during the execution of the loop. It provides flexibility in scenarios where the number of iterations is not known in advance.

Java do-while loop

The `do-while` loop is similar to the `while` loop, but with one key difference: the code block is executed at least once before the condition is checked. This means that the loop body is guaranteed to execute at least one time, regardless of whether the condition is initially true or false. 

The syntax of a `do-while` loop is:

do {
    // code block to be executed
} while (condition);

 

  • `condition`: A Boolean expression that is evaluated after each iteration of the loop. If the condition is true, the loop continues. If the condition is false, the loop terminates.

The `do-while` loop begins by executing the code block inside the loop. After the code block is executed, the condition is evaluated. If the condition is true, the loop continues, & the code block is executed again. This process continues until the condition becomes false, at which point the loop terminates, & the program continues with the next statement after the loop.

For example : 

public class Main {
   public static void main(String[] args) {
       int count = 0;
       do {
           System.out.println("Count: " + count);
           count++;
       } while (count < 5);
   }
}
 
You can also try this code with Online Java Compiler
Run Code

 

In this example, the `count` variable is initialized to 0. The code block inside the `do-while` loop is executed first, which prints the current value of `count` & then increments it by 1. After the code block is executed, the condition `count < 5` is evaluated. If the condition is true, the loop continues, & the code block is executed again. This process continues until `count` reaches 5, at which point the condition becomes false, & the loop terminates.

Output: 

Count: 0
Count: 1
Count: 2
Count: 3
Count: 4

 

The main difference between a `while` loop & a `do-while` loop is the order in which the condition is checked. In a `while` loop, the condition is checked before each iteration, & the code block may not execute at all if the condition is initially false. In a `do-while` loop, the code block is executed first, & then the condition is checked, ensuring that the code block is executed at least once.

When it can be used: The `do-while` loop is useful in situations where you want to execute a block of code at least once, regardless of the initial condition. It is commonly used when you need to prompt the user for input or perform an action before checking a condition.

Jump Statements

Jump statements in Java are used to transfer the control of execution from one point to another within a program. They allow you to alter the normal flow of execution & perform unconditional jumps or conditional branching. Java provides three types of jump statements: `break`, `continue' & `return`.

1. `break` statement

The `break` statement is used to exit or terminate a loop (such as `for`, `while`, or `do-while`) or a switch statement prematurely. When encountered, the `break` statement immediately terminates the innermost enclosing loop or switch statement & transfers the control to the next statement following the loop or switch.

Example:

public class Main {
   public static void main(String[] args) {
       for (int i = 1; i <= 5; i++) {
           if (i == 3) {
               break;
           }
           System.out.println(i);
       }
   }
}
 
You can also try this code with Online Java Compiler
Run Code

 

Output:

1
2

 

In this example, the `break` statement is used inside the `for` loop. When `i` reaches 3, the `break` statement is encountered, causing the loop to terminate prematurely. The program continues with the next statement after the loop.

2. `continue` statement

The `continue` statement is used to skip the current iteration of a loop (such as `for`, `while`, or `do-while`) & proceed to the next iteration. When encountered, the `continue` statement immediately skips the remaining code block of the current iteration & moves the control to the next iteration of the loop.

Example:

public class Main {
   public static void main(String[] args) {
       for (int i = 1; i <= 5; i++) {
           if (i == 3) {
               continue;
           }
           System.out.println(i);
       }
   }
}
 
You can also try this code with Online Java Compiler
Run Code

 

Output:

1
2
4
5

 

In this example, the `continue` statement is used inside the `for` loop. When `i` reaches 3, the `continue` statement is encountered, causing the current iteration to be skipped. The program continues with the next iteration of the loop.

3. `return` statement

The `return` statement is used to exit a method & return control to the calling method. It can also be used to return a value from a method. When encountered, the `return` statement immediately terminates the execution of the current method & returns the specified value (if any) to the calling method.

Example:

public class Main {
   public static int sum(int a, int b) {
       int result = a + b;
       return result;
   }
   public static void main(String[] args) {
       int a = 5;
       int b = 3;
       int result = sum(a, b);
       System.out.println("The sum is: " + result);
   }
}
 
You can also try this code with Online Java Compiler
Run Code

 

In this example, the `return` statement is used to exit the `sum` method & return the value of `result` to the calling method.

Note: Jump statements provide a way to control the flow of execution in a program. They allow you to exit loops prematurely, skip iterations, or return from methods. However, it's important to use them judiciously & only when necessary to maintain code readability & clarity.

Java break statement

The `break` statement in Java is used to exit or terminate a loop (`for`, `while`, or `do-while`) or a switch statement prematurely. When encountered, the `break` statement immediately terminates the innermost enclosing loop or switch statement & transfers the control to the next statement following the loop or switch.

Let’s discuss a few situations where the `break` statement can be used:

1. Exiting a loop based on a condition

public class Main {
   public static void main(String[] args) {
       for (int i = 1; i <= 3; i++) {
           for (int j = 1; j <= 3; j++) {
               if (i == 2 && j == 2) {
                   break;
               }
               System.out.println("i = " + i + ", j = " + j);
           }
       }
   }
}
 
You can also try this code with Online Java Compiler
Run Code

 

Output:

1
2
3
4

 

In this example, the `break` statement is used inside the `for` loop. When `i` reaches 5, the `break` statement is encountered, causing the loop to terminate prematurely. The program continues with the next statement after the loop.

2. Breaking out of nested loops


public class Main {
   public static void main(String[] args) {
       for (int i = 1; i <= 3; i++) {
           for (int j = 1; j <= 3; j++) {
               if (i == 2 && j == 2) {
                   break;
               }
               System.out.println("i = " + i + ", j = " + j);
           }
       }
   }
}
 
You can also try this code with Online Java Compiler
Run Code


Output:

i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3

 

In this example, the `break` statement is used inside nested loops. When `i` is 2 & `j` is 2, the `break` statement is encountered, causing the innermost loop to terminate prematurely. The program continues with the next iteration of the outer loop.

3. Exiting a switch statement

public class Main {
   public static void main(String[] args) {
       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");
               break;
           default:
               System.out.println("Other day");
       }
   }
}
 
You can also try this code with Online Java Compiler
Run Code

 

Output:

Wednesday

 

In this example, the `break` statement is used within each case of the switch statement. When a matching case is found (in this case, `case 3`), the corresponding code block is executed, & the `break` statement is encountered, causing the switch statement to terminate. The program continues with the next statement after the switch.

When to use: The `break` statement provides a way to exit loops or switch statements prematurely based on certain conditions. It allows you to control the flow of execution & optimize your code by avoiding unnecessary iterations or comparisons.

Java continue statement

The `continue` statement in Java is used to skip the current iteration of a loop (`for`, `while`, or `do-while`) & proceed to the next iteration. When encountered, the `continue` statement immediately skips the remaining code block of the current iteration & moves the control to the next iteration of the loop.

 

Let’s discuss the few situations where the `continue` statement is normally used:

1. Skipping specific iterations based on a condition:

public class Main {
   public static void main(String[] args) {
       for (int i = 1; i <= 5; i++) {
           if (i == 3) {
               continue;
           }
           System.out.println(i);
       }
   }
}
 
You can also try this code with Online Java Compiler
Run Code

 

Output:

1
2
4
5

 

In this example, the `continue` statement is used inside the `for` loop. When `i` reaches 3, the `continue` statement is encountered, causing the current iteration to be skipped. The program continues with the next iteration of the loop.

2. Skipping iterations based on a complex condition

public class Main {
   public static void main(String[] args) {
       for (int i = 1; i <= 10; i++) {
           if (i % 2 == 0) {
               continue;
           }
           System.out.println(i);
       }
   }
}
 
You can also try this code with Online Java Compiler
Run Code

 

Output:

1
3
5
7
9

 

In this example, the `continue` statement is used to skip iterations where `i` is even. The condition `i % 2 == 0` checks if `i` is divisible by 2 (i.e., even). If the condition is true, the `continue` statement is encountered, causing the current iteration to be skipped. The program continues with the next iteration of the loop, printing only the odd numbers.

3. Using `continue` with labeled statement

outerLoop:

public class Main {
   public static void main(String[] args) {
       outerLoop:
       for (int i = 1; i <= 3; i++) {
           for (int j = 1; j <= 3; j++) {
               if (i == 2 && j == 2) {
                   continue outerLoop;
               }
               System.out.println("i = " + i + ", j = " + j);
           }
       }
   }
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3

In this example, the `continue` statement is used with a labeled statement. When `i` is 2 & `j` is 2, the `continue` statement is encountered with the label `outerLoop`, causing the control to skip the remaining iterations of the inner loop & move to the next iteration of the outer loop.

When it can be used: The `continue` statement provides a way to skip specific iterations of a loop based on certain conditions. It allows you to optimize your code by avoiding unnecessary computations or actions within a loop when certain conditions are met.

Frequently Asked Questions

Can we use break & continue statements with if-else statements?

No, break & continue statements are only used with loops & switch statements, not with if-else statements.

What happens if we don't use break statements in a switch case?

If break statements are omitted in a switch case, the execution will fall through to the next case, even if it doesn't match the condition.

Can we use the return statement instead of break to exit a loop?

Yes, the return statement can be used to exit a loop & return from the current method, but it's generally preferred to use break for loop termination.

Conclusion

In this article, we discussed the different control statements in Java, like decision-making statements like if, if-else, if-else-if ladder, & switch, as well as loop statements like for, for-each, while, & do-while. We also discussed jump statements like break & continue, which allow us to alter the normal flow of execution. These control statements provide the necessary tools to create dynamic and flexible programs in Java, which helps developers to make decisions, repeat actions, andcontrol the flow of their code based on specific conditions.

You can also check out our other blogs on Code360.

Live masterclass