0
Explore
0

if-else statement in Java- A Detailed Overview with Example

Updated on July 27, 2025

Conditional statements are the heart of decision-making in any programming language, and Java is no exception. Among these, the if-else statement is one of the most fundamental and widely used control structures. It allows your Java program to execute different blocks of code based on whether a certain condition is true or false.

Imagine you’re writing a program that checks whether someone is eligible to vote based on their age, or whether a number is positive or negative. These real-world decisions require conditions, and that’s where if-else shines.

In this tutorial, we’ll explore how if-else works in Java, its syntax, types (like if, if-else, else-if ladder, and nested if), along with examples to help you understand it clearly. Whether you’re a beginner learning Java or brushing up on the basics, this guide will make conditional logic easy to grasp.

Why Do We Need if-else?

Imagine you’re building a robot. You want it to say:

  • “Good morning!” if it’s before 12 PM.
  • “Good evening!” if it’s after 6 PM.
  • Otherwise, “Good afternoon!”

How will your program decide what to say?

This is where if-else comes into the picture!

It helps your program make decisions based on conditions.

What is if-else in Java?

In Java, if-else is a conditional control statement that allows your program to execute different blocks of code based on boolean conditions (true or false).

Syntax of if-else

if (condition) {
    // Code to run if condition is true
} else {
    // Code to run if condition is false
}

Example of if-else

int age = 20;
if (age >= 18) {
    System.out.println("You are eligible to vote.");
} else {
    System.out.println("You are not eligible to vote.");
}

Output:

You are eligible to vote.

Step-by-Step Breakdown of above example

Variable Declaration:

int age = 20;

Here, we declare an integer variable named age and assign it the value 20. This means the person is 20 years old.

Condition Check:

if (age >= 18)

The condition age >= 18 checks whether the value of age is greater than or equal to 18.

  • Since 20 is greater than 18, the condition is true.

If Block Execution:

System.out.println("You are eligible to vote.");

Because the condition is true, this line inside the if block runs, and the message is printed.

Else Block Skipped:

System.out.println("You are not eligible to vote.");

Since the condition is already true and the if block executed, this else block is skipped.

How Does if-else Work?

Let’s break it down:

1 .The condition is evaluated:

The condition written inside the parentheses of the if() statement is checked. It must return a boolean value either true or false.

2. If the condition is true:

The code block inside the if statement runs. Java executes all the lines of code inside that block and skips the else part.

3. If the condition is false:

The else block runs instead. Java completely ignores the if block and executes only the code inside the else.

Flowchart for if-else

        +---------------+
        |  Check Condition |
        +-------+-------+
                |
         +------v------+
         |   TRUE       |---------------> Run `if` block
         +--------------+
         |   FALSE      |---------------> Run `else` block
         +--------------+

if-else-if Ladder in Java

What if we have multiple choices?

The if-else-if ladder is used when you want to check multiple conditions one by one.
Java will check each condition from top to bottom.

  • As soon as it finds a true condition, it runs that block of code and skips the rest.
  • If none of the conditions are true, the else block runs.

Use it when you have more than two choices.

if-else-if Ladder example

Use the if-else-if ladder:

if (marks >= 90) {
    System.out.println("Grade: A+");
} else if (marks >= 80) {
    System.out.println("Grade: A");
} else if (marks >= 70) {
    System.out.println("Grade: B");
} else {
    System.out.println("Grade: C or below");
}

Java checks conditions one by one, from top to bottom, and executes the first true block.

Step-by-Step Explanation

Let’s say you have a variable marks that stores the score of a student.

The program checks the value of marks and prints the grade based on these rules:

First Condition:

if (marks >= 90)
  • If the marks are 90 or more, it prints Grade: A+.
  • Once this runs, the rest of the code is skipped.

Second Condition:

else if (marks >= 80)
  • If the first condition is false, this checks if marks are 80 or more.
  • If true, it prints Grade: A.

Third Condition:

else if (marks >= 70)
  • If the above two conditions are false, this checks if marks are 70 or more.
  • If true, it prints Grade: B.

Else Block (Default Case):

else {
    System.out.println("Grade: C or below");
}
  • If none of the above conditions are true (i.e., marks are less than 70), this block runs and prints Grade: C or below.

Example of if-else-if ladder:

If marks = 85, then:

  • marks >= 90 → false
  • marks >= 80true
    ✅ So it prints: Grade: A

Important Points to Remember about if-else

ConceptExplanation
ConditionMust return a boolean (true or false)
Curly BracesRequired if more than one statement
Only one if runsIn a ladder, only the first matching condition’s block runs
Nested ifYou can put if inside another if

Nested if in Java

A nested if in Java means using one if statement inside another if. It lets you check one condition only if another condition is true.

✅ Use it when you want to check a condition within another condition.

Example of Nested if (Check Voting Eligibility Using Nested if in Java)

int age = 20;
boolean hasVoterID = true;

if (age >= 18) {
    if (hasVoterID) {
        System.out.println("You can vote.");
    } else {
        System.out.println("You need a Voter ID to vote.");
    }
} else {
    System.out.println("You are underage.");
}

Output (for age = 20 and hasVoterID = true):

You can vote.

Step-by-Step Explanation

1. Variable Declarations:

  • age = 20 → The person is 20 years old.
  • hasVoterID = true → The person has a voter ID card.

2. First if Condition (Outer if):

if (age >= 18)
  • This checks whether the person is 18 or older.
  • Since the age is 20, the condition is true, so it goes inside this block.

3. Second if Condition (Nested if):

if (hasVoterID)
  • Now it checks if the person has a voter ID.
  • Since hasVoterID is true, it prints:
    • You can vote.

4. What if Conditions Were Different?

If age = 16, it would skip the voter ID check and print:

You are underage.

If age = 20 and hasVoterID = false, it would print:

You need a Voter ID to vote.

Practice Examples

Example 1: Find Greatest of Two Numbers

int a = 10, b = 20;

if (a > b) {
    System.out.println("A is greater");
} else {
    System.out.println("B is greater");
}

Example 2: Check Leap Year

int year = 2024;

if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
    System.out.println("Leap Year");
} else {
    System.out.println("Not a Leap Year");
}

Common Mistakes to Avoid

❌ Mistake✅ Correct Way
if x > 10if (x > 10) ← Always use parentheses
if x = 10if (x == 10) ← Use == for comparison
Forgetting bracesUse {} if more than one statement

Practice Set for Students

  1. Write a program to check if a number is positive, negative, or zero.
  2. Create a grade calculator using if-else-if ladder.
  3. Check whether a character is vowel or consonant.
  4. Create a login system where username = “admin” and password = “1234”.
  5. Write a program to check whether a number is divisible by both 3 and 5.

Summary

if-else allows your program to choose between two paths.

  • You can use multiple conditions using else if.
  • For complex conditions, use nested if.
  • Conditions must return true/false.
  • Always test your logic with different inputs.

Final Words

Learning how to control the flow of your program is one of the most powerful tools you’ll gain as a Java programmer. The if-else statement is your first step toward writing smart, dynamic, and intelligent code.

Keep practicing with different examples. The more conditions you handle, the more you’ll learn how programs really think!