Control Statements in Java: if-else, switch, and Loops Explained

7/19/2025

Diagram of Control Statements in Java: if-else.

Go Back
Diagram of Control Statements in Java: if-else.

Control Statements in Java: if-else, switch, and Loops Explained

Control Statements in Java

Control statements allow you to control the flow of execution in a Java program. They include conditional statements like if-else and switch, as well as looping structures like for, while, and do-while.

Let’s explore how they work with examples.


1. if-else Statement

The if-else statement is used to execute code blocks based on conditions.

Syntax:

if (condition) {
    // code if true
} else {
    // code if false
}

Example:

int number = 10;
if (number > 0) {
    System.out.println("Positive number");
} else {
    System.out.println("Non-positive number");
}

 2. if-else if Ladder

Used for checking multiple conditions.

Example:

int marks = 85;
if (marks >= 90) {
    System.out.println("Grade A");
} else if (marks >= 75) {
    System.out.println("Grade B");
} else {
    System.out.println("Grade C");
}

3. switch Statement

The switch statement is an alternative to multiple if-else conditions.

Syntax:

switch (variable) {
    case value1:
        // code
        break;
    case value2:
        // code
        break;
    default:
        // default code
}

Example:

int day = 2;
switch (day) {
    case 1:
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    default:
        System.out.println("Other Day");
}

🔄 4. Loops in Java

Loops execute a block of code multiple times.

A. for Loop

Used when the number of iterations is known.

for (int i = 0; i < 5; i++) {
    System.out.println(i);
}

B. while Loop

Used when the condition is checked before executing the loop.

int i = 0;
while (i < 5) {
    System.out.println(i);
    i++;
}

C. do-while Loop

Executes the block at least once before checking the condition.

int i = 0;
do {
    System.out.println(i);
    i++;
} while (i < 5);

When to Use Which Statement?

  • Use if-else for complex conditions

  • Use switch for multiple fixed values

  • Use for when you know how many times to loop

  • Use while or do-while when the number of iterations is not known in advance


Conclusion

Control statements are essential for building logic in Java programs. With if-else, switch, and loops, you can handle decision-making and repetitive tasks efficiently.

Practice these examples to gain confidence and build more dynamic Java applications.


Want to master Java? Follow us for more tutorials on syntax, OOP, error handling, and more!

Table of content