4.1 Conditional Statements
Conditional statements are used to alter the execution path within a block { } depending on the result of a conditional expression. The two main types are the if statement and the switch statement.
1. if, if-else, and if-else if Statements
This is the most fundamental conditional statement. It executes the statements inside its block only when the conditional expression evaluates to true. When branching based on multiple conditions, you can combine else if and else clauses.
int score = 85;
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) { // If less than 90 and greater than or equal to 80
System.out.println("Grade: B");
} else { // Any other case (less than 80)
System.out.println("Grade: C or below");
}
Nested if Statements
You can write another if statement inside the body block of an if statement. There is no limit to the number of nestings.
int score = 95;
char opt = '0';
// Nested if condition
if (score >= 90) {
if (score >= 98) {
opt = '+';
} else if (score < 94) {
opt = '-';
}
}
System.out.println("Your final grade is A" + opt);
2. switch Statement
When there are very many possible conditions, using a switch statement is much more readable and faster than a multiple if-else statement.
The switch statement jumps directly to the case that matches a specific 'value', and breaks out of the switch block when it encounters a break statement. Unlike if, it checks if the 'value' exactly matches rather than evaluating a logical condition.
int month = 4;
String season = "";
switch (month) {
case 3:
case 4:
case 5:
season = "Spring";
break; // Leaving out break causes fall-through, potentially leading to unintended behavior.
case 6: case 7: case 8: // Placing cases on a single line is also acceptable.
season = "Summer";
break;
default:
// Executed when there are no matching cases.
season = "Other seasons";
}
System.out.println("Month " + month + " is " + season + ".");
Note: Since Java 14, more advanced forms of the switch expression using arrow statements (->) and yield have been added.