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
1 2 3 4 5 |
if (condition) { // Executes if condition is true } else { // Executes if condition is false } |
Types of If-Else Statements
- if statement: Executes a block if the condition is
true
.
1 2 3 4 |
int num = 10; if (num > 0) { System.out.println("Positive number"); } |
- if-else Statement: Executes one block if the condition is
true
, otherwise runs theelse
block.
1 2 3 4 5 6 |
int num = -5; if (num > 0) { System.out.println("Positive number"); } else { System.out.println("Negative number"); } |
- Shorter if-else: The ternary operator is a compact way to write an
if-else
statement.
1 2 3 |
int num = 10; String result = (num > 0) ? "Positive" : "Negative"; System.out.println(result); |
- if-else-if Ladder: Used when multiple conditions need to be checked.
1 2 3 4 5 6 7 8 |
int marks = 85; if (marks >= 90) { System.out.println("Grade: A"); } else if (marks >= 75) { System.out.println("Grade: B"); } else { System.out.println("Grade: C"); } |
- Nested if-else: An if-else inside another if-else for complex conditions.
1 2 3 4 5 6 7 8 9 10 11 |
int age = 20; int weight = 55; if (age >= 18) { if (weight > 50) { System.out.println("Eligible to donate blood"); } else { System.out.println("Not eligible due to weight"); } } else { System.out.println("Not eligible due to age"); } |