TExcelTAD
Home › Java › Java If..Else

Java If..Else

Conditional statements let a program make decisions: run one block of code when a condition is true, and optionally another block when it's false.

Statement Use it to
if run code only when a condition is true
else run code when the if condition is false
else if test another condition if the previous one was false
? : choose between two values in one expression
switch pick one of many branches (next chapter)

if

The condition goes in parentheses and must be a boolean expression:

java · try it yourself
class Main {
    public static void main(String[] args) {
        int battery = 15;
        if (battery < 20) {
            System.out.println("Battery low - please charge");
        }
        System.out.println("Done checking");
    }
}
Battery low - please charge
Done checking

else

java · try it yourself
class Main {
    public static void main(String[] args) {
        int hour = 20;
        if (hour < 18) {
            System.out.println("Good day!");
        } else {
            System.out.println("Good evening!");
        }
    }
}
Good evening!

else if

Chain several conditions. Java checks them from top to bottom and runs only the first branch whose condition is true; the rest are skipped:

java · try it yourself
class Main {
    public static void main(String[] args) {
        int[] scores = {95, 82, 71, 40};
        for (int score : scores) {
            String grade;
            if (score >= 90) {
                grade = "A";
            } else if (score >= 80) {
                grade = "B";
            } else if (score >= 70) {
                grade = "C";
            } else {
                grade = "F";
            }
            System.out.println(score + " -> " + grade);
        }
    }
}
95 -> A
82 -> B
71 -> C
40 -> F

Order matters: if score >= 70 came first, 95 would also get a "C".

Note: The for loop here just repeats the check for each score. You'll learn loops in a few chapters.

Combining and nesting conditions

You can combine conditions with && and ||, or place an if inside another if:

java · try it yourself
class Main {
    public static void main(String[] args) {
        int age = 16;
        boolean withParent = true;

        if (age >= 18 || withParent) {
            System.out.println("You may enter.");
            if (age < 18) {
                System.out.println("Please stay with your parent.");
            }
        } else {
            System.out.println("Sorry, adults only.");
        }

        int year = 2024;
        boolean leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
        System.out.println(year + " is a leap year: " + leap);
    }
}
You may enter.
Please stay with your parent.
2024 is a leap year: true

Short-hand if...else (ternary)

When you only need to choose a value, the ternary operator is shorter:

java · try it yourself
class Main {
    public static void main(String[] args) {
        int items = 1;
        String text = items + (items == 1 ? " item" : " items");
        System.out.println(text);
        int n = -5;
        System.out.println(n >= 0 ? "non-negative" : "negative");
    }
}
1 item
negative

Braces are your friend

If an if has a single statement you may omit the braces, but this is a classic source of bugs: only the first statement belongs to the if.

java
if (balance < 0)
    System.out.println("Overdrawn!");
    sendWarningEmail();   // ALWAYS runs - the indentation lies

Always using { } avoids this trap entirely.

Test yourself

With int x = 7;, which branch runs? if (x > 10) A else if (x > 5) B else if (x > 0) C else D

  1. A
  2. B
  3. C
  4. B and C

Which of these is a valid condition in Java?

  1. if (x = 5)
  2. if (x)
  3. if (x == 5)
  4. if x == 5

What does String s = 3 > 2 ? "yes" : "no"; assign?

  1. "yes"
  2. "no"
  3. true
  4. 3