Java Reference
In-Depth Information
When a reference type parameter is passed to a method in java, the formal parameter can access the object the
same way the actual parameter can access the object. the formal parameter can modify the object by directly changing
the values of the instance variables or by calling methods on the object. any modification made on the object through
the formal parameter is immediately visible through the actual parameter because both hold the reference to the same
object in memory. the formal parameter itself can be modified to reference another object (or the null reference) inside
the method.
Tip
If you do not want the method to change the reference type formal parameter to reference a different object than
the one referenced by the actual parameter, you can use the pass by constant reference value mechanism to pass that
parameter. If you use the keyword final in the reference type formal parameter declaration, the parameter is passed by
constant reference value and the formal parameter cannot be modified inside the method. The following declaration
of the test() method declares the xyzCar formal parameter as final and it is passed by constant reference value. The
method attempts to change the xyzCar formal parameter by assigning a null reference to it and then by assigning a
reference to a new Car objects. Both of these assignment statements will generate a compiler error:
// xyzCar is passed by constant reference value because it is declared final
void test(final Car xyzCar) {
// Can read the object referenced by xyzCar
String model = xyzCar.model;
// Can modify object referenced by xyzCar
xyzCar.year = 2001;
/* Cannot modify xzyCar. That is, xyzCar must reference the object what the actual
parameter is referencing at the time this method is called. You cannot even set it to
null reference. */
xyzCar = null; // A compile-time error. Cannot modify xyzCar
xyzCar = new Car(); // A compile-time error. Cannot modify xyzCar
}
Let's discuss one more example on parameter passing mechanism in Java. Consider the following code for the
changeString() method:
public static void changeString(String s2) {
/* #2 */
s2 = s2 + " there";
/* #3 */
}
Consider the following snippet of code that calls the changeString() method:
String s1 = "hi";
/* #1 */
changeString(s1);
/* #4 */
 
 
Search WWH ::




Custom Search