Control Statements in Java with Examples: If, If-Else and Switch Statement

Control statements in Java allow a program to make decisions and execute different blocks of code based on given conditions. Instead of running every line sequentially, control statements let your program choose a path depending on the situation.

if Statement

The simplest control statement — executes a block of code only if the given condition evaluates to true.

int age = 20;
if (age >= 18) {
    System.out.println("Eligible to vote");
}

if...else Statement

Adds an alternative block of code that runs when the condition is false.

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

if...else if...else Ladder

Used when there are multiple conditions to check in sequence, evaluating each else if until one is true.

int marks = 72;
if (marks >= 90) {
    System.out.println("Grade A");
} else if (marks >= 75) {
    System.out.println("Grade B");
} else if (marks >= 50) {
    System.out.println("Grade C");
} else {
    System.out.println("Fail");
}

Nested if Statement

An if statement placed inside another if statement, useful when a decision depends on more than one condition together.

switch Statement

Used to select one of many code blocks to execute based on the value of a single variable, offering a cleaner alternative to a long if...else if ladder.

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;
    default:
        System.out.println("Invalid day");
}

switch vs if...else

  • switch works best when checking a single variable against many fixed values
  • if...else is more flexible for complex or range-based conditions
  • Forgetting break in a switch case causes execution to "fall through" into the next case
Since Java 14, switch also supports a newer arrow syntax (case 1 -> ...) that removes the need for break statements entirely.

Master Java with Uncodemy

Hands-on training, live projects, and placement support in our Java Programming Course.

Explore the Course