Java Else If

In Java, you can use the else if statement to specify a new condition if the first condition is false.



The Else If Statement

Use the else if statement to define a new condition to test when the initial condition in the if statement is not met.

Syntax

if (condition1) {
  // block of code to be executed if condition1 is true
} else if (condition2) {
  // block of code to be executed if condition1 is false and condition2 is true
} else {
  // block of code to be executed if both condition1 and condition2 are false
}




Example: Basic Else If Statement

In the example below, we test if the time is less than 10. If the condition is true, it prints “Good morning.” If the first condition is false, it checks if time is less than 18. If this condition is true, it prints “Good day.” Otherwise, it prints “Good evening.”:

// Example
int time = 22;
if (time < 10) {
  System.out.println("Good morning.");
} else if (time < 18) {
  System.out.println("Good day.");
} else {
  System.out.println("Good evening.");
}
// Outputs "Good evening."

In the example above, time is 22, which is greater than 10, so the first condition time < 10 is false. The next condition time < 18 is also false, so the program moves to the else block and prints “Good evening.” If time were 14, the program would print “Good day.”




Example: Testing Variables with Vehicles

Let’s apply the concept of vehicles to an else if statement example:

// Example
int carSpeed = 120;
int speedLimit = 70;
if (carSpeed <= speedLimit) {
  System.out.println("The car is within the speed limit.");
} else if (carSpeed <= (speedLimit + 20)) {
  System.out.println("The car is slightly over the speed limit.");
} else {
  System.out.println("The car is significantly over the speed limit.");
}
// Outputs "The car is significantly over the speed limit."

In this example, we use two variables, carSpeed and speedLimit, to test different conditions:

  • If carSpeed is within the speed limit, it prints “The car is within the speed limit.”
  • If carSpeed is slightly over the speed limit (by 20 units), it prints “The car is slightly over the speed limit.”
  • If neither condition is true, it prints “The car is significantly over the speed limit.”

Scroll to Top