Java Reference
In-Depth Information
To invoke this method, you must pass in an
int
argument. For example, the following
code invokes the
cubic
method:
31. int x = 11;
32. long result = cubic(x);
The value of
x
is copied into the parameter
y
. We now have two
int
s in memory that
have the value 11:
x
and
y
. Changing
y
to -1 in
cubic
has no effect on
x
. In fact, it is
impossible to change
x
within the
cubic
function.
Passing Primitives vs. Passing References
Sun seems to enjoy questions on the exam regarding call by value and methods that
attempt to change the value of the argument. If the argument passed into a method
parameter is a primitive type, it is impossible in Java for the method to alter the value of
the original primitive.
If the argument passed into a method parameter is a reference type, the same rule
applies: it is impossible for a method to alter the original
reference
. However, because the
method now has a reference to the same object that the argument points to, the method
can
change the object. This is an important difference to understand. Study the upcom-
ing
StackDemo
program for an example of this situation.
The following example of call by value uses references. Suppose we have the following
method signature:
5. public int findByName(String lastName, String firstName) {
6. lastName = “Doe”;
7. firstName = “Jane”;
8. return -1;
9. }
This method has two parameters,
lastName
and
firstName
. To invoke this method, two
String
objects must be passed in as arguments. For example, the following code invokes
the
findByName
method. What is the output of this code?
14. String first = “Albert”;
15. String last = “Einstein”;
16. int result = findByName(last, first);
17. System.out.println(first + “ “ + last);
Search WWH ::
Custom Search