Java Else

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.

Tutorials dojo strip



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

JAVA




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.”:

JAVA

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:

HTML

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.”

Tutorials dojo strip