1.4.9 How to Write an If Statement

If Statements (or conditional statements) are used to make decisions within code. There are many instances where a certain method or line of code should only run under certain circumstances. Thought about in daily life, this can be as simple as saying: if it's raining...grab an umbrella. You wouldn't want to grab an umbrella during every weather condition.

If Statement Structure and Execution

Let's say we have a person that has the method shown below that takes an amount and then removes whatever the amount is from their MoneyBalance.

Now say the value of amount is 3,000.00 and the MoneyBalance is 10.00. Whoever is buying this thing is going to be massively in debt.

We can avoid that, however, by introducing an 'If' statement. To define an if statement it will be: if (some conditional check) {the code that will execute if true}

In this case we want to make sure the amount is less than or equal to the MoneyBalance the person has so we will 'wrap' the line of code that removes the amount from the MoneyBalance in an if statement.

Now we can see that when our code runs the MoneyBalance will not be changed because the amount parameter isn't less than or equal to 10. The conditional statement evaluates to false and the code wrapped in the if statement will not execute.

However, let's say the amount is 2.

Now the conditional statement will evaluate to true and the code wrapped in the if statement will execute.

Code Outside of an If Statement

A method can do many things. With that in mind, it sometimes doesn't make sense to put all lines of code inside an if statement. Sometimes you want the method to do something even if the if statement evaluates to false.

For example, let's assume the person buying something is doing so from a real person. Even if they didn't have enough money they would be polite and thank them for their time. If we put the call to ThankCashier inside the If Statement...

The only time they would thank the cashier is if they had enough money. We don't want them to be rude, though, so we will place the call to ThankCashier outside of the if statement to ensure it is called every time they buy something no matter if they can or not.

Multiple Lines of Code Inside an If Statement

Many times there won't be just one line of code in an if statement. Sometimes we don't want to do multiple things if a conditional is false.

For example, if the person doesn't have enough money we don't want them to remove money or pay the cashier. We also don't want multiple if statements for the same thing.

Instead, we can wrap all of those lines of code into a single if statement.

Now all the code inside the if statement will either get executed or it won't.