Chapter 3 - Java for Beginners Course

If-Then-Else Statement

A second common case is when a given condition is true, we want to execute a certain block of code (same as before), but also want to execute some other block of code when the condition is false. The if-then-else statement allows us to do this and its syntax looks as follows:

if (boolean condition is true) {
	// then execute this block of code
} else {
	// execute this block of code if the condition is false
}

For example:

int age = 19;
double discount = 1d;

if (age < 18) {
    discount = 0.5d;
    System.out.println("The age is under 18");
} else {
    discount = 0d;
    System.out.println("The age is 18 or over");
}

System.out.println("The discount to use is: " + discount);

Output:

The age is 18 or over
The discount to use is: 0.0

Analysing the if-else statement example

In this case, the age variable has a value of 19, hence the condition in the if statement (age < 18) is false. This means that the first block of code won’t be executed.

However, because we have an else statement, the block of code after it will be executed, and as a result the message The age is 18 or over is printed out and the discount variable is given a value of 0.