Java Reference
In-Depth Information
Suppose you want to call the method
isTwoUniqueDigits
. You want the method
to take a value of type
int
and return
true
if the
int
is composed of two unique digits
and
false
if it is not. So, the method would look like the following:
public static boolean isTwoUniqueDigits(int n) {
...
}
How would you write the body of this method? We've already written the test, so
we just have to figure out how to incorporate it into the method. The method has a
boolean
return type, so you want it to return the value
true
when the test succeeds
and the value
false
when it fails. You can write the method as follows:
public static boolean isTwoUniqueDigits(int n) {
if (n >= 10 && n <= 99 && (n % 10 != n / 10)) {
return true;
} else {
return false;
}
}
This method works, but it is more verbose than it needs to be. The preceding code
evaluates the test that we developed. That expression is of type
boolean
, which
means that it evaluates to either
true
or
false
. The
if/else
statement tells the
computer to return
true
if the expression evaluates to
true
and to return
false
if it
evaluates to
false
. But why use this construct? If the method is going to return
true
when the expression evaluates to
true
and return
false
when it evaluates to
false
,
you can just return the value of the expression directly:
public static boolean isTwoUniqueDigits(int n) {
return (n >= 10 && n <= 99 && (n % 10 != n / 10));
}
Even the preceding version can be simplified, because the parentheses are not nec-
essary (although they make it clearer exactly what the method will return). This code
evaluates the test that we developed to determine whether a number is composed of
two unique digits and returns the result (
true
when it does,
false
when it does not).
Consider an analogy to integer expressions. To someone who understands Boolean
Zen, the
if/else
version of this method looks as odd as the following code:
if (x == 1) {
return 1;
} else if (x == 2) {
return 2;
} else if (x == 3) {
return 3;
Search WWH ::
Custom Search