If-else

In Java, if-else is a control flow statement used to make decisions in a program based on a given condition. It allows you to execute one block of code if a condition is true and another block of code if the condition is false.

  • It allows your program to branch based on different outcomes.
  • It is one of the building blocks for decision-making in code, such as checking if a user is logged in, if a number is positive, etc.

Syntax

Types of If-Else Statements

  • if statement: Executes a block if the condition is true.

  • if-else Statement: Executes one block if the condition is true, otherwise runs the else block.

  • Shorter if-else: The ternary operator is a compact way to write an if-else statement.

  • if-else-if Ladder: Used when multiple conditions need to be checked.

  • Nested if-else: An if-else inside another if-else for complex conditions.