Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Java Dictionary

  1. Home
  2. Java Dictionary
  3. if / else if / else (Java)

if / else if / else (Java)

The fundamental syntax for conditional branching. Use if to define a block that executes when a condition is true, else if to add additional conditions, and else to handle the case where none of the conditions match.

Syntax

// Basic if statement
if (condition) {
    // Executed when condition is true
}

// if / else if / else
if (condition1) {
    // Executed when condition1 is true
} else if (condition2) {
    // Executed when condition1 is false and condition2 is true
} else {
    // Executed when all conditions are false
}

// Nested conditional branching
if (conditionA) {
    if (conditionB) {
        // Executed when both conditionA and conditionB are true
    }
}

Common Operators Used in Conditions

OperatorMeaningExample
==Equal to (value comparison for primitive types).hp == 0
!=Not equal to.level != 1
>Greater than.power > 9000
>=Greater than or equal to.power >= 9000
<Less than.hp < 0
<=Less than or equal to.hp <= 0
&&AND (logical AND). If the left operand is false, the right operand is not evaluated (short-circuit evaluation).hp > 0 && alive
||OR (logical OR). If the left operand is true, the right operand is not evaluated (short-circuit evaluation).isKing || isElite
!NOT (logical NOT).!isDefeated

Sample Code

IfElseBasic.java
public class IfElseBasic {
    public static void main(String[] args) {

        // --- Basic if / else if / else ---
        String name = "孫悟空";
        int power = 9000;

        if (power >= 10000) {
            System.out.println(name + " is a super warrior class.");
        } else if (power >= 5000) {
            System.out.println(name + " is an elite warrior class."); // This branch executes
        } else {
            System.out.println(name + " is a general warrior class.");
        }

        // --- Nested conditional branching ---
        boolean isSaiyan = true;
        boolean hasTail   = false;

        if (isSaiyan) {
            if (hasTail) {
                System.out.println(name + " can transform into a Great Ape.");
            } else {
                System.out.println(name + " is a Saiyan but has no tail."); // This branch executes
            }
        } else {
            System.out.println(name + " is not a Saiyan.");
        }

        // --- Early return pattern ---
        // Also known as a guard clause.
        // Rejecting invalid values early keeps nesting shallow.
        System.out.println(getStatusMessage("ベジータ", -1));
        System.out.println(getStatusMessage("フリーザ", 15000));
        System.out.println(getStatusMessage("クリリン", 1500));
    }

    // Method that uses early return to avoid deep nesting
    static String getStatusMessage(String name, int power) {
        if (power < 0) {
            return name + " has an invalid power value."; // Reject invalid input early
        }
        if (power >= 10000) {
            return name + " is a super elite warrior.";
        }
        if (power >= 5000) {
            return name + " is an elite warrior.";
        }
        return name + " is a general warrior."; // Fallback when no condition matches
    }
}
javac IfElseBasic.java
java IfElseBasic
孫悟空 is an elite warrior class.
孫悟空 is a Saiyan but has no tail.
ベジータ has an invalid power value.
フリーザ is a super elite warrior.
クリリン is a general warrior.

Ternary Operator (Conditional Operator)

The ternary operator (condition ? valueIfTrue : valueIfFalse) returns a value based on a condition in a single line. It is handy for variable initialization or inside a return statement.

TernaryDemo.java
public class TernaryDemo {
    public static void main(String[] args) {

        // Basic use of the ternary operator: assigning to a variable
        int power = 9000;
        String rank = (power >= 9000) ? "Elite warrior" : "General warrior";
        System.out.println("Rank: " + rank); // Elite warrior

        // Can also be used in a return statement
        System.out.println(getLabel("孫悟空", true));
        System.out.println(getLabel("クリリン", false));

        // Nested ternary operators become hard to read; if/else if may be clearer
        int hp = 3500;
        String status = (hp > 5000) ? "Excellent" : (hp > 1000) ? "Somewhat exhausted" : "Near death";
        System.out.println("Status: " + status); // Somewhat exhausted
    }

    static String getLabel(String name, boolean isSaiyan) {
        return name + " is a " + (isSaiyan ? "Saiyan" : "Earthling") + ".";
    }
}
javac TernaryDemo.java
java TernaryDemo
Rank: Elite warrior
孫悟空 is a Saiyan.
クリリン is a Earthling.
Status: Somewhat exhausted

if vs. switch: When to Use Each

if / else if can handle any condition (range comparisons, combinations of multiple variables, etc.). switch, on the other hand, becomes more readable when matching the value of a single variable against multiple cases.

Comparisonif / else ifswitch
Condition flexibilityAny condition expression (ranges, multiple variables, etc.)Matching one variable against constant values
Supported typesAny expression returning booleanint, char, String, enum, etc.
Fall-throughNoneYes (forgetting break flows into the next case)
ReadabilityClearer when conditions are complexEasier to organize when there are many cases
SwitchComparison.java
public class SwitchComparison {
    public static void main(String[] args) {

        // Example of branching by rank with if / else if
        int power = 8500;
        String rankByIf;
        if (power >= 10000) {
            rankByIf = "Super elite";
        } else if (power >= 7000) {
            rankByIf = "Elite";
        } else if (power >= 4000) {
            rankByIf = "Mid-level warrior";
        } else {
            rankByIf = "General warrior";
        }
        System.out.println("if version: " + rankByIf); // Elite

        // switch can be more readable for matching a single variable
        // Java 14+ also supports switch expressions (-> syntax)
        String planet = "ベジータ星";
        switch (planet) {
            case "地球":
                System.out.println("A warrior from Earth.");
                break;
            case "ベジータ星":
                System.out.println("From the Saiyan homeworld.");
                break;
            case "ナメック星":
                System.out.println("A Namekian.");
                break;
            default:
                System.out.println("Home planet unknown.");
                break;
        }
    }
}
javac SwitchComparison.java
java SwitchComparison
if version: Elite
From the Saiyan homeworld.

Common Mistake 1: Comparing strings with ==

== compares reference identity. String literals often refer to the same object, so == may return true for them, but for strings created with new String(...) or returned from a method, == returns false even when the contents are the same.

StringEqNg.java
public class StringEqNg {
    public static void main(String[] args) {
        String name1 = new String("ベジータ");
        String name2 = new String("ベジータ");

        // == compares reference identity, so this returns false
        if (name1 == name2) {
            System.out.println("Same character.");
        } else {
            System.out.println("Different characters."); // This branch executes (unintended result)
        }
    }
}
javac StringEqNg.java
java StringEqNg
Different characters.

Use .equals() to compare string contents. If null is possible, use the form "constant".equals(variable), or use Objects.equals().

StringEqOk.java
public class StringEqOk {
    public static void main(String[] args) {
        String name1 = new String("ベジータ");
        String name2 = new String("ベジータ");

        // equals() compares the sequence of characters (contents)
        if (name1.equals(name2)) {
            System.out.println("Same character."); // This branch executes
        } else {
            System.out.println("Different characters.");
        }
    }
}
javac StringEqOk.java
java StringEqOk
Same character.

Common Mistake 2: Null reference with the Boolean wrapper type

The Boolean wrapper class can hold null. Passing a null Boolean as a condition triggers unboxing and throws a NullPointerException.

BooleanNullNg.java
public class BooleanNullNg {
    public static void main(String[] args) {
        Boolean isTransformed = null; // Transformation info not yet retrieved

        // Unboxing null throws NullPointerException
        if (isTransformed) { // ← NullPointerException
            System.out.println("Already transformed.");
        }
    }
}
javac BooleanNullNg.java
java BooleanNullNg
Exception in thread "main" java.lang.NullPointerException

The primitive boolean cannot hold null. When a wrapper type is required, perform a null check first.

BooleanNullOk.java
public class BooleanNullOk {
    public static void main(String[] args) {
        Boolean isTransformed = null; // Transformation info not yet retrieved

        // Checking for null first prevents NullPointerException
        if (Boolean.TRUE.equals(isTransformed)) {
            System.out.println("Already transformed.");
        } else {
            System.out.println("Transformation info is unknown or not transformed."); // This branch executes
        }
    }
}
javac BooleanNullOk.java
java BooleanNullOk
Transformation info is unknown or not transformed.

Notes

Conditions use either the primitive type boolean or the wrapper class Boolean. When a Boolean object is used as a condition, a NullPointerException is thrown if its value is null. Because the primitive boolean cannot hold null, it is commonly used in situations where null cannot occur.

To compare string values, use .equals() instead of ==. Because == compares reference identity, it returns false for two strings with the same contents if they are different objects. When null is possible, use the form "constant".equals(variable), or take advantage of Objects.equals().

When nesting becomes deep, using early return (guard clauses) to reject conditions upfront leads to more readable code. For multi-way branching, switch statements and switch expressions are also effective. For exception handling, see try / catch / finally.

If you find any errors or copyright issues, please .