Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

else if

The else if Statement

Utilize the else if statement to introduce a new condition in case the initial condition is false.

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

In the example provided, since the time (22) is greater than 10, the first condition is false. Subsequently, the following condition within the else if statement is also false. Consequently, as both condition1 and condition2 are false, we proceed to the else block and print “Good evening” to the screen.

If the time were 14, our program would output “Good day.”