Java Reference
In-Depth Information
Next follows a simple accessor method for the current display value ( getValue ). This allows
other objects to read the current value of the display.
The following mutator method setValue is more interesting. It reads:
public void setValue(int replacementValue)
if((replacementValue >= 0) && (replacementValue < limit)) {
value = replacementValue;
Here, we pass the new value for the display as a parameter into the method. However, before
we assign the value, we have to check whether the value is legal. The legal range for the value,
as discussed above, is 0 to 1 below the limit. We use an if statement to check that the value is
legal before we assign it. The symbol “ && ” is a logical “and” operator. It causes the condition in
the if statement to be true if both the conditions on either side of the “ && ” symbol are true. See
the “Logic operators” note that follows for details. Appendix C shows a complete table of logic
operators in Java.
Logic operators Logic operators operate on boolean values (true or false) and produce a new
boolean value as a result. The three most important logical operators are and , or , and not . They
are written in Java as:
&& (and)
││ (or)
! (not)
The expression
a && b
is true if both a and b are true, and false in all other cases. The expression
a ││ b
is true if either a or b or both are true, and false if they are both false. The expression
is true if a is false and false if a is true.
Exercise 3.6 What happens when the setValue method is called with an illegal value? Is
this a good solution? Can you think of a better solution?
Exercise 3.7 What would happen if you replaced the " >= " operator in the test with " > " so
that it reads
if((replacementValue > 0) && (replacementValue < limit))
Search WWH ::

Custom Search