Example
Utilize the “else” statement to designate a code block for execution when the condition is false:
int time = 20;
if (time < 18) {
System.out .println("Good day.");
} else {
System.out .println("Good evening.");
}
// Outputs "Good evening."
|
Definition and Usage
The “else” statement in Java defines a block of code to execute when a condition within an “if” statement evaluates to false.
In Java, the subsequent conditional statements are available:
- Employ “if” to define a code block for execution when a specific condition is true.
- Utilize “else” to designate a code block for execution when the same condition is false.
- Incorporate “else if” to introduce a new condition to test if the initial one fails.
- Implement “switch” to specify multiple alternative code blocks for execution.
More Examples
Example
Utilize the “else if” statement to introduce an additional condition when the initial one evaluates to false.
int time = 22;
if (time < 10) {
System.out .println("Good morning.");
} else if (time < 20) {
System.out .println("Good day.");
} else {
System.out .println("Good evening.");
}
// Outputs "Good evening."
|