Java If-Else Statement - Syntax, Flowchart and Examples

⏱️ 7 min read • Beginner Level • Lesson 22

Lesson 22 of 124 of Java Tutorial
You have completed this lesson

Completed on . You can revise this lesson or continue to the next topic.

The if-else statement in Java is used when we want to execute one block of code if a condition is true, and another block of code if the condition is false.

Before learning the if-else statement, you should understand Java if statement, Java operators, and Java data types.


What is if-else Statement in Java?

The if-else statement is a decision-making statement. It checks a condition and chooses between two possible blocks of code.

  • If the condition is true, the if block executes.

  • If the condition is false, the else block executes.

  • It is useful when exactly one of two actions should happen.

Syntax of if-else Statement

The syntax of an if-else statement contains one condition, one if block, and one else block.

IfElseSyntax.java
Copy Download
if (condition) {
    // statements execute if condition is true
} else {
    // statements execute if condition is false
}
Note: The condition inside if must return a boolean value: either true or false.

Flowchart of if-else Statement

The flowchart below shows how an if-else statement works. Java checks the condition first. If the condition is true, the if block executes. Otherwise, the else block executes.

Flowchart of if-else statement in Java

How does it work?

  • Java first checks the condition written inside the if statement.
  • If the condition evaluates to true, the statements inside the if block are executed.
  • If the condition evaluates to false, the statements inside the else block are executed.
  • After executing either the if block or the else block, the program continues with the next statement after the if-else structure.

Real-World Uses of if-else

  • Checking whether a student passed or failed.
  • Determining voting eligibility.
  • Verifying login credentials.
  • Checking account balance before withdrawal.
  • Applying discounts based on purchase amount.

Java if-else Statement Example

The following program checks whether a number is positive or negative using an if-else statement. If the entered number is greater than or equal to 0, the program prints "X is Positive". Otherwise, it prints "X is Negative".

IfElseExample.java
Copy Try Download
import java.util.Scanner;

public class IfElseExample {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter any number: ");
        int x = sc.nextInt();

        if (x >= 0) {
            System.out.println("X is Positive");
        } else {
            System.out.println("X is Negative");
        }

        sc.close();
    }
}

Output 1:

Enter any number:10
X is Positive

Output 2:

Enter any number:-12
X is Negative

Explanation of the Program

  1. The program imports the Scanner class from the java.util package.
  2. A Scanner object named sc is created to read input from the keyboard.
  3. The statement System.out.print("Enter any number: "); displays a message asking the user to enter a number.
  4. The statement int x = sc.nextInt(); reads the integer value entered by the user and stores it in the variable x.
  5. The condition x >= 0 checks whether the value of x is greater than or equal to zero.
  6. If the condition is true, the if block executes and prints "X is Positive".
  7. If the condition is false, the else block executes and prints "X is Negative".
  8. Finally, sc.close(); closes the Scanner object and releases system resources.

How does this program work?

  • If the user enters 12, the condition 12 >= 0 becomes true, so the program prints X is Positive.
  • If the user enters -12, the condition -12 >= 0 becomes false, so the program prints X is Negative.
  • In an if-else statement, only one block executes: either the if block or the else block.

Another Example: Check Pass or Fail

The following program checks whether a student passed or failed based on marks. If the marks are greater than or equal to 33, the program prints "Pass". Otherwise, it prints "Fail".

PassFailExample.java
Copy Try Download
public class PassFailExample {
    public static void main(String[] args) {
        int marks = 25;

        if (marks >= 33) {
            System.out.println("Pass");
        } else {
            System.out.println("Fail");
        }
    }
}

Output:

Fail

Explanation of Pass or Fail Program

  1. The variable marks is declared and initialized with the value 25.
  2. The condition marks >= 33 checks whether the student has scored at least 33 marks.
  3. Since 25 >= 33 is false, the if block is skipped.
  4. The else block executes and prints "Fail".
  5. If the value of marks was 33 or more, the program would print "Pass".

Example: Check Voting Eligibility

In this example, we will check whether a person is eligible to vote or not. If the age is greater than or equal to 18, the person is eligible to vote. Otherwise, the person is not eligible to vote.

VotingEligibilityExample.java
Copy Try Download
public class VotingEligibilityExample {
    public static void main(String[] args) {
        int age = 20;

        if (age >= 18) {
            System.out.println("Eligible to Vote");
        } else {
            System.out.println("Not Eligible to Vote");
        }
    }
}

Output:

Eligible to Vote

Explanation

  • The variable age is initialized with the value 20.
  • The condition age >= 18 checks whether the age is greater than or equal to 18.
  • Since 20 >= 18 is true, the if block executes.
  • Therefore, the program prints Eligible to Vote.
  • If the value of age was less than 18, the else block would execute and print Not Eligible to Vote.

Difference Between if and if-else

if Statement if-else Statement
Executes a block only if the condition is true. Executes one block if true and another block if false.
No alternate block is required. Alternate else block is available.
Used when action is needed only for true condition. Used when one of two actions must happen.

Common Mistakes with if-else Statement

  • Using = instead of == for comparison.
  • Adding a semicolon immediately after the if condition.
  • Forgetting braces when multiple statements should be inside a block.
  • Writing a condition that does not return a boolean value.
  • Confusing else with a separate condition. The else block does not have a condition.

Mistake: Semicolon after if condition

IfElseSemicolonMistake.java
Copy Try Download
public class IfElseSemicolonMistake {
    public static void main(String[] args) {
        int x = -10;

        if (x >= 0); {
            System.out.println("Positive");
        } else {
            System.out.println("Negative");
        }
    }
}
Important: The above code causes a compilation problem because the semicolon ends the if statement before the block. Avoid placing a semicolon after if (condition).
Summary:
  • The if-else statement is used for two-way decision-making.
  • If the condition is true, the if block executes.
  • If the condition is false, the else block executes.
  • The condition inside if must be a boolean expression.
  • Use braces { } for better readability and safer code.

Interview Questions ⭐

The if-else statement in Java is a decision-making statement that executes one block of code when a condition is true and another block when the condition is false.

An if statement executes code only when the condition is true, while an if-else statement executes one block when true and another block when false.

No, the else block does not have a condition. It executes automatically when the if condition is false.

Yes, braces are optional for a single statement, but using braces is recommended for readability and to avoid mistakes.

The condition inside an if-else statement must be a boolean expression that evaluates to true or false.

A common mistake is placing a semicolon immediately after the if condition, which can break the if-else structure and cause unexpected behavior or compilation errors.

Next step: Learn Java If-Else-If Ladder

🚀 Continue to Java If-Else-If Ladder →

🧠 Test your understanding with a quick quiz



🚀 Quick Knowledge Check

Topic: If-else-statement | Language: Java

Question 1 of 10
Q1. Which of the following is the correct syntax of an if-else statement in Java?
Q2. What happens if the if condition is false in an if-else statement?
Q3. What will be the output of this code?
int marks = 25;
if (marks >= 33) {
    System.out.println("Pass");
} else {
    System.out.println("Fail");
}
Q4. What is the main purpose of an if-else statement in Java?
Q5. What type of expression is required inside the if condition?
Q6. What will be the output of this code?
int x = -12;
if (x >= 0) {
    System.out.println("Positive");
} else {
    System.out.println("Negative");
}
Q7. What will be the output of the following code?
int x = 12;
if (x >= 0) {
    System.out.println("Positive");
} else {
    System.out.println("Negative");
}
Q8. Which statement is TRUE about if-else in Java?
Q9. Does the else block have a condition in Java?
Q10. What is wrong with the following code?
int x = 10;
if (x = 10) {
    System.out.println("Equal");
} else {
    System.out.println("Not Equal");
}

🎉 Great job! Continue learning Java step by step.

Discussion

Ask questions, share suggestions, or discuss this lesson.

Please login or create an account to join the discussion and save your learning activity.

Loading comments...

Have you completed this lesson?

Mark this lesson as completed to track your learning progress. To keep track across devices, please login and save your learning progress.

Not completed yet.