This book is now obsolete Please use CSAwesome instead.

5.1. Conditionals

Java statements normally execute one at a time from top to bottom. If you want a statement to only execute when something is true use a conditional. Something that can only be true or false is called a Boolean. If the condition is true then the next statement or a block of statements will execute. If the condition is false then the next statement or block of statements is skipped.

../_images/Condition.png

Figure 1: The order that statements execute in a conditional

Note

A conditional uses the keyword if followed by Boolean expression inside of an open parenthesis ( and a close parenthesis ) and then followed by a single statement or block of statements. The single statement or block of statements are only executed if the condition is true. A block of statements is enclosed by an open curly brace { and a close curly brace }.

Imagine that your cell phone wanted to remind you to take an umbrella if it was currently raining in your area when it detected that you were leaving the house. This type of thing is going to become more common in the future and it is an area of research called Human Computer Interaction (HCI) or Ubiquitous Computing (computers are everywhere).

The variable isRaining is a boolean variable that is either true or false. If it is true then the message Take an umbrella! will be printed and then execution will continue with the next statement which will print Drive carefully. Run the code above to see this.

What if you want to pick between two possibilities? If you are trying to decide between a couple of things to do, you might do one thing if a coin flip is heads and another if it is tails. In this case use the if keyword followed by a statement or block of statements and then the else keyword also followed by a statement or block of statements.

../_images/Condition-two.png

Figure 2: The order that statements execute in a conditional with 2 options: if and else

Note

The else will only execute if the condition is false.

If isHeads is true it will print Let's go to the game and then after conditional. Run the code above to see this.

Note

An if will only execute one single statement following it unless there is a block of statements enclosed in a pair of open and closed curly braces { and }. Java doesn’t care if you indent the code to show what you intend!

The code below doesn’t work as expected. Fix it to only print “Wear a coat” and “Wear gloves” when isCold is true.

Check your understanding

You have attempted of activities on this page