Skip to main content
Course/Module 3/Topic 1 of 4Beginner

If-Else Statements

Conditional statements let your program make decisions. The if-else statement checks a condition and executes different code blocks depending on whether the condition is true or false.

35 minBy Priygop TeamLast updated: Feb 2026

How If-Else Works

The if statement evaluates a boolean condition. If the condition is true, the code inside the if block runs. If it's false, the code inside the else block runs (if provided). You can chain multiple conditions with 'else if' for more complex decision-making.

If-Else Examples

Example
public class IfElseDemo {
    public static void main(String[] args) {
        int age = 20;
        
        // Simple if-else
        if (age >= 18) {
            System.out.println("You are an adult!");
        } else {
            System.out.println("You are a minor.");
        }
        
        // If-else if-else chain
        int score = 85;
        String grade;
        
        if (score >= 90) {
            grade = "A";
        } else if (score >= 80) {
            grade = "B";
        } else if (score >= 70) {
            grade = "C";
        } else if (score >= 60) {
            grade = "D";
        } else {
            grade = "F";
        }
        System.out.println("Score: " + score + " → Grade: " + grade);
        
        // Nested if
        boolean hasTicket = true;
        int personAge = 15;
        
        if (hasTicket) {
            if (personAge >= 13) {
                System.out.println("Welcome to the movie!");
            } else {
                System.out.println("You need a parent.");
            }
        } else {
            System.out.println("Please buy a ticket first.");
        }
        
        // Ternary operator (shorthand if-else)
        String status = (age >= 18) ? "Adult" : "Minor";
        System.out.println("Status: " + status);
    }
}

Try It Yourself: Grade Calculator

Try It Yourself: Grade CalculatorJava
Java Editor
✓ ValidTab = 2 spaces
Java|34 lines|1015 chars|✓ Valid syntax
UTF-8

Quick Quiz: If-Else

Chat on WhatsApp
Priygop - Leading Professional Development Platform | Expert Courses & Interview Prep