Java provides control flow statements that allow the execution of specific blocks of code based on certain conditions.
Used when decisions are based on Boolean expressions.
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");
}
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:
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.
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.