Java If–Else Statements
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

Java If–Else Statements

Jeevadharshan

Java If–Else Statements

Conditional statements in Java allow your program to make decisions and control execution flow. Using if, else if, and else, you can run specific blocks of code only when certain conditions are met. 
 
A simple real-world analogy: 
If it rains → carry an umbrella. Otherwise → do nothing. 
 
In Java, every if statement evaluates a boolean condition (true or false) to determine whether its code block should execute.

Types of Conditional Statements in Java

Java provides several decision-making statements:
  • if → executes when condition is true 
  • else → executes when condition is false 
  • else if → checks additional conditions 
  • switch → handles multiple fixed options

The if Statement 

The if statement runs a block of code only when its condition evaluates to true.  

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

Example: Checking Eligibility 
 
public class VotingEligibility { 
    public static void main(String[] args) { 
        int age = 22; 
 
        if (age >= 18) { 
            System.out.println("Eligible to vote"); 
        } 
    } 
}

Output

Eligible to vote

Comparing Two Variables 

public class ScoreComparison { 
    public static void main(String[] args) { 
        int playerOneScore = 85; 
        int playerTwoScore = 78; 
 
        if (playerOneScore > playerTwoScore) { 
            System.out.println("Player One leads the game"); 
        } 
    } 
}

Output

Player One leads the game 

Checking Equality 

public class PasswordCheck { 
    public static void main(String[] args) { 
        int enteredCode = 4321; 
        int storedCode = 4321; 
 
        if (enteredCode == storedCode) { 
            System.out.println("Access granted"); 
        } 
    } 
}

Output

Access granted

Using Boolean Variables in if  

You can directly use boolean variables as conditions. 
 
public class DeviceStatus { 
    public static void main(String[] args) { 
        boolean isConnected = true; 
 
        if (isConnected) { 
            System.out.println("Device is online"); 
        } 
    } 
}

Output

Device is online

This is equivalent to: 
 
if (isConnected == true) 
 
…but shorter and clearer.

Example: Condition is False 
 
public class FeatureToggle { 
    public static void main(String[] args) { 
        boolean featureEnabled = false; 
 
        if (featureEnabled) { 
            System.out.println("New feature active"); 
        } 
 
        System.out.println("Application running normally"); 
    } 

Output 

Application running normally

The second line executes because it is outside the if block. 

If Without Braces { } 

If only one statement belongs to if, braces are optional: 
 
public class SimpleIf { 
    public static void main(String[] args) { 
        int temperature = 35; 
 
        if (temperature > 30) 
            System.out.println("Hot weather"); 
    } 
}

Common Mistake Without Braces 

Only the first statement belongs to the if. 
 
public class BraceMistake { 
    public static void main(String[] args) { 
        int stock = 5; 
        int order = 10; 
 
        if (order > stock) 
            System.out.println("Insufficient stock"); 
            System.out.println("Order cannot be processed"); 
    } 

Actual Output 

Insufficient stock 
Order cannot be processed 
 
The second line always runs — even when the condition is false.

Java else Statement 

The else statement in Java defines an alternative execution path when the condition in an if statement evaluates to false. Together, if and else allow programs to handle two possible outcomes, making them essential for decision-making logic. 

What Does the else Statement Do? 

In simple terms: 
 
If a condition is true → run one block of code 
Otherwise (else) → run another block 
 
This pattern is widely used in validation, user input handling, authentication, and business rules. 

if–else Syntax in Java 

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

Important Rules

  • The if condition must return a boolean (true or false) 
  • else has no condition 
  • Never place a semicolon after if (condition) 
  • Use braces { } for clarity and safety
Example 1: Order Delivery Decision 
 
public class DeliveryCheck { 
    public static void main(String[] args) { 
        double orderAmount = 750.0; 
        double freeDeliveryThreshold = 500.0; 
 
        if (orderAmount >= freeDeliveryThreshold) { 
            System.out.println("Free delivery applied"); 
        } else { 
            System.out.println("Delivery charges added"); 
        } 
    } 
 
Explanation: 
Since the order amount meets the threshold, the if block runs. Otherwise, the else block would apply delivery charges.

Example 2: Exam Result Message 
 
public class ExamResult { 
    public static void main(String[] args) { 
        int marks = 42; 
        int passMarks = 50; 
 
        if (marks >= passMarks) { 
            System.out.println("Result: Pass"); 
        } else { 
            System.out.println("Result: Fail"); 
        } 
    } 

Example 3: Time-Based Greeting 
 
public class GreetingApp { 
    public static void main(String[] args) { 
        int hourOfDay = 19; 
 
        if (hourOfDay < 18) { 
            System.out.println("Good day"); 
        } else { 
            System.out.println("Good evening"); 
        } 
    } 
}

Why “Good evening”? 

Because 19 < 18 is false, the else block executes.

How else Executes 
  • Java evaluates the if condition 
  • If true → run if block 
  • If false → skip if block 
  • Execute else block 
  • Continue program normally

Common Error: Semicolon After if 

Incorrect: 

if (temperature > 30); { 
    System.out.println("Hot day"); 
} else { 
    System.out.println("Pleasant day"); 
 
The semicolon ends the if prematurely, causing a compile-time error with else.  

Correct: 

if (temperature > 30) { 
    System.out.println("Hot day"); 
} else { 
    System.out.println("Pleasant day"); 

When to Use else 

Use else when:
  • There are exactly two possible outcomes 
  • You need a fallback/default action 
  • Handling success vs failure 
  • Validating conditions 
  • Controlling program flow

Java else if Statement 

The else if statement in Java allows you to evaluate multiple conditions sequentially. It is used when you need more than two possible execution paths in a decision structure. 

In an if–else if–else chain, Java checks each condition in order. As soon as one condition evaluates to true, its block executes and the rest of the chain is skipped. 

Why Use else if? 

Real-world analogy:
 
If it’s raining → carry an umbrella 
Else if it’s sunny → wear sunglasses 
Else → go out normally  
 
This pattern is common in applications that must choose among several outcomes based on different conditions. 

Syntax of if–else if–else 

if (condition1) { 
// runs if condition1 is true 
} else if (condition2) { 
// runs if condition1 is false AND condition2 is true 
} else { 
// runs if all above conditions are false 
}

Key Rules 

  • Conditions are evaluated top to bottom 
  • Only the first matching block executes 
  • else is optional but recommended 
  • Each condition must return a boolean
Example 1: Shipping Cost Category 
 
public class ShippingCategory { 
    public static void main(String[] args) { 
        double weightKg = 7.5; 
 
        if (weightKg <= 1) { 
            System.out.println("Light package"); 
        } else if (weightKg <= 5) { 
            System.out.println("Standard package"); 
        } else if (weightKg <= 10) { 
            System.out.println("Heavy package"); 
        } else { 
            System.out.println("Oversized package"); 
        } 
    } 
}
 
Explanation: 
 
Since 7.5 <= 10 is the first true condition, “Heavy package” is printed and the rest is skipped.
 
Example 2: Academic Grade Classification 
 
public class GradeCalculator { 
    public static void main(String[] args) { 
        int score = 83; 
 
        if (score >= 90) { 
            System.out.println("Grade: A"); 
        } else if (score >= 75) { 
            System.out.println("Grade: B"); 
        } else if (score >= 60) { 
            System.out.println("Grade: C"); 
        } else { 
            System.out.println("Grade: D"); 
        } 
    } 
}

Example 3: Time-Based Greeting 
 
public class SmartGreeting { 
    public static void main(String[] args) { 
        int hour = 22; 
 
        if (hour < 12) { 
            System.out.println("Good morning"); 
        } else if (hour < 18) { 
            System.out.println("Good afternoon"); 
        } else { 
            System.out.println("Good evening"); 
        } 
    } 
}

Why “Good evening”? 

Because both earlier conditions are false.

How else if Executes Internally

  1. Evaluate if condition 
  2. If true → execute and exit chain 
  3. If false → check next else if 
  4. Repeat until a condition is true 
  5. If none true → execute else

Common Mistake: Incorrect Order of Conditions 

 Incorrect: 

if (score >= 60) { 
    System.out.println("Pass"); 
} else if (score >= 90) { 
    System.out.println("Excellent"); 
 
The second condition never runs because scores ≥90 already satisfy ≥60.  

Correct: 

if (score >= 90) { 
System.out.println("Excellent"); 
} else if (score >= 60) { 
System.out.println("Pass"); 

When to Use else if 

Use else if when: 
  • There are multiple mutually exclusive conditions 
  • Decisions depend on ranges or categories 
  • Only one outcome should execute 
  • Replacing nested if improves readability

Java Ternary Operator (?:): Short-Hand if–else 

The ternary operator in Java provides a concise way to write simple if–else conditions in a single line. It is called ternary because it uses three operands: 

condition ? valueIfTrue : valueIfFalse

This operator is ideal when you need to choose between two values based on a boolean condition. 

Why Use the Ternary Operator? 

Instead of writing a multi-line if–else, you can assign or return a value directly from a condition. This improves readability for short decisions and reduces boilerplate code.

Basic Syntax 

result = (condition) ? expressionIfTrue : expressionIfFalse;
  • condition → must evaluate to true or false 
  • expressionIfTrue → returned when condition is true 
  • expressionIfFalse → returned when condition is false
Example 1: Discount Eligibility 

Standard if–else 
public class DiscountCheck { 
    public static void main(String[] args) { 
        double purchaseAmount = 1200; 
        String discountMessage; 
 
        if (purchaseAmount >= 1000) { 
            discountMessage = "Discount applied"; 
        } else { 
            discountMessage = "No discount"; 
        } 
 
        System.out.println(discountMessage); 
    } 
}

Using Ternary Operator 

public class DiscountCheckTernary { 
    public static void main(String[] args) { 
        double purchaseAmount = 1200; 
 
        String discountMessage = (purchaseAmount >= 1000) 
                ? "Discount applied" 
                : "No discount"; 
 
        System.out.println(discountMessage); 
    } 

Example 2: Direct Output with Ternary 
 
You can use the ternary operator directly inside println. 
 
public class TemperatureStatus { 
    public static void main(String[] args) { 
        int temperature = 28; 
 
        System.out.println( 
            (temperature > 30) ? "Hot weather" : "Comfortable weather" 
        ); 
    } 
}

Example 3: Choosing the Larger Number 
 
public class MaxValueTernary { 
    public static void main(String[] args) { 
        int a = 45; 
        int b = 72; 
 
        int max = (a > b) ? a : b; 
 
        System.out.println("Larger value: " + max); 
    } 
}

Nested Ternary Operator (Multiple Conditions)  

You can chain ternary operators to handle more than two outcomes. However, readability can decrease if overused. 
 
public class ScoreCategory { 
    public static void main(String[] args) { 
        int score = 67; 
 
        String category = (score >= 90) ? "Excellent" 
                         : (score >= 75) ? "Good" 
                         : (score >= 50) ? "Average" 
                         : "Needs Improvement"; 
 
        System.out.println(category); 
    } 
}

When to Use the Ternary Operator

 Use it when:
  • There are exactly two outcomes 
  • The logic is simple 
  • You need to assign or return a value 
  • It improves readability 

When NOT to Use It

Avoid ternary when
  • Logic is complex 
  • Multiple statements are needed 
  • Nested conditions become hard to read 
  • Side effects occur
In such cases, a regular if–else is clearer. 

Java Nested if Statement 

In Java, a nested if statement is an if block placed inside another if block. This structure allows you to evaluate a secondary condition only when a primary condition is already true. 
 
Nested conditionals are useful when decisions depend on multiple related criteria—such as eligibility checks, permissions, or multi-step validation.  

What Is a Nested if? 

A nested if enables hierarchical decision-making: 
 
      If condition A is true → then check condition B 
      If both are true → execute specific code 
 
Syntax of Nested if in Java 
 
if (condition1) { 
    // runs if condition1 is true 
 
    if (condition2) { 
        // runs only if both condition1 and condition2 are true 
    } 
}  
 
You can also combine nested if with else or else if for more complete logic paths.

Example 1: Product Purchase Validation 
 
public class PurchaseValidation { 
    public static void main(String[] args) { 
        double walletBalance = 2500; 
        double productPrice = 1800; 
        boolean productInStock = true; 
 
        if (walletBalance >= productPrice) { 
            System.out.println("Sufficient balance"); 
 
            if (productInStock) { 
                System.out.println("Product available — purchase successful"); 
            } else { 
                System.out.println("Product out of stock"); 
            } 
        } else { 
            System.out.println("Insufficient balance"); 
        } 
    } 
}

Logic: 
 
The stock check runs only if the user can afford the product.
 
Example 2: Employee Bonus Eligibility 
 
public class BonusEligibility { 
    public static void main(String[] args) { 
        int yearsOfService = 6; 
        double performanceRating = 4.5; 
 
        if (yearsOfService >= 5) { 
            System.out.println("Service requirement met"); 
 
            if (performanceRating >= 4.0) { 
                System.out.println("Eligible for performance bonus"); 
            } else { 
                System.out.println("Performance rating too low"); 
            } 
        } else { 
            System.out.println("Not eligible — insufficient service years"); 
        } 
    } 
}

Example 3: Student Admission Check 
 
public class AdmissionCheck { 
    public static void main(String[] args) { 
        int entranceScore = 82; 
        boolean hasValidDocuments = true; 
 
        if (entranceScore >= 75) { 
            if (hasValidDocuments) { 
                System.out.println("Admission approved"); 
            } else { 
                System.out.println("Documents verification pending"); 
            } 
        } else { 
            System.out.println("Entrance score below cutoff"); 
        } 
    } 

How Nested if Executes 

  • Outer if condition is evaluated 
  • If false → skip entire inner block 
  • If true → enter outer block 
  • Inner if condition evaluated 
  • Execute matching inner branch

When to Use Nested if

Nested if is appropriate when:
  • One condition depends on another 
  • Validation occurs in stages 
  • Permissions or prerequisites exist 
  • Multiple criteria must all be satisfied

Alternative: Combining Conditions 

Sometimes nested if can be simplified using logical operators: 
 
if (walletBalance >= productPrice && productInStock) { 
    System.out.println("Purchase successful"); 
 
Use this when both conditions are independent and required together.

Java Logical Operators in Conditions (&&, ||, !) 

Logical operators in Java allow you to combine, evaluate, and invert conditions inside decision 
statements such as if, else if, and while. They are essential for building real-world program logic 
where multiple criteria determine outcomes.

Why Logical Operators Matter? 

Most real applications require checking more than one condition. For example:
  • User must be authenticated and verified 
  • Order is valid or priority customer 
  • Account is not suspended
Logical operators make such compound conditions possible.

AND Operator (&&) 

The AND operator returns true only if every condition is true. 
 
Example: Loan Approval Criteria 
 
public class LoanApproval { 
    public static void main(String[] args) { 
        int creditScore = 720; 
        double annualIncome = 55000; 
 
        if (creditScore >= 700 && annualIncome >= 50000) { 
            System.out.println("Loan approved"); 
        } else { 
            System.out.println("Loan rejected"); 
        } 
    } 
}  
 
Logic: Both credit score and income requirements must be satisfied.

OR Operator (||) 

The OR operator returns true if any one condition is true. 
 
Example: Free Delivery Eligibility 

public class DeliveryEligibility { 
    public static void main(String[] args) { 
        double orderAmount = 350; 
        boolean premiumMember = true; 
 
        if (orderAmount >= 500 || premiumMember) { 
            System.out.println("Eligible for free delivery"); 
        } else { 
            System.out.println("Delivery charges apply"); 
        } 
    } 
  
Logic: Either large order OR membership qualifies.

NOT Operator (!) 

The NOT operator reverses a boolean value. 
  • true → false 
  • false → true
Example: Account Status Check 
 
public class AccountStatus { 
    public static void main(String[] args) { 
        boolean accountSuspended = false; 
 
        if (!accountSuspended) { 
            System.out.println("Account active"); 
        } else { 
            System.out.println("Account suspended"); 
        } 
    } 
}

Combined Logical Conditions  

Logical operators are often combined for complex rules. 
 
Example: System Access Control 
 
public class SystemAccess { 
    public static void main(String[] args) { 
        boolean isLoggedIn = true; 
        boolean has2FA = true; 
        String role = "USER"; 
 
        if (isLoggedIn && has2FA && (role.equals("ADMIN") || role.equals("SUPERVISOR"))) { 
            System.out.println("Privileged access granted"); 
        } else { 
            System.out.println("Standard or denied access"); 
        } 
    } 
}

Logic Explanation 

Access requires: 
  • Logged in  
  • Two-factor authentication  
  • Role = ADMIN or SUPERVISOR

Our website uses cookies to enhance your experience. Learn More
Accept !