Java Reference
In-Depth Information
repetition. In selection, the program executes particular statements depending on one or
more conditions. In repetition, the program repeats particular statements a certain
number of times depending on one or more conditions. This chapter introduces selection
(branching); Chapter 5 introduces repetition (looping).
Branch: Altering the flow of program execution by making a selection or choice.
Loop: Altering the flow of program execution by the repetition of statement(s).
Before you can learn about selection and repetition, you must understand the nature of
conditional expressions and how to use them. Consider the following three statements
(notice that these are not Java statements):
1. if (score is greater than or equal to 90)
grade is A
2. if (hours worked are less than or equal to 40)
wages = rate * hours
otherwise
wages = (rate * 40) + 1.5 * (rate * (hours - 40))
3. if (temperature is greater than 50 degrees and it is not
raining)
recommended activity is golfing
These statements include conditional expressions. For example, in 1, the conditional
expression is: score is greater than or equal to 90 .
You can see that a statement such as grade is A is to be executed only if a certain
condition is met.
A condition is met if it evaluates to true . For example, in statement 1:
4
score is greater than or equal to 90
is true if the value of score is greater than or equal to 90 ;itis false otherwise. For
example, if the value of score is 95 , the statement evaluates to true . Similarly, if the
value of score is 86 , the statement evaluates to false . So if the value of score is greater
than or equal to 90 , then the statement, grade is A , executes.
It is useful for the computer to be able to recognize expressions, such as score
is greater than or equal to 90 ,tobe true for appropriate values. Furthermore, in
certain situations, the truth of a statement could depend on more than one condition. For
example, in statement 3, both temperature is greater than 50 degrees and it is
not raining must be true for the recommended activity to be golfing .
As you can see from these examples, to make decisions, the computer must be able to
react to conditions that exist when the program executes. The next few sections discuss
how to represent and evaluate conditional statements in Java.
Search WWH ::




Custom Search