Thus far, we have been building some basic programs. However, the further we delve into Java, the more we find that in order to build more extensive programs, that we will need to start implementing conditional statements.
The best way to describe the usage of conditional statements is that they are statements that are only executed under the prescribed condition. One of the most basic conditional statements in Java is the if statement (or sometimes known as the if-then statement). Let us look at the skeleton code below to better understand how they work.
There are three things we need in order to write the outline of an if statement.
- The reserved word
- A set of parentheses immediately following the
- A set of brackets after the parenthesis.
As you can guess, the word
if declares that it is a conditional if statement. The set of parentheses is the conditional statement that returns a Boolean answer – true or false. This Boolean answer must be equal to the if statement’s criteria for the code in between the brackets to execute. Lets look at an actual if statement now.
Looking at the Java program above, we notice that we are using a Boolean value as our conditional if statement. In pseudocode, our if statement translates to: if hasCoffee is true, then print “I am happy” .
Also, notice how there are two equal signs in our if statement? This is what is known as an Equality Operator. The equality operator
== is essentially used to ask the computer if the two values on either side of the operator are equal to each other and will return either a true or false.
Remember that one
= sign is used to assign value to a variable, and the
== is used to return a true/false value on whether two variables are equal to each other.
Now that we know what a equality operator is, lets go over an even simpler way that we can use boolean values within our if statements.
In Java, if we put the name/identifier of a boolean value within the parenthesis of an if statement, Java will assume that we only want the to execute the if statement when the boolean value is true. So the if statement below works exactly the same as the if statement shown above with the equality operator:
Now that we know the basics of using boolean values within our if statements, let us look at what would happen if the Boolean variable
hasCoffee = false. Lets look at the example below.
Can you guess what the output is for the code above? There is no output! That is because our conditional if statement does not equal true. Therefore, all the code enclosed within our if statement is skipped over.
In the next lesson, we will go over some more examples of different if statements and equality operators that are associated with them. If you don’t understand everything quite yet, don’t worry. We will continue to see more examples in the upcoming lessons.