Program Flow  «Prev  Next»
Lesson 1

Controlling Program Flow in Java Program

This module explores the flow of Java programs and shows you how to alter program flow using
  1. branches
  2. and loops.

You will begin the module by learning how to use conditional branches such as if-else and switch statements. You will then move on to learn the basics of loops, including how to use the for loop. From there, you will learn about while loops, do loops, and you will get some tips on how to control loops in general.

Applications need Control Flow

Every application makes some kind of decisions. In Java there are several programming constructs that we can use to make these decisions. These include 1) logical expressions, 2) if statement, and 3) switch statement. The purpose of this module is to introduce these tools to you and illustrate how they can be used. We will begin with a discussion of logical expressions as they are central to making decisions. Logical expressions are expressions that return a Boolean value. Next, we will examine how the logical expressions can be used with the if statement and the conditional operator. There are numerous variations on how a if statement can be structured and we will look at their advantages and disadvantages. This will be followed up with a discussion of the switch statement. Prior to Java 7, switch statements were based on integer or enumeration values. In Java 7, we can now use String values. The use of Strings and their potential pitfalls are examined. The last section addresses general control structure issues along with the impact of floating point numbers when making decisions, comparing objects, and a discussion of useful ways of organizing code.

Order of Statement Execution

In any application, the flow of control within a program is determined by the order in which the statements are executed. It is convenient to consider groups of statements as blocks whose execution is controlled by decision statements. A block can be considered to be an individual statement or several statements contained within a block statement. A block statement in Java is a group of statements enclosed in open and close curly braces.

Module learning objectives

After completing the module, you will have the skills and knowledge necessary to:
  1. Branch conditionally using if-else and switch statements
  2. Understand and use for loops, while loops, and do loops
  3. Make informed decisions about the effectiveness of different loops
  4. Break out of loops using the break statement
Can you imagine trying to write code using a language that did not give you a way to execute statements conditionally? Flow control is a key part of any useful programming language, and Java offers several ways to accomplish it. Some statements, such as if statements and for loops, are common to most languages. But Java also throws in a couple of flow control features you might not have used before, namely exceptions and assertions.