Java Reference
In-Depth Information
A loop , or repetition statement , allows us to execute a program-
ming statement over and over again. Like a conditional, a loop is
based on a boolean expression that determines how many times the
statement is executed.
For example, suppose we wanted to calculate the grade point average of every
student in a class. The calculation is the same for each student; it is just performed
on different data. We would set up a loop that repeats the calculation for each
student until there are no more students to process.
Java has three types of loop statements: the while statement, the do statement,
and the for statement. Each type of loop statement has unique characteristics that
distinguish it from the others. We cover the while statement in this chapter and
explore do loops and for loops in Chapter 6.
The boolean expressions on which conditionals and loops are based use
equality operators, relational operators, and logical operators to make decisions.
Before we discuss the conditional and loop statements in detail, let's explore
these operators.
KEY CONCEPT
A loop allows a program to execute
a statement multiple times.
Equality and Relational Operators
The == and != operators are called equality operators. They test whether two val-
ues are equal or not equal, respectively. Note that the equality operator consists
of two equal signs side by side and should not be mistaken for the assignment
operator that uses only one equal sign.
The following if statement prints a sentence only if the variables total and
sum contain the same value:
if (total == sum)
System.out.println ("total equals sum");
Likewise, the following if statement prints a sentence only if the variables
total and sum do not contain the same value:
if (total != sum)
System.out.println ("total does NOT equal sum");
relational operators that let us decide relative ordering
between values. Earlier in this section we used the greater than operator ( > ) to
decide if one value was greater than another. We can ask similar questions using
various operators. In Java, relational operators are greater than (>), less than ( < ),
greater than or equal to ( >= ), and less than or equal to ( <= ). Figure 5.1 lists the
Java equality and relational operators.
Java also has several
 
Search WWH ::




Custom Search