Conditional Statements

Conditional statements allow your program to make decisions based on certain conditions. In this tutorial, you’ll learn about if-else statements and switch-case statements.

If-Else Statements

The if-else statement executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed:


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 negative or zero.");
        }
    }
}
      

Switch-Case Statements

The switch-case statement allows you to select one of many code blocks to be executed:


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

Nesting Conditional Statements

You can nest if-else statements inside other if-else statements:


public class Main {
    public static void main(String[] args) {
        int number = 5;
        if (number > 0) {
            if (number % 2 == 0) {
                System.out.println("The number is positive and even.");
            } else {
                System.out.println("The number is positive and odd.");
            }
        } else {
            System.out.println("The number is negative or zero.");
        }
    }
}
      

Continue exploring our beginner tutorials to learn more about Java programming.

Scroll to Top