Java Reference
In-Depth Information
Let's write our own version of the
max
method that returns the larger of two inte-
gers. Its header will look like this:
public static int max(int x, int y) {
...
}
We want to return either
x
or
y
, depending on which is larger. This is a perfect
place to use an
if/else
construct:
public static int max(int x, int y) {
if (x > y) {
return x;
} else {
return y;
}
}
This code begins by testing whether
x
is greater than
y
. If it is, the computer exe-
cutes the first branch by returning
x
. If it is not, the computer executes the
else
branch by returning
y
. But what if
x
and
y
are equal? The preceding code executes
the
else
branch when the values are equal, but it doesn't actually matter which
return
statement is executed when
x
and
y
are equal.
Remember that when Java executes a
return
statement, the method stops execut-
ing. It's like a command to Java to “get out of this method right now.” That means
that this method could also be written as follows:
public static int max(int x, int y) {
if (x > y) {
return x;
}
return y;
}
This version of the code is equivalent in behavior because the statement
return x
inside the
if
statement will cause Java to exit the method immediately and Java will
not execute the
return
statement that follows the
if
. On the other hand, if we don't
enter the
if
statement, we proceed directly to the statement that follows it (
return y
).
Whether you choose to use the first form or the second in your own programs
depends somewhat on personal taste. The
if/else
construct makes it more clear that
the method is choosing between two alternatives, but some people prefer the second
alternative because it is shorter.
As another example, consider the
indexOf
method of the
String
class. We'll
define a variable
s
that stores the following
String
:
String s = "four score and seven years ago";
Search WWH ::
Custom Search