If Statement

Now that we’ve covered many different types of conditional constructs, let’s dive right in and see how they can be used in Java.

First, let’s look at the if statement. In Java, the syntax for an if statement is shown below:

if (<Boolean expression>) {
    <true block>
}

As expected, Java will first evaluate the <Boolean expression> to a single Boolean value. If that value is true, it will execute the instructions in the <true block>, which can be one or more lines of code, or even additional constructs as we’ll see later. If that value is false, then the program will simply skip over the <true block> and continue executing the code immediately below the if statement.

It is very important to remember that the Boolean expression is enclosed by parentheses ( ), while the block of code that should be executed if that expression is true is enclosed by curly braces { }, just like a class body or method body.

Let’s take a look at a few code examples, just to see how this construct works in practice. First, let’s consider the program represented by this flowchart from earlier in the chapter:

If-Then Flowchart If-Then Flowchart

This flowchart corresponds to the following code in Java. In this case, we’ll assume x is hard-coded for now:

int x = 1;
if (x > 0) {
    System.out.println(x);
}
System.out.println("Goodbye");

As we can see, this program uses x > 0 as the Boolean expression inside of the if statement. If it is true, then it will output the value of x. So, it is very simple to write code that matches the execution paths shown in a flowchart representing the program.

Here’s one more example. Let’s assume we’d like to write a program that will calculate both the sum and product of two variables, x and y, but only if they are both greater than 0. That program may look like this:

int x = 5;
int y = 7;
if ((x > 0) && (y > 0)) {
    int sum = x + y;
    int product = x * y;
    System.out.println("Sum: " + sum);
    System.out.println("Product: " + product);
}

As we can see, we can create more complex Boolean statements using the various Boolean operators we’ve already learned. In addition, we can include multiple lines of code inside the curly braces.