• Home
  • Blog
  • General
  • Control Statements in Java: Types, Flowcharts, and Code Examples

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

By Rohan Vats

Updated on Jun 25, 2026 | 10 min read | 12.59K+ views

Share:

Control statements in Java control how a program executes by making decisions, repeating tasks, or changing the normal flow of execution. Statements such as if, if-else, switch, for, while, do-while, break, continue, and return help you build applications that respond to different conditions and user inputs.

This guide explains the different types of control statements in Java with flowcharts, syntax, code examples, and practical use cases. You'll also learn when to use each statement and how they work together to write clean and reliable Java programs.

Build a strong foundation in Python, analytics, and AI with upGrad's Data Science Course. Learn through hands-on projects and practical applications to prepare for data-driven and software development careers.

Control Statements in Java at a Glance

Java provides different control statements to handle decisions, loops, and changes in program execution. The table below gives a quick overview of each control statement, its purpose, and where you would typically use it.

Control Statement Type Purpose Common Use Case
Sequence Flow Control Executes statements one after another Variable initialization, calculations
if Selection Executes code when a condition is true Login validation, eligibility checks
if-else Selection Chooses between two execution paths Pass or fail decisions
switch Selection Selects one block from multiple options Menu-driven programs, command selection
for Iteration Repeats code for a fixed number of iterations Array traversal, counting loops
while Iteration Repeats code while a condition remains true Reading user input, waiting for events
do-while Iteration Runs the loop once before checking the condition Menu-based applications, input validation
break Branching Exits a loop or switch statement immediately Search operations, switch cases
continue Branching Skips the current loop iteration Filtering values, skipping invalid data
return Branching Exits a method and optionally returns a value Returning results from methods

What Are Control Statements in Java? Types and Examples

Control statements in Java are essential constructs that manage the flow of program execution by directing the order in which code blocks run. They enable conditional branching, allowing the program to choose different paths based on evaluated expressions, and facilitate repetitive execution through loops.

By default, Java executes code line by line from top to bottom, left to right. However, control statements in Java let you change this flow by deciding whether certain blocks of code should run based on conditions or loops.

For example, the if statement is a decision-making control structure that executes code only when a specified condition is true. Since Java is case-sensitive, keywords like if must be written in lowercase. Inside the if block, you can perform actions such as printing variable values to monitor the program’s behavior.

Now that you have a good understanding of control statements in Java, let’s look at the different types of control statements in Java.

1. Sequence Structure

This structure refers to the sequential execution of statements one after the other, as specified in the code. This is the default structure built into Java wherein the statements are executed one after the other from beginning to end unless instructed otherwise.

For example, a simple program that prints "Hello" followed by "World" will execute in sequence, printing "Hello" first and "World" second: 

System.out.println("Hello");
System.out.println("World");

Output: 

Hello
World

In real-life applications, the sequence structure is often used for straightforward tasks that don’t require decision-making or repetition, like initialization steps, simple calculations, or logging information. 

For example, when initializing variables or setting up initial configurations in your program, the sequence structure ensures that the steps happen in the correct order.

Also Read: Is Java Easy to Learn? Key Factors to Consider

Having trouble getting a solid foundation in Java? Enroll in upGrad’s free Core Java Basics course and start building strong coding skills today. Learn variables, data types, loops, and OOP principles from the ground up!

2. Selection Structure

This structure will let us choose a path based on a given condition. Java has three types of Selection statements, namely, if statement, if-else-statement, and switch statement. Selection statements are also called as decision-making statements. If and switch statements allow you to control the program execution flow based on the condition at runtime.

  • If Statement

This statement allows the program to start, reach a decision based on the set condition. This means a code can or cannot be executed.

Example:

if (x < 20) {
    System.out.println("Hello Universe!");
}

Example output:

Hello Universe!

If x = 25, there will be no output.

  • If-else Statement

The program starts and reads the decision based on the set condition and continues to do one thing or another and concludes.

Example:

if (x < 20) {
    System.out.println("Hello Universe!");
} else {
    System.out.println("Hello folks!");
}

Example outputs:

For x = 15:
Hello Universe!

For x = 25:
Hello folks!

  • Switch or Break Statement

A switch statement allows the program to select one of many possible execution paths based on the value of a variable. Each case corresponds to a specific value, and the program executes the code under the matching case until it encounters a break statement, which exits the switch. If no case matches, the default case is executed.
Example:

String dayName;
int dayNumber = 2;  // Example input

switch (dayNumber) {
    case 1:
        dayName = "Monday";
        break;
    case 2:
        dayName = "Tuesday";
        break;
    case 3:
        dayName = "Wednesday";
        break;
    default:
        dayName = "Any other Day";
        break;
}

System.out.println(dayName);

Example output:

For dayNumber = 2, the output will be:
Tuesday

If dayNumber = 5, the output will be:
Any other Day

If you're finding it tough to break down complex problems efficiently, check out upGrad’s Data Structures & Algorithms free course to strengthen your foundation and start solving challenges with ease. Start today!

Also Read: Learn 50 Java Projects With Source Code (2025 Edition)

3. Repetition Structure

The Repetition Structure in Java allows you to execute code statements multiple times, or even zero times, depending on a specified condition. This structure is fundamental for performing repetitive tasks within a program, such as iterating through a list of items or executing code until a certain condition is met.

In Java, there are three main types of looping statements that enable repetition:

  • For Loop
  • While Loop
  • Do-While Loop

These loops allow you to repeat one or more statements a set number of times, or as long as a specific condition remains true. Each loop follows a four-part structure:

  • Initialization: Setting up the loop control variable (e.g., starting a counter).
  • Condition Checking: Evaluating a condition to decide whether to continue the loop or exit.
  • Execution: Executing the code block inside the loop.
  • Increment/Decrement: Modifying the loop control variable, usually after each iteration.

For Loop

This statement is used when the number of iterations is known before entering the loop. This loop is used to evaluate the initial value statements to the final value with a given increment/decrement.

For Loop flow:

  1. Initialization: Set the starting value for the loop control variable.
  2. Test Condition: Check if the condition is true. If true, execute the loop body; if false, exit the loop.
  3. Loop Body: Execute the code inside the loop.
  4. Increment/Decrement: Modify the loop control variable (e.g., i++).
  5. Repeat: Return to the test condition. Repeat steps 2-4 until the condition is false.

Example: Counting from 1 to 20

for (int m = 1; m <= 20; m = m + 1) {
    System.out.println(m);
}

How it works: Starts with m = 1 and prints the value of m. Then it increments m by 1 each time, repeating until m is greater than 20.

Output:

1
2
3
...
19
20

While Loop

A while loop repeatedly executes a block of code as long as the given condition remains true. It starts with an initial value and continues looping, incrementing or decrementing the control variable until the condition becomes false.

While Loop flow:

  1. Test Condition: Check if the condition is true. If true, execute the loop body; if false, exit the loop.
  2. Loop Body: Execute the code inside the loop.
  3. Increment/Decrement: Modify the loop control variable (e.g., i++).
  4. Repeat: Return to the test condition. Repeat steps 1-3 until the condition is false.

Example : Print values from 1 to 10

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

Expected Output:

1
2
3
4
5
6
7
8
9
10

do while loop

A do-while loop executes the block of code at least once before checking the condition. It continues to repeat the loop as long as the condition remains true. This is useful when you want the loop body to run before any condition is tested.

Do-While Loop flow:

  1. Loop Body: Execute the code inside the loop at least once.
  2. Test Condition: After the loop body executes, check if the condition is true. If true, repeat the loop; if false, exit the loop.
  3. Increment/Decrement: Modify the loop control variable (e.g., i++).
  4. Repeat: Return to the test condition. Repeat steps 2-3 until the condition is false.

Example : Calculating the sum of numbers from 1 to 10

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

        do {
            sum = sum + i;
            i++;
        } while (i <= 10);

        System.out.println("\nThe sum of 1 to 10 is: " + sum);
    }
}

Expected Output:

The sum of 1 to 10 is: 55

One of the major differences between the while loop and the do-while loop is that in a do-while loop, you will be executing the body of the loop initially and then check the condition. the do-while loop executes the block of the statement even when the condition fails, and it executes one time.

After understanding selection and repetition, branching statements in Java provide further control over program flow by allowing you to break, continue, or return.

Build strong programming, AI, and leadership skills with these upGrad programs to prepare for advanced software development and technology leadership roles.

What are Branching Statements?

When working with loops in Java, there are situations where you may want to skip certain iterations or exit the loop immediately. This is where branching statements like break, continue, and return come into play. 

They control the flow by either terminating loops or skipping parts of them, allowing more precise execution control.

  • Break: Immediately exits the nearest enclosing loop or switch statement, transferring control to the code following the loop or switch block. It effectively stops the loop before the normal condition fails.
  • Continue: Skips the remaining code in the current iteration and moves to the next iteration of the loop. For do-while loops, control moves to the test condition; for other loops, it moves to the update expression.
  • Return: Exits from the current method, optionally returning a value. It stops all further execution within the method.

1. Break Statements

The break statement in Java has two forms: unlabeled and labeled. The unlabeled break is commonly used to exit loops (while, do-while) or switch blocks immediately. Without a break inside a switch case, execution continues (“falls through”) to the next case, which can lead to unintended results.

The switch statement works like an if-else, selecting code to execute based on the input value.

  • Start: The loop or switch statement begins execution.
  • Condition Met? Is the condition for the break statement true (e.g., a specific value is reached or a condition is satisfied)?
    • Yes: Exit the loop or switch immediately, skipping the remaining iterations or cases.
    • No: Continue the loop or switch until the condition is met.
  • End: The program continues execution after the loop or switch statement.

For instance, passing a marks integer to switch will print the matched case message, but if no break is present, it continues to the next case and eventually the default.

Example:

public class BreakDemo {

    public static void main(String[] args) {

        String str1 = args[0];

        int marks = Integer.parseInt(str1);

        switch(marks) {
            case 95:
                System.out.println("Your marks: " + marks + " and rank is A");
                break;

            case 80:
                System.out.println("Your marks: " + marks + " and rank is B");
                break;

            case 70:
                System.out.println("Your marks: " + marks + " and rank is C");
                break;

            default:
                System.out.println("Your marks: " + marks + " and rank is FAIL");
                break;
        }
    }
}

Example Outputs:

  • If you run:

    java BreakDemo 95

Output:

Your marks: 95 and rank is A

  • If you run:

    java BreakDemo 80

Output:

Your marks: 80 and rank is

  • If you run:

    java BreakDemo 65

Output:

Your marks: 65 and rank is FAIL

2. Continue Statement

The continue statement is used inside loops to skip the current iteration and proceed to the next one. Instead of exiting the loop entirely (like with break), continue allows you to skip the remaining code in the current iteration and go back to the loop’s condition check or increment/decrement step.

  • Start: The loop begins execution.
  • Condition Met? Is the condition for the continue statement true (e.g., a specific value is reached or a condition is satisfied)?
    • Yes: Skip the remaining code in the current iteration and proceed to the next iteration.
    • No: Continue executing the loop as usual.
  • Repeat: Move to the next iteration or condition check, repeating steps until the loop exits.
  • End: The loop finishes execution once the condition becomes false or the loop ends naturally.

This example is to print odd numbers. The continue statement skips the iteration of for, while loops.

Example:

public class ContinueDemo {

    public static void main(String[] args) {

        for (int i = 1; i <= 10; i++) {

            if (i % 2 == 0) continue;

            System.out.println("Odd number " + i);
        }
    }
}

Output:

Odd number 1
Odd number 3
Odd number 5
Odd number 7
Odd number 9

You can also build relevant Java skills for advanced web development with upGrad’s Master of Design in User Experience. You’ll learn to create user-centered designs that are innovative, efficient, and aligned with current industry trends, ensuring that your designs are not only functional but also impactful.

Also Read: Careers in Java: How to Make a Successful Career in Java in 2025

3. Return Statements

The return statement is used to return the value from a method explicitly. The called class will process and transfer the control back to the caller of the method. The data type of the return value must match the type of methods declared return value. If a method is declared as void, it does not return a value.

  • Start: The method begins execution.
  • Is Return Statement Encountered?
    • Yes: Exit the method immediately, passing control back to the calling method. If the method has a return value, return it.
    • No: Continue executing the method.
  • Return Value Present?
    • Yes: Return the specified value (if the method is not void).
    • No: Simply exit (for void methods). 
  • End: The method finishes, and the control moves to the next statement in the calling method.

Example:

public class RectangleTest {
    public static void main(String[] args) {
        Rectangle rect = new Rectangle();
        rect.setDim(10, 5);
        int area = rect.getArea();
        System.out.println("Area of rectangle: " + area);
    }
}

class Rectangle {
    int length;
    int breadth;

    void setDim(int le, int br) {
        length = le;
        breadth = br;
    }

    int getArea() {
        return length * breadth;
    }
}

Expected Output:

Area of rectangle: 50

Explanation: Length = 10, Breadth = 5, so Area = 10 * 5 = 50.
Connecting the Control Structure and connect the statements control structures in two ways, one is by stacking, and the other is by nesting.
Control Statement Stacking

The entry point of one activity diagram can be connected to the exit point of another. For example, a sequence statement and a selection statement can be combined through stacking.

Focus on optimizing your code using efficient loop structures and control flows. To take it further, dive into design patterns and multithreading for building more scalable and efficient applications. 

How Can upGrad Help You Learn Java Programming?

Control statements in Java, like if, switch, and for loops are essential for building dynamic applications, such as creating an interactive login system or processing user inputs in a real-time chat application. However, you might face challenges in handling more complex decision trees or optimizing large-scale applications.

To improve, focus on mastering nested loops, branching logic, and refining control statements in Java. For further growth, upGrad’s Java courses offer hands-on experience and mentorship to tackle advanced challenges.

In addition to the courses mentioned above, here are some more free courses that can help you elevate your skills: 

Curious which courses can help you advance in Java development? upGrad’s personalized career guidance can help you explore the right learning path based on your goals. You can also visit your nearest upGrad center and start hands-on training today!  

Frequently Asked Question (FAQs)

1. What are control statements in Java?

Control statements in Java determine how a program executes by controlling decisions, loops, and branching. They help you decide which code should run, how many times it should repeat, and when execution should stop or move to another section. These statements form the foundation of Java programming.

2. What are the four types of control statements?

Java control flow is commonly grouped into four categories: sequence, selection, iteration (repetition), and branching. Sequence executes statements in order, selection makes decisions, iteration repeats code, and branching changes the normal execution flow using statements such as break, continue, and return.

3. What are the 4 types of if statements in Java?

Java provides four common forms of the if statement: simple if, if-else, if-else-if ladder, and nested if. Each type handles different decision-making scenarios, from checking a single condition to evaluating multiple conditions or placing one if statement inside another.

4. What are the 4 types of containers in Java?

The four commonly discussed container categories in Java are List, Set, Queue, and Map. These belong to the Java Collections Framework and are different from control flow structures. Each stores and manages data differently depending on your application's requirements.

5. When should you use switch instead of if-else?

Control statements in Java include both switch and if-else, but each suits different situations. Use switch when comparing one variable against multiple fixed values. Choose if-else when evaluating ranges, logical operators, or multiple independent conditions that require greater flexibility.

6. Which loop is best for beginners in Java?

The for loop is usually the easiest choice because it combines initialization, condition checking, and incrementing in one statement. Once you understand for loops, learning while and do-while loops becomes much easier since they follow similar execution principles with different use cases.

7. What is the difference between while and do-while loops?

A while loop checks the condition before executing its code block, so it may never run if the condition is false. A do-while loop executes the code once before checking the condition, making it useful for menus, user input, and validation tasks.

8. How do break and continue statements work in Java?

Control statements in Java include break and continue for managing loop execution. The break statement exits the nearest loop or switch immediately, while continue skips the remaining code in the current iteration and moves directly to the next iteration of the loop.

9. Can return be used inside loops?

Yes. A return statement can appear inside a loop if it is placed within a method. Once executed, it immediately exits the method instead of just leaving the loop. This approach is useful when the required result has already been found.

10. What are common mistakes when using control statements in Java?

When learning control statements in Java, beginners often create infinite loops, forget break statements inside switch blocks, write incorrect loop conditions, or overuse nested if statements. Testing your logic with different inputs and tracing execution step by step helps prevent these errors.

11. How can I master Java control statements quickly?

Practice writing small Java programs that use decision-making, loops, and branching statements together. Build projects such as calculators, ATM systems, grading applications, and menu-driven programs. Solving coding problems regularly will help you understand program flow and improve your coding confidence.

Rohan Vats

416 articles published

Rohan Vats is a Senior Engineering Manager with over a decade of experience in building scalable frontend architectures and leading high-performing engineering teams. Holding a B.Tech in Computer Scie...