JavaBasicsbeginner
Updated:

Java Control Statements: if, switch and Decision Making

6 min read

How Java programs make decisions: if, if-else, the ternary operator, switch statements and modern switch expressions, with the pitfalls interviewers love to test.

TL;DR – Quick Answer

Control statements let a Java program choose which code to run based on conditions. The main decision-making statements are if, if-else, the else-if ladder, the ternary operator and switch. Since Java 14 you can also use switch expressions, which return a value and remove fall-through bugs.

On This Page

Every useful program makes decisions. A banking app checks whether the balance covers a withdrawal. A login form checks whether the password matches. In Java, the statements that make these decisions are called control statements, and they are the first place where your code stops being a straight line and starts having logic.

This tutorial covers the decision-making statements: if, if-else, the else-if ladder, nested if, the ternary operator, the classic switch statement and the modern switch expression. Repetition statements get their own guide on Java loops.

What control statements do in a Java program

By default, the JVM executes your statements top to bottom, one after another. Control statements interrupt that flow. Java groups them into three families:

Family Statements Purpose
Decision-making if, if-else, switch Choose between paths
Looping for, while, do-while Repeat a block of code
Jump break, continue, return Transfer control elsewhere

This page focuses on the first family. Every decision-making statement evaluates a condition built from Java operators — comparisons like > and ==, combined with && and || — and the condition must produce a boolean. Unlike C or Python, Java will not accept an int where a boolean is expected, so if (1) is a compile error.

The if statement

The if statement runs a block only when its condition is true:

public class WithdrawCheck {
    public static void main(String[] args) {
        double balance = 5000.0;
        double amount = 2000.0;

        if (amount <= balance) {
            balance = balance - amount;
            System.out.println("Withdrawal successful. New balance: " + balance);
        }
        System.out.println("Transaction complete.");
    }
}

Run this and both lines print. Change amount to 8000.0 and only "Transaction complete." prints — the block inside if is skipped entirely. Notice that the condition compares two variables; the result of amount <= balance is a boolean that the if consumes.

Braces are technically optional for a single statement, but always write them. Adding a second line to a brace-less if later is one of the oldest sources of production bugs.

Common mistake: A common mistake beginners make is writing if (isActive = true) instead of if (isActive == true). The single = assigns rather than compares. Because the assignment expression evaluates to true, the block always runs. The cleaner fix is to drop the comparison completely and write if (isActive).

if-else and the else-if ladder

else gives the condition a second path, and chaining else if lets you test several conditions in order. Java evaluates the ladder top to bottom and runs the first branch whose condition is true — everything after it is skipped.

public class GradeCalculator {
    public static void main(String[] args) {
        int marks = 74;
        String grade;

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

This prints Marks 74 => Grade C. Order matters: because 74 >= 60 is the first condition that passes, the ladder never checks the rest. If you reversed the ladder and tested marks >= 40 first, every passing student would get a D. When you review your own ladders, check that conditions go from most specific to least specific.

Nested if statements

You can place an if inside another if when a second check only makes sense after the first one passes:

if (user != null) {
    if (user.isVerified()) {
        System.out.println("Access granted");
    }
}

Nesting two levels is fine. Beyond that, readability collapses fast. Most deep nesting can be flattened with early returns or by combining conditions:

if (user != null && user.isVerified()) {
    System.out.println("Access granted");
}

The && operator short-circuits: if user != null is false, Java never calls user.isVerified(), so there is no NullPointerException. This short-circuit behaviour is exactly why the combined version is safe and why interviewers ask about it.

The ternary operator

The ternary operator condition ? valueIfTrue : valueIfFalse is a compact if-else that produces a value:

int a = 12, b = 20;
int max = (a > b) ? a : b;          // 20
String result = (marks >= 40) ? "Pass" : "Fail";

It shines when you are choosing between two values for an assignment. It becomes unreadable the moment you nest one ternary inside another.

Pro tip: If you cannot read a ternary aloud in one breath, convert it back to if-else. Code reviews at product companies routinely flag nested ternaries, so build the habit early: one condition, two values, nothing more.

The switch statement

When you compare a single variable against a list of fixed constants, switch reads better than a long else-if ladder:

public class WeekPlanner {
    public static void main(String[] args) {
        int day = 3;
        String type;

        switch (day) {
            case 1:
            case 7:
                type = "Weekend";
                break;
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
                type = "Weekday";
                break;
            default:
                type = "Invalid day";
        }
        System.out.println("Day " + day + " is a " + type);
    }
}

This prints Day 3 is a Weekday. Two details to notice. First, stacking case 1: and case 7: with no code between them deliberately groups those values — that is controlled fall-through. Second, every branch ends with break; without it, execution falls into the next case whether its label matches or not.

switch works on int (and the smaller integer types), char, enum and, since Java 7, String. It does not work on long, float, double or boolean. Switching on a String that is null throws a NullPointerException.

Interview note: "What happens if you forget break in a switch?" is a standard fresher question. The answer: execution falls through into the following cases until it hits a break or the switch ends. Follow-up they expect you to know — the default case can appear anywhere in the switch, not only at the end, though the end is the convention.

Switch expressions (Java 14 and later)

Classic switch has two chronic problems: forgotten break statements and the boilerplate of assigning the same variable in every branch. Switch expressions, standard since Java 14, fix both. The arrow syntax never falls through, and the whole switch produces a value:

public class WeekPlannerModern {
    public static void main(String[] args) {
        int day = 6;

        String type = switch (day) {
            case 1, 7 -> "Weekend";
            case 2, 3, 4, 5, 6 -> "Weekday";
            default -> "Invalid day";
        };
        System.out.println("Day " + day + " is a " + type);
    }
}

Multiple labels sit on one line separated by commas, there is no break, and the result is assigned directly to type. If a branch needs several statements, wrap them in braces and use yield to return the value. The compiler also enforces exhaustiveness: when you switch over an enum and cover every constant, you can even drop default.

If you are preparing for interviews in 2026, learn both forms. Codebases still contain years of classic switch, but new code — and newer interview questions — increasingly use the expression form, especially combined with pattern matching in recent Java versions.

if-else vs switch: how to choose

Situation Use
Range checks (marks >= 75) if-else
Compound conditions (age > 18 && hasId) if-else
One variable vs many fixed constants switch
Mapping an enum or command string to an action switch expression
Two-way value assignment ternary

A practical rule: three or more else if branches that all compare the same variable against constants is a signal to switch to switch. Conditions involving ranges, multiple variables or method calls belong in if-else.

Performance is rarely a reason to choose. For a handful of branches the difference is negligible; correctness and readability should drive the decision, and the type of the value you are testing usually makes the choice for you — check the Java data types guide if you are unsure what a variable's type allows.

Where to go next

Control statements plus loops form the core of program logic, and almost every coding round for freshers tests them together — printing patterns, grading logic, menu-driven programs. Move on to the loops guide next, then practise combining both with arrays. If you want to learn this in a structured, mentor-led way with daily coding practice, that is exactly how we begin the Java Full Stack course at CodeBegun in Hyderabad: decisions and loops in week one, applied to small real programs from day one.

Frequently Asked Questions

What are the types of control statements in Java?
Java has three groups: decision-making statements (if, if-else, switch), looping statements (for, while, do-while) and jump statements (break, continue, return). Decision-making statements choose between paths, loops repeat work and jump statements transfer control.
What is the difference between if-else and switch in Java?
if-else can test any boolean condition, including ranges and compound logic. switch compares one variable against fixed constant values such as int, String or enum cases. Use switch when you match a single value against many known constants, and if-else for everything else.
Can we use a String in a switch statement?
Yes, String is supported in switch since Java 7. The comparison uses the equals method internally, so it is case-sensitive. Passing a null String to a switch throws a NullPointerException, which is a common interview follow-up.
What is fall-through in a switch statement?
Fall-through happens when a case block has no break statement, so execution continues into the next case. It is occasionally useful for grouping cases, but it is usually a bug. Switch expressions with the arrow syntax do not fall through at all.
What is a switch expression in Java?
A switch expression, standard since Java 14, is a form of switch that produces a value you can assign to a variable. It uses the arrow syntax, needs no break statements, and the compiler forces you to cover all possible cases, which makes it safer than a classic switch.
When should I use the ternary operator instead of if-else?
Use the ternary operator for a simple two-way choice that assigns a value, like picking the larger of two numbers. If the logic needs multiple conditions, side effects or nesting, a plain if-else block is easier to read and debug.

Want to Build Your Career in Java Full Stack with AI?

Join CodeBegun and train with working industry engineers — Explore the Program

Apply for Demo Class →
Siva Prasad Galaba
Founder, CodeBegun · Staff Engineer

Founder of CodeBegun. 15+ years building Java systems at companies like Crunchyroll. Teaches Java, Spring Boot and system design the way the industry actually works, and mentors students through projects, mock interviews and placement preparation.

Technically reviewed by CodeBegun Technical TeamLast reviewed 14 July 2026 LinkedIn
Chat with us