Java for Humans { Control Flow Statements: Decisions}

Lincoln W Daniel
Dec 19, 2015 · 6 min read
View Table of Contents | Download Supporting Code | Subscribe to ModernNerd Youtube Channel for Coding Videos | By Lincoln W Daniel

Decisions, decisions, decisions … Decisions are the concepts you had no control over as a baby. As you grew older, however, the world expected you to start making decisions for yourself. In school, you had to make a decision everyday to sit in the front or in the back of the room; if you sat in the back, you ran the risk of being less attentive, and if you sat in the front, you had a better chance of getting the excellent grade. When it’s raining, you have to make a decision to use an umbrella or not; if you use the umbrella, you stay dry, and if you don’t use the umbrella you get wet and sad.

Why Decisions are Important & Useful

In Java, your code is generally executed from top to bottom in order. Line one will be executed before line two, line three after line two, and line four before line five but definitely after line three. This is great when you are writing simple programs, but when it’s time for your programs to do more, your code will have to employ control flow statements to allow your program to do some things sometimes and other things when the time is write. One form of control flow statements are decision-making statements which allow us to tell our program to do Task A if a condition is true or Task B if it is not true: If it is raining, use the umbrella, otherwise, leave it in the closet.

Decision-Making Statements

If-Then Statements

If this is true, then do that.

If a certain condition is satisfied, then do something. You’ve been doing this for as long as you can remember. If you are hungry, you eat. If you are tired, you sleep. If your bank account is empty, you work hard to get more money. If you get a good grade, you pass the class. If you pass “Go” in Monopoly, collect 200 dollars. This is how the if-then statement, otherwise known as if statement, works:

//previous code runs//check a condition
if(condition) {
//body
//do something; run more code here
}
//other code runs

The condition could be a mathematical expression, a variable, or a method, but regardless of what it is, it must return, or evaluate to, a boolean value of true or false. If it the condition evaluates to true, we say that the condition is satisfied.

In that code snippet, some code runs, then we use a if statement to evaluate a condition. If the condition is satisfied, evaluates to true, we can do something inside the body of the if statement. Let’s try to model a turn in the game of Monopoly:

Player player1 = new Player("Lucy");
//the first player rolls the dice
int movePositions = player1.rollDice();

//player moves piece on game's board
player1.moveForward(movePositions);

if(player1.passedGo()) {
player1.collect200Dollars();
}

//next player rolls dice
movePositions = player2.rollDice();

//...

Note that the rollDice() instance method of the player class always returns a perfect roll of 12 and its moveForwad() instance method increases the instance’s position on the board by the number we provide it. Finally, its passedGo() instance method returns true if the player’s position on the board is greater than 11 and false otherwise. In the Generating Random Numbers chapter, we will learn how we can randomize the rollDice() method.

In that code snippet, the current player of the Monopoly board game rolls the dice to see how far he can move and moves his piece forward on the board accordingly. If the player passed “Go” he collects 200 dollars. After all of that, the next player gets to roll the dice, and the process repeats until the game ends.

If-Then-Else Statements

If-then-else statements are a little more powerful than simple if-then statements because they let us do things if a condition is satisfied and other things otherwise. You can think of it like so:

if this is true, then do that. Otherwise, do something else.

Let’s say we want to explore the Amazon rainforest. In planning, we check the weather forecast to see if it will be raining on the day we go. We only want to pack our umbrella in our bag if it will rain when we get there. If it’s not going to rain, we should put our umbrella back in our closet because we won’t need it. We can model our plans with if-then-else statements like so:

boolean itWillRain = true;//check if it will rain
if
(itWillRain) {
//pack the umbrella for the trip
System.out.println("Adding our umbrella to the bag.");
} else {
//put the umbrella back in the closet
System.out.println("Putting umbrella back in the closet.";
}

If the condition is satisfied, the body of the if statement will run, and the body of the else statement will run otherwise. Thus, if itWillRain evaluates to true, we add our umbrella to our bag — otherwise, if itWillRain evaluates to false, we put the umbrella back in the closet.

Nesting Decisions

Java allows you to nest decision-statements to make multiple decisions before doing something. Let’s take our rain example from earlier for example. If it is raining outside we want to use the umbrella. However, we only want to use the umbrella if it is raining outside and we are outside. We don’t want to use the umbrella if we are inside. We can write this in code by using nested if statements.

/*some of the variables used in this snippet have been omitted.
Please see the supporting code for this chapter for working code*/
//make the first decision
//check if its raining
if (itsRaining) {
/*make the second decision
because it's true that it's raining*/
//check if we are outside
if (weAreOutside) {
/*use the umbrella
because it's true that we are outside*/
useUmbrella = true;
} else {
/*otherwise, don't use the umbrella
because we are not outside*/
useUmbrella = false;
}
} else {
/*otherwise, don't use the umbrella
because it is not raining*/
useUmbrella = false;
}

The code snippet demonstrates how we use nested if statements to make nested decisions. First, we check if it’s raining: if it’s not raining, that’s it, don’t use the umbrella. If it is raining, we use another if statement to check if we are outside. If we are outside, we want to use the umbrella, otherwise, don’t use the umbrella.

We could also put if statements in the body of the else statements if we wanted to make more decisions after our initial conditions failed. For instance, if it is raining and we are not outside, we could check if we will be going outside soon before we decide to put the umbrella away or keep it nearby for when we are ready to step outside into the rain.

If-Then-Else If-Then-Else Statements

I may or may not have coined that hyphenated statement name, but excuse me for its complexity. Although it appears ugly, it allows us to make multiple decisions inline. You can think of it like so:

If this condition is not true, check the others until one is true, then do something.

Think of else as the default choice that is executed if none of the conditions before it are satisfied. When you get home from school, you try to find an activity to do. In this order, you check if you have homework, if not, you check if you have chores, if not, you check if your friends are free to play, and if not that, your default option is to watch the television if you have one. We can do this inline decision making in code, too:

/*some of the variables used in this snippet have been omitted.
Please see the supporting code for this chapter for working code*/
String activityToDo = "nothing yet";

if(haveHomework) {
activityToDo = "do homework";
} else if (haveChores) {
activityToDo = "wash dishes.";
} else if(friendsAreFreeToPlay) {
activityToDo = "go play with friends.";
} else {
if(haveTV) {
activityToDo = "watch favorite TV show.";
} else {
activityToDo = "do nothing";
}
}

Others

We have one more notable option for how we can make decisions in Java. The switch statement is powerful and can be used in special cases where you have many decisions, perhaps ten, to make before doing something. In some ways, the switch statement is an optimized version of what I call the if-then-else if-then-else statement. It is more of a matching statement than a decision-making statement. This is something you should research more on Google because it can be handy in bigger projects as you become more experienced.


ModernNerd Code

Learn to Code Life. Subscribe to Video Tutorials on Youtube

Lincoln W Daniel

Written by

My passion is in developing software to enable people to accomplish their goals more efficiently. Author @JavaForHumans.com. Creator of @Smedian.com

ModernNerd Code

Learn to Code Life. Subscribe to Video Tutorials on Youtube

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade