The If else statement

The if-else statement is much similar to the simple if statement, but here we have else part for the if statement. If the condition of if statement evaluated as “false” then statements written inside the else part will be executed.

Syntax

if (<condition>) {
    //code to be executed if the condition is "true"
} else {
    //code to be executed if the condition is "false"
}

Example

In this program, we are going to check if the user’s given number is an “even” or “odd” number.

import java.util.Scanner;

public class IfElseExample {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter an integer : ");
        int number = scanner.nextInt();

        if (number % 2 == 0) {
            System.out.println(number + " is even number.");
        } else {
            System.out.println(number + " is odd number.");
        }

    }
}

Flow diagram

Flow-diagram of the above example program –