Control Statements in Java

A control statement in Java is a statement that determines whether the other statements will be executed or not. It controls the flow of a program.

Types of control statements in Java

There are three types of control statements in Java:

  • Selection statements: Selection statements are used to make decisions based on certain conditions. These statements in Java are the if statement, the else statement, and the switch statement.
  • Looping statements: Looping statements are used to execute a block of code repeatedly. These statements in Java are the while loop, the do-while loop, and the for loop.
  • Jump statements: Jump statements are used to change the flow of execution of a program. These statements in Java are the break statement, the continue statement, and the return statement.

Control statements are essential for writing efficient and well-structured Java programs. They allow us to control the flow of execution of our program and to make decisions based on certain conditions.

if Statement

In Java, the if statement is used to execute a block of code if a specified condition is true. If the condition is false, the code inside the if statement will not be executed.

The syntax of an if statement in Java is as follows:

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

Optionally, we can use else to specify a block of code to be executed when the condition is false:

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

We can also use else if to chain multiple conditions:

if (condition1) {
    // Code to be executed if condition1 is true
} else if (condition2) {
    // Code to be executed if condition1 is false and condition2 is true
} else {
    // Code to be executed if both condition1 and condition2 are false
}

Following is an example of using an if statement to check if a number is positive or negative:

public class IfExample {
    public static void main(String[] args) {
        int number = -5; // You can change this value to test different cases

        if (number > 0) {
            System.out.println("The number is positive.");
        } else if (number < 0) {
            System.out.println("The number is negative.");
        } else {
            System.out.println("The number is zero.");
        }
    }
}

In this example, the program checks the value of the number variable. If it is greater than 0, it prints “The number is positive.” If it is less than 0, it prints “The number is negative.” Otherwise, if the value is 0, it prints “The number is zero.”

The if statement is a fundamental control flow construct in Java and allows us to make decisions based on the evaluation of conditions. It is widely used to control the flow of our programs based on different scenarios.

switch Statement

In Java, the switch statement is used to perform different actions based on the value of an expression or a variable. It is an alternative to using multiple if-else statements when we have a series of conditions to check against the same variable.

The syntax of a switch statement in Java is as follows:

switch (expression) {
    case value1:
        // Code to be executed if expression is equal to value1
        break;
    case value2:
        // Code to be executed if expression is equal to value2
        break;
    // more cases can be added as needed
    default:
        // Code to be executed if none of the cases match the expression
        break;
}

Following is an example of using a switch statement to handle different day names based on numeric input:

public class SwitchExample {
    public static void main(String[] args) {
        int dayOfWeek = 3; // You can change this value to test different cases

        switch (dayOfWeek) {
            case 1:
                System.out.println("Sunday");
                break;
            case 2:
                System.out.println("Monday");
                break;
            case 3:
                System.out.println("Tuesday");
                break;
            case 4:
                System.out.println("Wednesday");
                break;
            case 5:
                System.out.println("Thursday");
                break;
            case 6:
                System.out.println("Friday");
                break;
            case 7:
                System.out.println("Saturday");
                break;
            default:
                System.out.println("Invalid input. Please enter a number between 1 and 7.");
                break;
        }
    }
}

Output:

Tuesday

In this example, the dayOfWeek variable is set to 3. The switch statement evaluates the value of dayOfWeek, and because it matches case 3, it prints “Tuesday” to the console. If we change the value of dayOfWeek to any other integer between 1 and 7, the corresponding case will be executed, and if the value is outside this range, the default block will be executed, printing “Invalid input.”

The switch statement provides a clean and concise way to handle multiple cases based on the value of an expression. Note that each case block is terminated with a break statement to exit the switch block and prevent fall-through behavior.

while loop

The while loop in Java allows us to repeatedly execute a block of code as long as a given condition is true.

The general syntax of a while loop in Java is as follows:

while (condition) {
    // Code to be executed as long as the condition is true
    // This code will repeat until the condition becomes false
    // Make sure to have a way to update the condition to avoid infinite loops
}

Following is an example of using a while loop to print numbers from 1 to 5:

public class WhileLoopExample {
    public static void main(String[] args) {
        int i = 1;

        while (i <= 5) {
            System.out.println(i);
            i++; // Increment i to avoid an infinite loop
        }
    }
}

In this example, the while loop will execute as long as the value of i is less than or equal to 5. It will print the value of i and then increment i by 1 in each iteration. The loop will terminate when i becomes greater than 5, and the program will move to the next line of code after the while loop.

The output of this code will be:

1
2
3
4
5

Remember to ensure that the condition inside the while loop eventually becomes false to prevent infinite loops. Always include a way to update the loop control variable so that the loop can eventually terminate.

do while loop

The do while loop in Java is similar to the while loop, but it guarantees that the loop body will be executed at least once, even if the condition is initially false.

The syntax of a do-while loop in Java is as follows:

do {
    // Code to be executed
    // This code will repeat until the condition becomes false
} while (condition);

Following is an example of using a do-while loop to print numbers from 1 to 5:

public class DoWhileLoopExample {
    public static void main(String[] args) {
        int i = 1;

        do {
            System.out.println(i);
            i++; // Increment i in each iteration
        } while (i <= 5);
    }
}

In this example, the do-while loop will execute at least once because the code inside the loop is executed first, and then the condition i <= 5 is checked. If the condition is still true, the loop will repeat. It will print the value of i and then increment i by 1 in each iteration. The loop will terminate when i becomes greater than 5, and the program will move to the next line of code after the do-while loop. The output of this code will be the same as the previous example:

1
2
3
4
5

The do-while loop is useful when we want to ensure that the loop body executes at least once, regardless of the condition. It is commonly used when we need to get user input and then check the validity of the input in the loop body.

for loop

The for loop in Java is used to repeatedly execute a block of code for a specified number of times. It is particularly useful when we know in advance how many times we want the loop to run.

The syntax of a for loop in Java is as follows:

for (initialization; condition; update) {
    // Code to be executed in each iteration
}

Following is an example of using a for loop to print numbers from 1 to 5:

public class ForLoopExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.println(i);
        }
    }
}

In this example, the for loop has three parts:

  1. Initialization (int i = 1;): This part is executed before the loop starts and is used to set up the loop control variable (i in this case).
  2. Condition (i <= 5;): The loop continues as long as the condition is true. If the condition becomes false, the loop stops.
  3. Update (increment or decrement) (i++): This part is executed after each iteration and updates the loop control variable (i in this case).

The loop will execute the code inside the loop body (printing the value of i) for i equal to 1, 2, 3, 4, and 5. After that, the condition i <= 5 becomes false, and the loop terminates.

The output of this code will be:

1
2
3
4
5

The for loop is commonly used when we know the exact number of iterations we need, and it provides a concise and clear way to express such loops.

break statement

In Java, the break statement is used to immediately exit from a loop or a switch statement. When the break statement is encountered inside a loop or a switch block, the control flow jumps to the statement immediately following the loop or the switch block, effectively terminating the loop or the switch prematurely.

Inside Loop

The break statement can be used inside a loop to stop the loop execution prematurely based on a certain condition. It is commonly used to exit a loop early if a specific condition is met.

Example of using break inside a loop:

public class BreakExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            if (i == 6) {
                break; // Exit the loop when i becomes 6
            }
            System.out.println("Iteration: " + i);
        }
    }
}

Output:

Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5

Inside a Switch Statement

The break statement is also used inside a switch statement to exit the switch block once a matching case is found. Without the break statement, the program would “fall through” to the next case, executing all subsequent cases until a break or the end of the switch is encountered.

Example of using break inside a switch statement:

public class SwitchBreakExample {
    public static void main(String[] args) {
        int dayOfWeek = 3;

        switch (dayOfWeek) {
            case 1:
                System.out.println("Sunday");
                break;
            case 2:
                System.out.println("Monday");
                break;
            case 3:
                System.out.println("Tuesday");
                break;
            default:
                System.out.println("Invalid input.");
                break;
        }
    }
}

Output:

Tuesday

In both cases, the break statement is used to terminate the loop or the switch early, allowing the program to continue with the next statement outside the loop or the switch.

continue statement

In Java, the continue statement is used inside a loop to immediately skip the remaining code within the loop for the current iteration and move on to the next iteration. When the continue statement is encountered, the loop control variable is updated (if necessary) and the loop proceeds with the next iteration, ignoring the code that follows the continue statement for the current iteration.

Inside loop

The continue statement is typically used to skip certain iterations of a loop based on a specific condition.

Example of using continue inside a loop:

public class ContinueExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            if (i == 3) {
                continue; // Skip the rest of the code in the loop for i=3
            }
            System.out.println("Iteration: " + i);
        }
    }
}

Output:

Iteration: 1
Iteration: 2
Iteration: 4
Iteration: 5

As we can see, the iteration with i=3 was skipped because of the continue statement, and the loop continued with the next iteration.

Inside Nested Loops

The continue statement is also used in nested loops to control the flow within both the inner and outer loops.

Example of using continue inside nested loops:

public class NestedContinueExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            System.out.println("Outer loop, i: " + i);
            for (int j = 1; j <= 2; j++) {
                if (j == 1) {
                    continue; // Skip the rest of the code in the inner loop for j=1
                }
                System.out.println("   Inner loop, j: " + j);
            }
        }
    }
}

Output:

Outer loop, i: 1
   Inner loop, j: 2
Outer loop, i: 2
   Inner loop, j: 2
Outer loop, i: 3
   Inner loop, j: 2

In this example, the continue statement inside the inner loop causes the inner loop to skip executing the rest of the code for j=1 and move to the next iteration (j=2). The outer loop continues as usual.

The continue statement is a useful control flow statement to selectively skip certain iterations in a loop when a particular condition is met.

return statement

In Java, the return statement is used to exit a method and return a value (if the method has a return type) to the caller of the method. It can also be used to terminate the execution of a method without returning any value.

The return statement has the following syntax:

return; // Used in methods with void return type, exits the method without returning any value
return expression; // Used in methods with non-void return type, returns the value of 'expression'

Let’s see some examples of using return in Java methods:

Method with void return type

public class VoidReturnExample {
    public static void main(String[] args) {
        printMessage("Hello, World!");
    }

    public static void printMessage(String message) {
        System.out.println(message);
        return; // This 'return' statement is optional in void return type methods
    }
}

Output:

Hello, World!

Method with a non-void return type

public class NonVoidReturnExample {
    public static void main(String[] args) {
        int result = sum(5, 10);
        System.out.println("The sum is: " + result);
    }

    public static int sum(int a, int b) {
        int total = a + b;
        return total; // Returns the value of 'total' to the caller
    }
}

Output:

The sum is: 15

In this example, the method sum takes two integer arguments and returns their sum. The return statement is used to send the computed value back to the caller. The main method then prints the returned value.

It’s important to note that once the return statement is encountered in a method, the method execution immediately stops, and any code after the return statement in the method will not be executed. If the method has a return type, the returned value should match the type specified in the method signature. If the method is of type void, the return statement without an expression simply exits the method without returning any value.

FAQs

What are control statements in Java?

Control statements are programming constructs in Java that determine the flow of execution in a program. They enable us to make decisions, repeat actions, and control the order in which statements are executed.

How many types of control statements are there in Java?

There are three primary types of control statements in Java:
Conditional Control Statements: These include if, else if, and switch statements, which allow you to make decisions based on conditions.
Looping Control Statements: These include for, while, and do-while loops, which enable you to repeat a set of statements.
Unconditional Control Statements These statements allow us to jump to another part of our program without checking any conditions. The most common unconditional control statements are the break and continue statements.

What is the purpose of the “if-else” statement in Java?

The “if-else” statement allows us to execute different blocks of code based on a condition. If the condition is true, the code inside the “if” block is executed; otherwise, the code inside the “else” block is executed.

When should I use a “for” loop, a “while” loop, or a “do-while” loop in Java?

Use a “for” loop when you know the number of iterations in advance.
Use a “while” loop when you want to repeat an action while a condition is true.
Use a “do-while” loop when you want to ensure the loop body is executed at least once before checking the condition.