What are the Conditional Statements in Java?
Conditional statements are an essential part of programming, as they allow developers to control the flow of execution based on certain conditions. In Java, conditional statements are used to make decisions and execute different blocks of code depending on the evaluation of a given condition. This article will explore the different types of conditional statements available in Java, their syntax, and practical examples.
1. If-Else Statement
The most basic conditional statement in Java is the if-else statement. It allows you to execute a block of code if a specified condition is true, and another block of code if the condition is false.
Syntax:
“`java
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}
“`
Example:
“`java
int number = 10;
if (number > 5) {
System.out.println(“The number is greater than 5.”);
} else {
System.out.println(“The number is not greater than 5.”);
}
“`
2. If-Else If-Else Statement
The if-else if-else statement is used when you need to check multiple conditions. It allows you to evaluate multiple conditions sequentially and execute the block of code that corresponds to the first true condition.
Syntax:
“`java
if (condition1) {
// Code to be executed if condition1 is true
} else if (condition2) {
// Code to be executed if condition1 is false and condition2 is true
} else {
// Code to be executed if both condition1 and condition2 are false
}
“`
Example:
“`java
int number = 7;
if (number > 10) {
System.out.println(“The number is greater than 10.”);
} else if (number > 5) {
System.out.println(“The number is greater than 5.”);
} else {
System.out.println(“The number is not greater than 5.”);
}
“`
3. Switch-Case Statement
The switch-case statement is another way to control the flow of execution based on a given value. It allows you to compare the value of a variable against multiple possible values (case labels) and execute the block of code associated with the matching case.
Syntax:
“`java
switch (expression) {
case value1:
// Code to be executed if expression matches value1
break;
case value2:
// Code to be executed if expression matches value2
break;
// …
default:
// Code to be executed if none of the cases match the expression
}
“`
Example:
“`java
int day = 3;
switch (day) {
case 1:
System.out.println(“It’s Monday.”);
break;
case 2:
System.out.println(“It’s Tuesday.”);
break;
case 3:
System.out.println(“It’s Wednesday.”);
break;
default:
System.out.println(“It’s not a weekday.”);
}
“`
In conclusion, conditional statements in Java are a powerful tool for controlling the flow of execution based on specific conditions. By using if-else, if-else if-else, and switch-case statements, you can create more flexible and dynamic programs. Understanding and utilizing these conditional statements will greatly enhance your Java programming skills.