JB Header

Java if, else if and else Statements with Examples

Introduction Until now, our programs have run every statement from top to bottom. Real programs need to make decisions - charge shipping only below a certain order value, or print a different message for each grade. This tutorial explains Java's if, else if and else statements with examples. We will start with the simple if statement, and add an else branch. We will then choose between many options with an else if ladder, and put if statements inside each other. Lastly, we will look at the most common mistakes with if statements, and at guard clauses, which keep decision-making code readable.

(Note - Conditions are built from the relational and logical operators covered in Arithmetic, Relational and Logical OperatorsClick to read tutorial: Java Arithmetic, Relational and Logical Operators.) The if statement Syntax of the if statement
if (condition) { statements }
Where,
  • condition must be a boolean expression, in parentheses. Unlike in C or JavaScript, a number is not accepted - if (count) does not compile in Java.
  • If the condition is true, the statements in the block run. If it is false, they are skipped, and the program carries on after the block.
A simple if statement
//FreeShipping.java
public class FreeShipping {
  public static void main(String[] args) {
    double orderTotal = 42.50;
    double shipping = 4.99;

    if (orderTotal >= 50) {
      shipping = 0;
      System.out.println("You qualify for free shipping!");
    }
    System.out.println("Order: " + orderTotal + ", shipping: " + shipping);
  }
}
 OUTPUT of the above code
Order: 42.5, shipping: 4.99
The order total is below 50, so the condition is false, the block is skipped, and shipping stays at 4.99. The if-else statement An else block gives the alternative - it runs when the condition is false. Exactly one of the two blocks always runs.
An if-else statement
//EvenOdd.java
public class EvenOdd {
  public static void main(String[] args) {
    int[] numbers = {7, 12};
    for (int n : numbers) {
      if (n % 2 == 0) {
        System.out.println(n + " is even");
      } else {
        System.out.println(n + " is odd");
      }
    }
  }
}
 OUTPUT of the above code
7 is odd
12 is even
Note - When an if-else only chooses between two values for one variable, the ternary operatorClick to read tutorial: Java Assignment, Increment/Decrement and Ternary Operators is often shorter: String kind = n % 2 == 0 ? "even" : "odd";.
The else if ladder To choose between more than two options, chain conditions with else if. The conditions are checked from top to bottom, and only the block of the first true condition runs - the rest are skipped. The final else, which is optional, runs if none of the conditions is true.
An else if ladder
//GradeCalculator.java
public class GradeCalculator {
  static String grade(int marks) {
    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 = "F";
    }
    return grade;
  }

  public static void main(String[] args) {
    int[] allMarks = {95, 75, 61, 40, 12};
    for (int marks : allMarks) {
      System.out.println(marks + " -> " + grade(marks));
    }
  }
}
 OUTPUT of the above code
95 -> A
75 -> B
61 -> C
40 -> D
12 -> F
Explanation of the code
  • For 95, the first condition is true, so the grade is A and no other condition is checked - even though 95 is also above 75, 60 and 40.
  • Because the first match wins, the order of the conditions matters. Checking marks >= 40 first would give every pass a D. Order the checks from the most specific to the least.
  • The compiler knows that one of the branches always assigns grade, because the ladder ends with an else. Without the final else, return grade; would be a "might not have been initialized" error.
Nested if statements An if statement can contain other if statements, when one decision depends on another.
Nested if statements
//TicketPrice.java
public class TicketPrice {
  static double price(int age, boolean isWeekend) {
    double price;
    if (age < 12) {
      price = 5;
    } else {
      if (isWeekend) {
        price = 15;
      } else {
        price = 12;
      }
    }
    return price;
  }

  public static void main(String[] args) {
    System.out.println("Child, weekday : " + price(8, false));
    System.out.println("Adult, weekday : " + price(30, false));
    System.out.println("Adult, weekend : " + price(30, true));
  }
}
 OUTPUT of the above code
Child, weekday : 5.0
Adult, weekday : 12.0
Adult, weekend : 15.0
Nesting more than two or three levels deep makes code hard to follow. Combining conditions with &&, using an else if ladder, or using guard clauses (below) usually reads better.
Common mistakes with if statements 1. Leaving out the braces. If the braces are left out, if controls only the one statement that follows it - however the code is indented.
Indentation does not create a block
//MissingBraces.java
public class MissingBraces {
  public static void main(String[] args) {
    int stock = 10;
    if (stock == 0)
      System.out.println("Out of stock!");
      System.out.println("Please order again later.");   // always runs!
    System.out.println("Stock: " + stock);
  }
}
 OUTPUT of the above code
Please order again later.
Stock: 10
The second message was printed although the item is in stock, because only the first println() belongs to the if. Always use braces, even for a single statement.

2. A semicolon after the condition. if (stock == 0); ends the if with an empty statement, so the block after it runs every time.

3. The dangling else. Without braces, an else belongs to the nearest if, which may not be the one its indentation suggests. Braces remove the doubt.

4. = instead of ==. Writing if (count = 0) is a compile error in Java, because the result is an int, not a boolean. With boolean variables, however, if (done = true) compiles - and assigns true. Write if (done) and if (!done) instead of comparing booleans with ==.

5. Comparing strings with ==. Use name.equals("Tom"), not name == "Tom". See == vs equals()Click to read tutorial: Java String Comparison: == vs equals() vs compareTo(). Guard clauses - return early When a method has to check several conditions before doing its real work, deep nesting can be avoided by handling the special cases first and returning early. These early checks are called guard clauses.
Guard clauses instead of nested ifs
//Withdrawal.java
public class Withdrawal {
  static String withdraw(double balance, double amount) {
    if (amount <= 0) {
      return "Rejected: amount must be positive";
    }
    if (amount > balance) {
      return "Rejected: insufficient funds";
    }
    if (amount > 1000) {
      return "Rejected: daily limit is 1000";
    }
    return "Approved: new balance " + (balance - amount);
  }

  public static void main(String[] args) {
    System.out.println(withdraw(500, -20));
    System.out.println(withdraw(500, 800));
    System.out.println(withdraw(5000, 1500));
    System.out.println(withdraw(500, 120));
  }
}
 OUTPUT of the above code
Rejected: amount must be positive
Rejected: insufficient funds
Rejected: daily limit is 1000
Approved: new balance 380.0
Each rule is a flat, separate if, and the normal case - the approval - sits at the end without any nesting. Methods and return are covered in Java MethodsClick to read tutorial: Java Methods: Defining, Calling and Returning Values. Summary In this tutorial we first used the if statement to run a block only when a condition is true, and added an else block for the alternative. We then chose between many options with an else if ladder, where the first true condition wins and the order of the checks matters. Next we nested if statements, and went through the most common mistakes - missing braces, a stray semicolon, the dangling else, = instead of ==, and comparing strings with ==. Lastly, we used guard clauses to keep decision-making code flat and readable. In the next tutorial, we will choose between many fixed values with the switch statementClick to read tutorial: Java switch Statement Tutorial with Examples.