Shiklo Programming
EN
  • English
  • Español
  • Português
  • Deutsch
  • Français
  • 日本語
  • हिन्दी

Java If ... Else

Programs become useful when they can make decisions: give a discount only to members, print a grade that depends on the marks, stop a game when the lives run out. In Java a decision is written with if, optionally followed by else if branches and an else branch. The condition is always a boolean expression.

if and else

if is followed by a condition in brackets and a block in curly brackets. When the condition is true, the block runs. Otherwise the else block runs, if there is one:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Your age: ");
        int age = in.nextInt();
        if (age >= 18) {
            System.out.println("You can vote.");
        } else {
            System.out.println("You can vote in " + (18 - age) + " years.");
        }
        System.out.println("Thank you.");
    }
}
You type
15
Output
Your age: You can vote in 3 years.
Thank you.

The last line is outside both blocks, so it always runs. The input is read with Scanner, as in User Input.

Several branches with else if

When there are more than two cases, add else if branches. Java checks the conditions from the top and runs only the first block whose condition is true:

public class Main {
    public static void main(String[] args) {
        int marks = 82;
        char grade;
        if (marks >= 90) {
            grade = 'A';
        } else if (marks >= 75) {
            grade = 'B';
        } else if (marks >= 60) {
            grade = 'C';
        } else {
            grade = 'F';
        }
        System.out.println("Grade: " + grade);
    }
}
Output
Grade: B

Because the checks go from the top, marks >= 75 does not need && marks < 90: if the marks had been 90 or more, the first branch would already have been taken.

Nested and combined conditions

A block can contain another if. Often, though, && and || express the same idea more simply:

public class Main {
    public static void main(String[] args) {
        int temperature = 24;
        boolean raining = true;
        if (temperature > 20) {
            if (raining) {
                System.out.println("Warm, but take an umbrella.");
            } else {
                System.out.println("A lovely day.");
            }
        }
        if (temperature > 20 && !raining) {
            System.out.println("Go to the park.");
        }
    }
}
Output
Warm, but take an umbrella.

When a block has only one statement, Java allows you to leave out the curly brackets. It is safer to always write them: adding a second line later then cannot change the meaning by accident.

The ternary operator

For a simple choice between two values, Java has a short form: condition ? valueIfTrue : valueIfFalse.

public class Main {
    public static void main(String[] args) {
        int n = 7;
        String kind = (n % 2 == 0) ? "even" : "odd";
        System.out.println(n + " is " + kind);
        int a = 12, b = 30;
        System.out.println("Larger: " + (a > b ? a : b));
    }
}
Output
7 is odd
Larger: 30

Use it for short choices only; for anything longer, a normal if ... else is clearer.

Practice exercises

  1. Ask for a number and print whether it is positive, negative or zero.
  2. Ask for a year and print whether it is a leap year.
  3. Ask for the price of a purchase: give 10 percent off above 1000 and 20 percent off above 5000, and print the final price.