Reading: Sections 6.1
Let's write an absolute-value function to illustrate the conditional statement.
public static double absoluteValue(double x) {
if(x < 0.0) {
return -x;
} else {
return x;
}
}
In the parentheses goes the condition. If the condition is
true, then the computer does what's between the first set of braces;
otherwise it does what's between the second set.
We can use several operators to build up conditions. First are the six comparison operators. Each of these operators works on two numeric values, and the value of the expression is a boolean.
< <= > >= == !=These are the less-than, at-most, less-than, at-least, equal, and not-equal operators. (Note that testing equality takes two equal signs; this is because a single equal sign is already used for assignment.)
We also have three boolean operators: && (two ampersands) is the AND operator; it holds if both sides are true. The || operator is OR; it holds if either (or both) sides are true. And ! is NOT; it holds if the condition does not hold. For example,
if(x >= 1. && x <= 3.) //...This is true if x is between 1 and 3.