Control Statements in Java

Updated on 01/09/20254,759 Views

Overview

Imagine a program like a road trip. Without any directions, it would just travel in a straight line from start to finish. But what if you need to make a decision, repeat a certain route, or take a detour? For that, you need Control Statements in Java.

These statements are the traffic signals, loops, and forks in the road for your code. Control flow Statements in Java are the fundamental tools that allow you to direct the execution path of your program, making it dynamic and intelligent. This guide will break down the three main types, decision-making, looping, and branching—to give you full control over your code. 

Advance your Java programming expertise with our Software Engineering courses and elevate your learning to the next level. 

What Are Control Statements in Java?

Control statements are used in Java to manage a program's execution flow. Based on specific conditions or criteria, they decide which parts of the code should be run and when. Java offers several control statements.

Types of Control Flow Statements

Here are the eight essential types of control statements in Java:

If- else

The if-else control statement allows us to perform different actions based on evaluating a condition. If the condition is true, the code within the if block is executed; otherwise, the code within the else block (if present) is executed. This enables us to control the flow of our program based on specific conditions. 

Example:

public class main {
    public static void main(String[] args) {
        int number = 10;


        if (number > 0) {
            System.out.println("The number is positive.");
        } else {
            System.out.println("The number is non-positive.");
        }
    }
}

In this example, we have an int variable called number initialized with a value of 10.

We use the if-else control statement to check whether the number is greater than 0. If the condition (number > 0) evaluates to true, the code within the if block is executed, which in this case prints "The number is positive." to the console.

If the condition evaluates to false, indicating that number is not greater than 0, the code within the else block is executed, which prints "The number is non-positive." to the console.

When you run this program, it will output "The number is positive." since the value of number is indeed greater than 0.

Accelerate your tech career by mastering future-ready skills in Cloud, DevOps, AI, and Full Stack Development. Gain hands-on experience, learn from industry leaders, and develop the expertise that top employers demand. 

  • Professional Certificate Program in Cloud Computing and DevOps
  • AI-Powered Full Stack Development Course by IIITB
  • Future-Proof Your Tech Career with AI-Driven Full-Stack Development

switch

The switch control statement provides a way to execute different blocks of code based on the value of a variable. It offers a cleaner alternative to using multiple if-else statements when comparing against multiple possible values.

Example:

public class main {
    public static void main(String[] args) {
        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";
                break;
        }

        System.out.println("Day " + day + " is " + dayName + ".");
    }
}

In this example, we have an int variable called day initialized with a value of 3. We also declare a String variable called dayName to store the corresponding name of the day.

We use the switch control statement to match the value of day with different cases. Each case represents a specific value that day could take. When a case matches the value of day, the corresponding block of code is executed.

In this example, when day is 3, the code within the case 3: block is executed, which assigns the value "Wednesday" to dayName. The break; statement is used to exit the switch block once the corresponding case is executed.

If none of the cases match the value of day, the code within the default: block is executed. In this example, if day is any value other than 1-7, the value "Invalid day" is assigned to dayName.

Finally, we print the value of day and dayName using the System.out.println() statement.

When you run this program, it will output "Day 3 is Wednesday.", indicating that the value of day is 3 and the corresponding day name is "Wednesday".

Also Read: JDK in Java: Comprehensive Guide to JDK, JRE, and JVM 

for

The for loop is commonly used when we know the number of iterations in advance or want to iterate over a specific range of values. It provides a concise way to control the iteration process with the initialization, condition, and iteration components all in one line.

Example:

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

This example has a for loop that iterates from 1 to 5. The loop consists of three parts: initialization (int i = 1), condition (i <= 5), and iteration (i++).

Inside the loop, we print the value of i using the System.out.println() statement. The loop will execute five times, printing the value of i from 1 to 5.

while

As long as a particular condition is true, it repeatedly runs a block of code. Each cycle begins with a condition check.

Example:

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

        while (count <= 5) {
            System.out.println("Count: " + count);
            count++;
        }
    }
}

In this example, a while loop executes a block of code repeatedly as long as the condition (count <= 5) evaluates to true. Inside the while loop, we print the value of count and then increment it. The loop will iterate five times, printing the value of count from 1 to 5.

do-while

The condition is verified after the code block has been executed, similar to the "while" statement. As a result, the code block is always run at least once.

Example:

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

        do {
            System.out.println("Count: " + count);
            count++;
        } while (count <= 5);
    }
}

This example has a do-while loop, similar to the while loop. The code block is executed first, then the condition (count <= 5) is checked. If the condition is true, the loop continues to iterate. The loop will execute at least once, regardless of whether the condition is true or false. In this case, it will iterate five times, printing the value of count from 1 to 5.

Also Read: Control Statements in Java: Types, Flowcharts, and Code Examples 

break

It is used to end the current iteration of a loop or switch statement and the entire loop or switch early.

Example:

public class main {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            if (i == 5) {
                break;
            }
            System.out.println("Value: " + i);
        }
    }
}

This example has a for loop that iterates from 1 to 10. Inside the loop, we check if the value of i equals 5. If the condition is true, the break statement is encountered, and the loop is immediately terminated. As a result, the loop will only execute up to the value of 4, and "Value: 5" will not be printed.

continue

It is employed to go directly to the subsequent iteration of a loop while skipping the current iteration.

Example:

public class main {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            if (i == 3) {
                continue;
            }
            System.out.println("Value: " + i);
        }
    }
}

This example has a for loop that iterates from 1 to 5. Inside the loop, we check if the value of i is equal to 3. If the condition is true, the continue statement is encountered, and the remaining code in the loop is skipped for that iteration. As a result, when i is 3, the loop continues to the next iteration, and "Value: 3" is not printed. The loop continues for the remaining iterations, printing "Value: 1", "Value: 2", "Value: 4", and "Value: 5".

Also Read: 50 Java Projects With Source Code in 2025: From Beginner to Advanced 

return

The return statement allows us to terminate the execution of a method and provide a value back to the caller. It is commonly used to return a result or a specific value from a method for further computations or output.

Example:

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


    public static int sum(int a, int b) {
        int sum = a + b;
        return sum;
    }
}

In this example, we have a sum method that takes two integers as parameters (a and b). Inside the method, we calculate the sum of the two numbers and store it in the sum variable.

The return statement is used to return the calculated sum from the method back to the caller. In this case, we return the value of sum.

In the main method, we call the sum method and pass the values 5 and 7 as arguments. The returned value from the sum method is assigned to the result variable.

Finally, we print the value of the result, which will be the sum of 5 and 7, resulting in the output: "Sum: 12".

These control statements offer versatility and let you make programs that can effectively manage various conditions. You may manage the execution flow and strengthen the responsiveness and scalability of your programs by employing the right control statements.

Also Read: File Handling in Java: How to Work with Java Files?

Conclusion

Control Statements in Java are the fundamental building blocks of any meaningful program. They are the tools that transform a simple, top-to-bottom script into a dynamic and intelligent application that can make decisions and repeat actions. 

Mastering the different Control flow Statements in Java—from if-else and switch to loops and jump statements—is what gives you, the programmer, the power to direct your program's logic. It's an essential skill for writing efficient, powerful, and robust Java code. 

To take your skills to the next level, you can check out courses on Java from upGrad. 

FAQs

1. What is the difference between an if-else statement and a switch statement?

You can use the if-else statement to examine a single condition and run various code blocks depending on whether it is true or false. On the other hand, the switch statement enables you to choose which of numerous code blocks to run depending on the result of an expression. You can use the if-else statement to examine a single condition and run various code blocks depending on whether it is true or false. On the other hand, the switch statement enables you to choose which of numerous code blocks to run depending on the result of an expression.

2. When is a while loop preferable to a for loop?

When you need to iterate across a collection or array or when you know the number of iterations in advance, a for loop is typically employed. On the other hand, a while loop is used when a specified condition must be met and the number of iterations is unknown. When you need to iterate across a collection or array or when you know the number of iterations in advance, a for loop is typically employed. On the other hand, a while loop is used when a specified condition must be met and the number of iterations is unknown.

3. How does a loop function with the continue statement?

Use the continue command to go to the next iteration of a loop and skip the remaining statements in the current iteration. It enables you to continue executing a loop while avoiding a portion of its code. Use the continue command to go to the next iteration of a loop and skip the remaining statements in the current iteration. It enables you to continue executing a loop while avoiding a portion of its code.

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow

FREE COURSES

Start Learning For Free

image
Pavan Vadapalli

Author|911 articles published

Pavan Vadapalli is the Director of Engineering , bringing over 18 years of experience in software engineering, technology leadership, and startup innovation. Holding a B.Tech and an MBA from the India....

Your Guide to Java Interviews: Top 50 Q&A

logo image
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

Top Resources

Recommended Programs

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 10 AM to 7 PM

text

Indian Nationals

text

Foreign Nationals