Java Reference
In-Depth Information
5.1 Boolean Expressions
The order in which statements are executed in a running program is called the
flow of control . Unless otherwise specified, the execution of a program proceeds
in a linear fashion. That is, a running program starts at the first programming
statement and moves down one statement at a time until the program is complete.
A Java application begins executing with the first line of the main method and
proceeds step by step until it gets to the end of the main method.
Invoking a method alters the flow of control. When a method is called, control
jumps to the code defined for that method. When the method completes, control
returns to the place in the calling method where the invocation was made, and
processing continues from there.
Within a given method, we can alter the flow of control through
the code by using certain types of programming statements.
Statements that control the flow of execution through a method fall
into two categories: conditionals and loops.
A conditional statement is sometimes called a selection statement,
because it allows us to choose which statement will be executed next. The con-
ditional statements in Java are the if statement, the if-else statement, and the
switch statement. We explore the if statement and the if-else statement in this
chapter and cover the switch statement in Chapter 6.
Each decision is based on a boolean expression (also called a condition ), which
is an expression that evaluates to either true or false. The result of the expression
determines which statement is executed next. The following is an example of an
if statement:
KEY CONCEPT
Conditionals and loops allow us
to control the flow of execution
through a method.
if (count > 20)
System.out.println ("Count exceeded");
The condition in this statement is count > 20 . That expression
evaluates to a boolean (true or false) result. Either the value stored in
count is greater than 20 or it's not. If it is, the println statement is
executed. If it's not, the println statement is skipped and processing
continues with whatever code follows it.
The need to make decisions like this comes up all the time in programming
situations. For example, the cost of life insurance might be dependent on whether
the insured person is a smoker. If the person smokes, we calculate the cost using a
particular formula; if not, we calculate it using another. The role of a conditional
statement is to evaluate a boolean condition (whether the person smokes) and
then to execute the proper calculation accordingly.
KEY CONCEPT
An if statement allows a program
to choose whether to execute a
particular statement.
 
Search WWH ::




Custom Search