Java Reference
In-Depth Information
handled differently or so groups of cases can be handled the same. Finally, you'll learn about some
keywords that have specific uses in guiding the execution of a program.
comparisons using operators and methods
You have already seen operators, such as arithmetic operators, in Chapter 2. Operators are based
on mathematical concepts and many will look familiar, even to those unfamiliar with program-
ming. This chapter discusses two types of control operators, comparative and logical , that are
used frequently in control structures. The syntax for operators will differ whether the data type is
primitive or composite. Recall that primitive types include char , boolean , and many numeric rep-
resentations, like int , double , and float . Arrays, strings, and other defined classes are composite
data types.
comparing primitive data types with comparison operators
Given the importance of operators when defining control structures, this section briefly revisits some
of the underlying concepts covered in Chapter 2.
For primitive data types, there are well-defined operators, as outlined in Table 5-1, which can be
used to compare the values of two variables. Equality and relational comparison operators com-
pare the values of two operands for equality, inequality, greater than, or less than. The result of
these expressions is a Boolean true or false . With primitive types, the following expressions are
used for comparison:
Equal: ==
Not equal: !=
Greater than: >
Greater than or equal: >=
Less than: <
Less than or equal: <=
Note that the ! indicates negation. While these operators are used for most primitive data types,
there is an exception; Boolean operands can only be compared with equality operators and not
with relational operators. That is, true cannot be greater than or less than false ; however, true
can be equal to true . Other primitive data types can be compared with both equality and rela-
tional operators.
It is important to distinguish a single equal sign ( = ) from a double equal sign ( == ). The first is used
for variable assignment. The variable on the left is assigned the value on the right. For example,
balance = 5000 ; assigns the value of 5000 to the variable balance . The second is a comparison
operator to test whether two things are equal. For example, balance == 5000; will return true if
the value of the variable balance is 5000 and false otherwise.
 
Search WWH ::




Custom Search