In the last lesson we were introduced to if statements and how they are implemented in Java.  In this lesson, we will be going over a more advanced version of the if statement.  This statement will be referred to as the if else statement.  This applies everything we learned in the lesson prior and adds an else statement.

It is important to note that the else statement can only be used with an accompanying if statement and is only executed if the accompanying if statement does not evaluate to true.   Also, because the else statement executes if the accompanying if statement does not equal to true, there is no need for creating a condition within parentheses.

In order to better understand the if else statement, let’s look at an example in order to better understand how it works.

In the example above, we notice that the if statement will not execute because the Boolean variable is set to false.  Consequently, this means that the following else statement will execute. 

So when we run our code, we understand why we get the following result:

However, if we were to set boolean hasCoffee = true , then we would execute the if statement because the conditional statement would evaluate to true.  Look at the modified code below and its accompanying output.

Also, remember the equality operator symbol == and how it is used to pose the question to the computer whether or not a value on the left side of the operand is equal to the operand on the right side. Whereas, if we use one = sign, we are assigning a value to a variable.

To summarize this lesson, let’s look at some pseudo code to cement the idea:

if(condition){ if the condition above evaluates to true, execute the code within these brackets }

else { execute the code within these brackets if the if statement above did not evaluate to true }

If you are still having trouble understanding the concept, try playing with the code above and changing the values until you see the connection between the two.  In the next lesson, we will learn about else-if statements!

GitHub link.