Chapter 5. Conditionals and Logic
The programs we’ve seen in previous chapters do pretty much the same thing every time, regardless of the input. For more complex computations, programs usually react to the inputs, check for certain conditions, and generate appropriate results. This chapter presents the features you need for programs to make decisions: a new data type called boolean, operators for expressing logic, and if statements.
Relational Operators
Relational operators are used to check conditions like whether two values are equal, or whether one is greater than the other. The following expressions show how they are used:
x==y// x is equal to yx!=y// x is not equal to yx>y// x is greater than yx<y// x is less than yx>=y// x is greater than or equal to yx<=y// x is less than or equal to y
The result of a relational operator is one of two special values, true or false. These values belong to the data type boolean; in fact, they are the only boolean values.
You are probably familiar with these operations, but notice that the Java operators are different from the mathematical symbols like
, ≠, and ≤. A common error is to use a single = instead of a double ==. Remember that = is the assignment operator, and == is a comparison operator. Also, there is no such thing as the =< or => operators.
The two sides of a relational operator have to be compatible. For example, ...