In Java, you can use the else
statement to define a block of code to be executed if the condition in the if
statement is false.
The Else Statement
Use the else
statement to specify a block of code that runs when the condition in the if
statement is not met.
Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Example: Basic Else Statement
In the example below, we test if the time is less than 18. If the condition is true, it prints “Good day.” Otherwise, it prints “Good evening.”:
// Example
int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
// Outputs "Good evening."
In the example above, time
is 20, which is greater than 18, so the condition time < 18
is false. Therefore, the program moves to the else
block and prints “Good evening.” If time
were less than 18, the program would print “Good day.”
Example: Testing Variables with Vehicles
Let’s apply the concept of vehicles to an else
statement example:
// Example
int carSpeed = 80;
int speedLimit = 70;
if (carSpeed <= speedLimit) {
System.out.println("The car is within the speed limit.");
} else {
System.out.println("The car is over the speed limit.");
}
// Outputs "The car is over the speed limit."
In this example, we use two variables, carSpeed
and speedLimit
, to test whether the car’s speed is within the limit (using the <=
operator). Since carSpeed
is 80 and speedLimit
is 70, the condition is false, and the program prints “The car is over the speed limit.” If carSpeed
were less than or equal to speedLimit
, the program would print “The car is within the speed limit.”