Control Flow in Java: If, Else, and Switch Statements
Introduction to Control Flow
Control flow statements in Java allow you to control the flow of your program's execution. They enable you to make
decisions and execute code conditionally. The primary control flow structures include if,
else, and switch statements.
If Statement
The if
statement is used to make decisions in your code based on a condition. If the condition is
true, the code inside the if
block is executed. Here's an example:
int age = 25;
if (age >= 18) {
System.out.println("You are an adult.");
}
Else Statement
You can extend the if
statement with an else
block to execute code when the condition is
false. For example:
int age = 15;
if (age >= 18) {
System.out.println("You are an adult.");
} else {
System.out.println("You are not an adult.");
}
Switch Statement
The switch
statement is used when you have multiple conditions to check. It compares an expression
to various case values and executes the code block associated with the matching case. Here's an example:
int day = 2;
String dayName;
switch (day) {
case 1:
dayName = "Sunday";
break;
case 2:
dayName = "Monday";
break;
// Add more cases for the other days...
default:
dayName = "Invalid day";
}
Conclusion
Control flow statements are essential for decision-making in your Java programs. They allow you to execute code
based on conditions and make your programs more flexible and interactive. As you continue your Java journey,
mastering control flow is a fundamental skill.