Aim : Develop a program to demonstrate use of switch case statement and conditional if

Theory

Decision-Making in Java

Java provides control flow statements that allow the execution of specific blocks of code based on certain conditions.

1. Conditional Statements

Used when decisions are based on Boolean expressions.

  • if: Executes a block only if the condition is true.
  • if-else: Executes one of two blocks based on the condition's truth value.
  • if-else-if ladder: Tests multiple conditions sequentially.

Example:


int number = 5;
if (number > 0) {
    System.out.println("Positive number");
} else if (number < 0) {
    System.out.println("Negative number");
} else {
    System.out.println("Zero");
}
        

2. Switch Case Statement

The switch statement is used to execute one block of code from many based on the value of an expression.

Syntax:


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;
    default:
        System.out.println("Invalid day");
}
        

Important Notes:

  • The expression must evaluate to byte, short, char, int, String, or enum.
  • break prevents fall-through to the next case.
  • default executes if no match is found. It’s optional but recommended.

Use Case: Prefer switch over if-else-if when checking the same variable against multiple constant values for better readability and performance.

Program :

Conclusion: This practical demonstrates how conditional statements like if-else and switch can control program flow depending on user input, which is essential for dynamic and responsive Java applications.