Java Lesson — if, else, ternary operator, and switch

A complete lesson from ground level to advanced use of decision making in Java.

What this lesson covers

In this lesson, you will learn how Java makes decisions using if, else, else if, the ternary operator, and switch. These are some of the most important tools in programming because they allow your program to choose different actions depending on the situation.

We will start at level zero, where you simply check one condition, and then move toward more advanced patterns such as nested conditions, switch expressions, choosing between if and switch, and writing cleaner, more readable decision-making logic.

if

Run code only when a condition is true

else

Run alternate code when condition is false

ternary

Short form for simple if-else logic

switch

Choose one block from many possible cases

Why decision making matters

Real programs do not just run line by line without thinking. They must make decisions. For example:

Decision statements make your programs intelligent and responsive.

Level 0 — The if statement

The simplest decision statement in Java is if. It checks a condition. If the condition is true, the code inside the block runs.

if (condition) {
    // code to run if condition is true
}

Example

int age = 20;

if (age >= 18) {
    System.out.println("You are an adult.");
}

Since age >= 18 is true, the message is printed.

Another example

int marks = 75;

if (marks >= 40) {
    System.out.println("Pass");
}

Level 1 — The if-else statement

Sometimes you want one action when the condition is true and another action when it is false. That is where else is used.

if (condition) {
    // code if true
} else {
    // code if false
}

Example

int marks = 32;

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

Since the condition is false here, the program prints Fail.

Level 2 — The else if ladder

When there are many possible conditions, you can use else if. Java checks each condition from top to bottom. As soon as one condition is true, that block runs and the rest are skipped.

if (condition1) {
    // block 1
} else if (condition2) {
    // block 2
} else if (condition3) {
    // block 3
} else {
    // default block
}

Example with grades

int marks = 84;

if (marks >= 90) {
    System.out.println("Grade A+");
} else if (marks >= 75) {
    System.out.println("Grade A");
} else if (marks >= 60) {
    System.out.println("Grade B");
} else if (marks >= 40) {
    System.out.println("Grade C");
} else {
    System.out.println("Fail");
}

Because 84 is not greater than or equal to 90 but is greater than or equal to 75, the program prints Grade A.

Level 3 — Nested if statements

A nested if statement means an if inside another if. Use this when a second decision depends on the first one.

int age = 20;
boolean hasId = true;

if (age >= 18) {
    if (hasId) {
        System.out.println("Entry allowed.");
    } else {
        System.out.println("Bring your ID.");
    }
} else {
    System.out.println("You are underage.");
}

Nested logic is powerful, but too much nesting can make code hard to read. Later in this lesson, we will see how to keep such code clean.

Conditions must be boolean

In Java, the condition inside if must be a boolean expression. That means it must evaluate to either true or false.

int x = 10;

if (x > 5) {
    System.out.println("x is greater than 5");
}

This is correct because x > 5 is a boolean expression.

int x = 10;

// This is wrong in Java
// if (x) {
//     System.out.println("Hello");
// }

Unlike some other languages, Java does not allow plain numbers as conditions.

Using relational and logical operators in if statements

Decision making becomes more useful when combined with relational operators like >, <, ==, and logical operators like &&, ||, and !.

int age = 22;
boolean hasTicket = true;

if (age >= 18 && hasTicket) {
    System.out.println("You may enter.");
} else {
    System.out.println("Entry not allowed.");
}
boolean isHoliday = false;
boolean isSunday = true;

if (isHoliday || isSunday) {
    System.out.println("No school today.");
}

Common mistakes in if and else

Wrong order example

int marks = 95;

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

This is wrong because any value above 90 is also above 40, so the first block runs and the second block is never reached.

Correct order example

int marks = 95;

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

The ternary operator

The ternary operator is a short form of if-else. It is useful when you want to choose one of two values quickly.

condition ? valueIfTrue : valueIfFalse

Simple example

int age = 17;

String result = (age >= 18) ? "Adult" : "Minor";
System.out.println(result);

This means: if age >= 18 is true, use "Adult". Otherwise, use "Minor".

Equivalent if-else code

String result;

if (age >= 18) {
    result = "Adult";
} else {
    result = "Minor";
}

When to use ternary and when not to use it

Use the ternary operator when the logic is short and simple. Avoid it when the expression becomes long or confusing.

Good ternary use

int num = 8;
String type = (num % 2 == 0) ? "Even" : "Odd";
System.out.println(type);

Poor ternary use

String result = (marks >= 90) ? "A+" :
                (marks >= 75) ? "A" :
                (marks >= 60) ? "B" :
                (marks >= 40) ? "C" : "Fail";

This works, but it is harder to read. In such cases, an else if ladder is usually better.

The switch statement

Use switch when one variable or expression can have several fixed values, and you want different code for each value.

switch (expression) {
    case value1:
        // code
        break;
    case value2:
        // code
        break;
    default:
        // code
}

Example with day number

int day = 3;

switch (day) {
    case 1:
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    case 3:
        System.out.println("Wednesday");
        break;
    case 4:
        System.out.println("Thursday");
        break;
    case 5:
        System.out.println("Friday");
        break;
    case 6:
        System.out.println("Saturday");
        break;
    case 7:
        System.out.println("Sunday");
        break;
    default:
        System.out.println("Invalid day");
}

What break does in switch

The break statement stops the switch once a matching case has run. Without break, execution continues into the next cases. This is called fall-through.

Example without break

int day = 2;

switch (day) {
    case 1:
        System.out.println("Monday");
    case 2:
        System.out.println("Tuesday");
    case 3:
        System.out.println("Wednesday");
    default:
        System.out.println("Done");
}

Here, if day is 2, Java prints Tuesday, then Wednesday, then Done, because there are no breaks.

Intentional fall-through example

char grade = 'B';

switch (grade) {
    case 'A':
    case 'B':
    case 'C':
        System.out.println("Pass");
        break;
    case 'D':
    case 'F':
        System.out.println("Needs improvement");
        break;
    default:
        System.out.println("Unknown grade");
}

Here, fall-through is used on purpose to group cases together.

switch with strings

Java can also use strings in a switch statement.

String role = "admin";

switch (role) {
    case "admin":
        System.out.println("Full access");
        break;
    case "teacher":
        System.out.println("Teaching access");
        break;
    case "student":
        System.out.println("Learning access");
        break;
    default:
        System.out.println("Unknown role");
}

Modern switch expression

Modern Java also supports a cleaner switch style using arrows. This style is shorter and avoids many break-related mistakes.

int day = 5;

switch (day) {
    case 1 -> System.out.println("Monday");
    case 2 -> System.out.println("Tuesday");
    case 3 -> System.out.println("Wednesday");
    case 4 -> System.out.println("Thursday");
    case 5 -> System.out.println("Friday");
    case 6 -> System.out.println("Saturday");
    case 7 -> System.out.println("Sunday");
    default -> System.out.println("Invalid day");
}

Switch expression returning a value

int day = 6;

String type = switch (day) {
    case 1, 2, 3, 4, 5 -> "Weekday";
    case 6, 7 -> "Weekend";
    default -> "Invalid";
};

System.out.println(type);

if-else versus switch

Use case Better choice Why
Checking ranges like marks >= 40 if-else Switch is not designed for range comparisons like this.
Checking one variable against many fixed values switch It is cleaner and easier to read.
Short two-way choice ternary It is concise and useful for assignments.
Complex boolean conditions if-else Logical operators fit naturally here.

Expert tips for cleaner decision-making code

Complete beginner-to-advanced example

public class Main {
    public static void main(String[] args) {
        int marks = 82;
        int day = 6;
        boolean hasProject = true;

        // if-else-if ladder
        if (marks >= 90) {
            System.out.println("Grade A+");
        } else if (marks >= 75) {
            System.out.println("Grade A");
        } else if (marks >= 60) {
            System.out.println("Grade B");
        } else if (marks >= 40) {
            System.out.println("Grade C");
        } else {
            System.out.println("Fail");
        }

        // ternary operator
        String projectStatus = hasProject ? "Project submitted" : "Project missing";
        System.out.println(projectStatus);

        // switch expression
        String dayType = switch (day) {
            case 1, 2, 3, 4, 5 -> "Weekday";
            case 6, 7 -> "Weekend";
            default -> "Invalid";
        };

        System.out.println(dayType);

        // nested if
        if (marks >= 40) {
            if (hasProject) {
                System.out.println("Student passed and completed project.");
            } else {
                System.out.println("Student passed but project is missing.");
            }
        } else {
            System.out.println("Student failed.");
        }
    }
}

Assignments

Assignment 1: Write a program that checks whether a number is positive using a simple if.
Assignment 2: Write a program that checks whether a number is even or odd using if-else.
Assignment 3: Write a program that prints pass or fail using if-else.
Assignment 4: Write a program that prints grades A, B, C, or Fail using an else if ladder.
Assignment 5: Write a nested if program to allow entry only when age is at least 18 and the user has an ID card.
Assignment 6: Rewrite a simple pass-fail program using the ternary operator.
Assignment 7: Use switch to print the day name for numbers 1 to 7.
Assignment 8: Use switch with string values like "admin", "teacher", and "student".
Assignment 9: Use a modern switch expression to decide whether a day is a weekday or weekend.
Assignment 10: Write one program that uses all of these: if, else if, ternary operator, and switch.

Interactive MCQ Quiz

Choose one answer for each question and click Check Answers.

Total Questions: 0

0 / 0

Your result will appear here.

Quick revision