If...Else Statements

An if…else statement allows us to do one thing if a condition is true, and a different thing if the condition is not true.

If…else statement syntax

Here is the syntax of an if…else statement:

if (condition)
{
    // first set of statements
}
else
{
    //second set of statements
}

Here, we will check condition – if it is true, we will execute the first set of statements. If condition is false, we will execute the second set of statements. In any case, exactly one set of statements is executed.

If…else example

For example, suppose we want to print out whether a number is even or odd. We can tell if a number is even by checking to see if it is divisible by two (i.e, we can use the modulo operator, %, to see if the remainder of a number when dividing by two is 0).

Scanner s = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = s.nextInt();

//If the remainder of num/2 is 0, then num is even
if (num % 2 == 0) 
{
    System.out.printf("%d is even%n", num);
}
else 
{
    System.out.printf("%d is odd%n", num);
}

(Note: this is not a complete program. We would need to put this code inside a class declaration and inside the main method.) When this code is executed, it will first ask the user for a number, and store the result in the num variable. It will then compute num%2 (the remainder of num/2). If it is 0, then it will print that the number is even. If it is anything else, it will print that the number is odd. Each time, exactly one of the statements will be printed.