Chapter 6

Conditional Statements: How Your Programs Make Choices

So far in this book, all the programs have run in a linear fashion. In other words, your programs simply ran from start to finish with each statement being executed one after the other. However, in most real-life situations, your programs will need to make decisions whether to skip a few statements, repeat things multiple times, or even jump from one part of your code to another part. Such actions are performed using control statements. You will learn about these statements in this chapter and the next chapter.

A programming language provides control statements that allow your programs to alter the flow of execution. Java’s control statements are divided into the following categories: selection, iteration, and jump.

Selection Statement

Selection statements allow your program to choose different paths of execution based on a Boolean expression. They are also known as conditional statements. They are the focus of this chapter.

Iteration Statement

Iteration statements enable your program to repeat one or more statements in your code. They are also known as loop statements. You will learn more about these statements in the next chapter.

Jump Statements

By far, jump statements are the simplest control statements. As the name suggests, they allow your program to jump from one location to another location. Given their simplicity, they don’t get their own chapter. However, we explain them in detail whenever their usage is required or when a concept is closely associated with them.

In this chapter, we will learn about the selection statements in Java. You discover two Java statements that let your programs make decisions. First you will learn about the if statement which allows you to execute a statement or a block of statements based on a Boolean condition. After which, you will learn about the switch statement, which is an elegant version of the if statement.

The if statement relies heavily on the use of Boolean expressions. In general, these expressions produce true or false. Which is why, this chapter begins by showing you how to write simple Boolean expressions that test the value of a variable. You have already learnt the various logical and comparison operators, which produce Boolean values. You can always go back to the previous chapter to jog your memory