loading

else if

The else if Statement

If the first condition is false, specify a new condition using the else if statement.

Syntax

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

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

Example explained

Since time (22) in the example above is larger than 10, the first condition is not met. After determining that both conditions 1 and 2 in the otherwise if statement are false, we proceed to the else condition and print “Good evening” on the screen.

That being said, our application would output “Good day” if the time was 14.

Share this Doc

else if

Or copy link

Explore Topic