Chapter 5. Conditionals and Logic
The programs in the previous chapters do pretty much the same thing every time, regardless of the input. For more-complex computations, programs usually react to inputs, check for certain conditions, and generate applicable results. This chapter introduces Java language features for expressing logic and making decisions.
Relational Operators
Java has six relational operators that test the relationship between two values (e.g., whether they 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, named after the mathematician George Boole. He developed an algebraic way of representing logic.
You are probably familiar with these operators, but notice how Java is different from mathematical symbols like , ≠, and ≥. A common error is to use a single = instead of a double == when comparing values. Remember that = is the assignment operator, and == is a relational operator. Also, the operators =< and => do not exist.
The two sides of a relational operator have to be compatible. For example, the expression 5 < "6" is invalid because 5 is an int and "6" is a String. When comparing values of different ...