Java Reference
In-Depth Information
36. response = a;
37. }
38. return response;
39. }
The
max
method returns a local variable named
response
. A copy of
response
is
returned to the calling method. Consider the following invocation of
max
:
45. public void go() {
46. int x = 20, y = 30;
47. int biggest = max(20, 30);
48. System.out.println(biggest);
49. }
In this case, the parameter
a
is 20 and
b
is 30, resulting in a
response
of 30. A copy of
30 is passed back to the
go
method and stored in
biggest
. Because
max
is done executing,
its call-stack memory is freed and
a
,
b
, and
response
all get destroyed. It doesn't make
sense to try to modify
response
in the
go
method because
response
no longer exists in
memory.
The Call Stack
Every method that gets invoked in a Java thread is pushed onto the thread's method
call
stack
. The method at the top of the call stack is the currently executing method. Each
method on the call stack gets its own small amount of memory. When a method fi nishes
executing (by running to completion, returning a value, or throwing an exception), the
method gets popped off the call stack and its memory is freed. Any parameters and local
variables are destroyed and no longer exist in the program's memory.
The next example shows a method that returns a reference to an object. Examine the
code and see if you can determine when the
File
object instantiated on line 6 is eligible for
garbage collection:
1. import java.io.File;
2.
3. public class ReturnDemo {
4.
5. public File getFile(String fileName) {
6. File f = new File(fileName);
7. return f;
Search WWH ::
Custom Search