Java Reference
In-Depth Information
The method call
greeting.length()
returns a valueȌthe integer 13. The return
value becomes a parameter of the
println
method.
Figure 7
shows the process.
Not all methods return values. One example is the
println
method. The
println
method interacts with the operating system, causing characters to appear in a window.
But it does not return a value to the code that calls it.
Let us analyze a more complex method call. Here, we will call the
replace
method
of the
String
class. The
replace
method carries out a search-and-replace
operation, similar to that of a word processor. For example, the call
river.replace(ÐissippÑ, ÐourÑ)
constructs a new string that is obtained by replacing all occurrences of
ÐissippÑ
in
ÐMiss
issipp
iÑ
with
ÐourÑ
. (In this situation, there was only one replacement.)
The method returns the
String
object
ÐMiss
our
iÑ
(which you can save in a
variable or pass to another method).
As
Figure 8
shows, this method call has
ȗ
one implicit parameter: the string
ÐMississippiÑ
ȗ
two explicit parameters: the strings
ÐissippÑ
and
ÐourÑ
ȗ
a return value: the string
ÐMissouriÑ
Figure 7
Passing the Result of a Method Call to Another Method
41