In this blog post, we will be discussing an important topic in Java programming, namely “Conditional statements (if-else and switch)”.
Conditional statements are used to execute specific blocks of code based on certain conditions. In Java, there are two types of conditional statements: the if-else
statement and the switch
statement.
if-else statement
The if-else
statement in Java is used to execute a block of code if a certain condition is true, and a different block of code if the condition is false. The basic syntax of an if-else
statement is as follows:
if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}
Here is an example of an if-else
statement in Java:
int num = 10;
if (num > 0) {
System.out.println("The number is positive");
} else {
System.out.println("The number is not positive");
}
In this example, the condition num > 0
is checked. If the condition is true, the first block of code is executed, which prints “The number is positive” to the console. If the condition is false, the second block of code is executed, which prints “The number is not positive” to the console.
switch statement
The switch
statement in Java is used to execute different blocks of code based on the value of a variable or expression. The basic syntax of a switch
statement is as follows:
switch (expression) {
case value1:
// code to be executed if the expression matches value1
break;
case value2:
// code to be executed if the expression matches value2
break;
...
default:
// code to be executed if the expression does not match any of the values
break;
}
Here is an example of a switch
statement in Java:
int day = 2;
String dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
break;
}
System.out.println("The day is " + dayName);
In this example, the value of the variable day
is checked using a switch
statement. If day
is equal to 2, the second block of code is executed, which sets the value of dayName
to “Tuesday”. The break
statement is used to exit the switch
statement and prevent the execution of the other blocks of code.
Conclusion
Conditional statements such as if-else
and switch
are an important part of Java programming, allowing you to execute different blocks of code based on certain conditions. By understanding the syntax and usage of these statements, you can create more complex and flexible programs.