Chapter 3 - Java for Beginners Course

If-Then Statement

In different occasions we’ll need a way to conditionally execute a block of code, this is, only when a certain boolean expression evaluates to true. The if-then statement allows us to do exactly that.

if (boolean condition is true) {
	// then execute this block of code

The block of code (delimited by the braces { …​ }) next to the if statement won’t be executed if the condition evaluates to false.

The above code reads: "if the boolean condition is true, then execute the block of code."

The code in the example below is deciding whether or not to execute blocks of code depending on the age variable:

int age = 17;
double discount = 0d;

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

if (age >= 18) {
    discount = 0d;
    System.out.println("The age is 18 or over");

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


The age is under 18
The discount to use is: 0.5

Analysing the first if statement

In the first if statement in our example, we’re checking if the age variable has a value of less than 18 (age < 18). In our case, this is true as the age variable has a value of 17.

Given that the condition is true, the block of code inside is executed, in our case, this means that:

  1. The discount variable is set to to a value of 0.5d.

  2. The message The age is under 18 is printed out to the console.

Analysing the second if statement

In the second if statement, we’re checking the opposite of the first one, this means, we’re checking if the age variable has a value of 18 or higher (age >= 18). In our case, this is false, and hence, the block of code of the second if statement isn’t executed.

This means, that the discount variable keeps the value it had, in our case 0.5d, and that the message The age is 18 or over isn’t printed out.

This example is overly simplistic, but is meant to cover the syntax and illustrate the way the if-then statement works.
Try running the example code by changing the value of the age variable and see what results you get. We’ll use a similar approach in the next sections of chapter 3.