"Seleniums.com is where I keep my notes organized."

Conditional Statements: if, else, else if, switch

Estimated reading: 4 minutes 18 views

Conditional statements are an essential feature of Java programming, enabling programs to make decisions based on conditions. They control the flow of execution by allowing specific blocks of code to run only when certain conditions are true. The primary conditional statements in Java are if, else, and else if.

What Are Conditional Statements?

Conditional statements evaluate boolean expressions (true or false) and execute code based on these evaluations. They are crucial for decision-making in programming, providing dynamic control over the program’s behavior.

1. if Statement

The if statement checks a condition and executes the associated block of code if the condition evaluates to true. If the condition is false, the block is skipped.

Syntax:

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

				
			

Example:

				
					int age = 20;
if (age >= 18) {
    System.out.println("You are eligible to vote.");
}

				
			

Here, the program checks whether age is greater than or equal to 18. If the condition evaluates to true, the message is printed.

2. else Statement

The else statement provides an alternative block of code to execute if the if condition evaluates to false. This ensures that one of two mutually exclusive blocks of code will run.

Syntax:

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

				
			

Example

				
					int age = 16;
if (age >= 18) {
    System.out.println("You are eligible to vote.");
} else {
    System.out.println("You are not eligible to vote.");
}

				
			

In this case, since age is 16 (less than 18), the else block executes, printing the second message.

3. else if Statement

The else if statement allows you to test multiple conditions in sequence. It executes the first block of code where the condition evaluates to true. If no conditions are true, the program can fall back to an optional else block.

Syntax:

				
					if (condition1) {
    // Code to execute if condition1 is true
} else if (condition2) {
    // Code to execute if condition2 is true
} else {
    // Code to execute if none of the conditions are true
}

				
			

Example

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

				
			

In this example, the program evaluates the conditions sequentially. Since marks is 85, the second condition (marks >= 75) is true, so the corresponding block executes.

4. switch Statement

The switch statement is an alternative to using multiple if-else if statements. It evaluates a single expression and matches its result against multiple case values. When a match is found, the corresponding block of code executes.

Syntax:

				
					switch (expression) {
    case value1:
        // Code to execute if expression == value1
        break;
    case value2:
        // Code to execute if expression == value2
        break;
    // Additional cases...
    default:
        // Code to execute if no cases match
}

				
			
  • Expression: A variable or value to evaluate.
  • case: Specifies a possible value for the expression.
  • break: Exits the switch block after executing the case code. Omitting it allows “fall-through” to the next case.
  • default: Executes if none of the cases match.

Example:

				
					int day = 3;

switch (day) {
    case 1:
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    case 3:
        System.out.println("Wednesday");
        break;
    case 4:
        System.out.println("Thursday");
        break;
    case 5:
        System.out.println("Friday");
        break;
    default:
        System.out.println("Weekend");
}

				
			

In this example, the value of day is 3, so the output will be: Wednesday

Combining Conditional Statements

You can combine if-else and switch statements for more complex decision-making. Logical operators like && (AND) and || (OR) are often used in conditions for if statements.

Example Program

				
					public class ConditionalStatementsExample {
    public static void main(String[] args) {
        int score = 85;

        // Using if-else if-else
        if (score >= 90) {
            System.out.println("Grade: A");
        } else if (score >= 75) {
            System.out.println("Grade: B");
        } else if (score >= 50) {
            System.out.println("Grade: C");
        } else {
            System.out.println("Grade: F");
        }

        int month = 8;

        // Using switch statement
        switch (month) {
            case 1:
                System.out.println("January");
                break;
            case 2:
                System.out.println("February");
                break;
            case 8:
                System.out.println("August");
                break;
            default:
                System.out.println("Other Month");
        }
    }
}

				
			

Output:

				
					Grade: B
August
				
			

Key Differences Between if-else and switch

Featureif-elseswitch
Use CaseUsed for evaluating conditions or ranges.Used for evaluating discrete values.
Data TypesSupports boolean, integers, and objects.Supports integers, enums, strings, etc.
ReadabilityCan get complex with multiple conditions.Cleaner for matching specific values.
Fall-throughDoes not allow fall-through between blocks.Allows fall-through unless break used.

Conditional statements (if, else, else if, and switch) are powerful tools that enable flexible and dynamic control over a program’s flow. By understanding their use and differences, you can write more effective and readable Java programs.

Leave a Comment

Share this Doc

Conditional Statements: if, else, else if, switch

Or copy link

CONTENTS