If Else statements

Whenever we create an if statement, we verify if something is true, and the only alternative to it being true is for it to be false.

If we also need to carry out some action if a value is false, we could create two if statements - one to check if it is true, and another to check if it is false (though the if statement is essentially still looking for a true value - something that is 'not false' is by definition true) as follows:

if (isRaining) {
    //take umbrella
}
    
if (!isRaining) {
    //leave umbrella at home    
}

This requires us to make two checks, wheras it would be easier to make the first check, and have some sort of statement to handle if the check isn't met with a true value, in programming this is known as an else statement, and it can only be used subsequently to an if statement. The version of the code above that uses an else statement would appear as follows:

if (isRaining) {
    //take umbrella
} else {
    //leave umbrealla at home
}
Just like the code that runs if the if statement is true, the else statement code is also placed inside a pair of braces.

Task

Take the code from the life expectancy task on the If statement tutorial, and modify it to use an else statement. verify the code works correctly

If statement scope

Sometimes we may do quite a lot of work inside an if statement, which could include variables. It is imperative to be aware that variables created inside the body of an if, or else statement cannot be used outside of the if or else statement. The following code, therefore, is invalid:

if (teamPlaying) {
    int playersOnPitch = 22;
}
//the next line will be an error
int averagePlayersPerTeam = playersOnPitch / 2;
In the above example, on the final when we try and use playersOnPitch, an error will be flagged in the IDE because the variable is 'out of scope'. The error displayed by the IntelliJ would be Cannot resolve symbol 'playersOnPitch'

If we think about this, players on pitch would only exist if the teamPlaying boolean were true, so we cannot rely on it existing after the if statement. If we need to use the variable, we must create it before the if statement as follows:

int playersOnPitch = 0;
if (teamPlaying) {
    playersOnPitch = 22;
}

int averagePlayersPerTeam = playersOnPitch / 2;
A general rule of thumb is that variables declared inside a set of braces cannot be accessed outside those braces. A set of braces and the code it contains is commonly known as a 'block'.

Nesting if statements

We can place if statements inside other if statements, to carry out additional checks, consider the following example where you are looking to find someone in a small house:

if (isInHouse) {
    if (isOnGroundFloor) {
        if (isInKitchen) {
            System.out.println("Found In Kitchen");
        } else {
            System.out.println("Must be in lounge/diner");
        }
    } else {
        System.out.println("Must be upstairs");
    }
} else {
    System.out.println("Must be in garden");
}

Such nested if statements are often hard to read. By placing the opening brackets on a new line, so they balance with their closing brace can aid readability, as follows:

if (isInHouse) 
{
    if (isOnGroundFloor) 
    {
        if (isInKitchen) 
        {
            System.out.println("Found In Kitchen");
        } 
        else 
        {
            System.out.println("Must be in lounge/diner");
        }
    } 
    else 
    {
        System.out.println("Must be upstairs");
    }
} 
else 
{
    System.out.println("Must be in garden");
}
Whilst the developer would need to shift brackets to a new line, most IDEs will automatically indent code to the correct position (provided all opening braces have a matching closing brace), in IntelliJ they keyboard shortcut is ⌘ + ⌥ + L (Cmd, Alt, L) on Mac and Ctrl + Alt + L on PC / Linux

Else - If statements

Sometimes we may want to carry out an additional check only if a statement has not been met, and this can be done using else - if syntax. Consider the following example where you are looking to find someone in a larger house than the above example:

if (isOnGroundFloor)
{
    if (isInKitchen)
    {
        System.out.println("Found In Kitchen");
    }
    else if (isInDiningRoom)
    {
        System.out.println("Found in Dining room");
    }
    else if (isInConservatory)
    {
        System.out.println("Found in Conservatory");
    }
    else if (isInStudy)
    {
        System.out.println("Found in Study");
    }
}
else
{
    System.out.println("Must be upstairs");
}
In the same way you wouldn't continue to look for someone after you found them, in each case in the above code, a subsequent else ifstatement is only evaluated if the person is not found