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

Example

Utilize the “else” statement to designate a code block for execution when the condition is false:

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

Definition and Usage

The “else” statement in Java defines a block of code to execute when a condition within an “if” statement evaluates to false.

In Java, the subsequent conditional statements are available:

  • Employ “if” to define a code block for execution when a specific condition is true.
  • Utilize “else” to designate a code block for execution when the same condition is false.
  • Incorporate “else if” to introduce a new condition to test if the initial one fails.
  • Implement “switch” to specify multiple alternative code blocks for execution.

More Examples

Example

Utilize the “else if” statement to introduce an additional condition when the initial one evaluates to false.

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