Home Java If Else Statement

If Else Statement in Java

Beginner ⏱ 6 min read Updated: Jun 2026

The If Else statement in Java is a decision-making statement that allows a program to execute different blocks of code based on a condition. It is used when we want to perform an action only if a specific condition is true otherwise execute another block of code.

Java provides different conditional statements like if, if-else, if-else-if ladder, and nested if to control the flow of a program.

What is If Else Statement in Java?

The if else statement in Java is used to make decisions in a program. It checks a condition and executes the if block when the condition is true. If the condition is false, the else block is executed.

💡
Key Point: The if block executes only when the condition returns true, otherwise the else block runs.

Syntax of If Else Statement

Syntax
if (condition) { 
    // code executes when condition is true
} else{
    // code executes when condition is false
}

How If Else Statement Works?

Step 1

The program first evaluates the given condition.

Step 2

If the condition is true, the statements inside the if block execute.

Step 3

If the condition is false, the statements inside the else block execute.

Example of If Else Statement in Java

Example
public class Main {
    public static void main(String[] args) { 
        int age =  18;
        if (age >= 18) { 
            System.out.println("You can vote");
       }else {
            System.out.println("You cannot vote");
       }
   }
}
Output
You can vote

Types of Conditional Statements in Java

  • if Statement: Executes code only when a condition is true.
  • if-else Statement: Executes one block when true and another block when false.
  • if-else-if Ladder: Used to check multiple conditions.
  • Nested if: An if statement inside another if statement.

Real-Life Example of If Else Statement

A real-life example of an if else statement is checking whether a person is eligible for voting.

Example: If a person's age is 18 or above, allow voting; otherwise, display that the person is not eligible.

Advantages of If Else Statement

Decision Making

Helps programs make decisions based on conditions.

Easy Logic

Makes program logic simple and readable.

Better Control

Controls the execution flow of a Java program.