Java Reference
In-Depth Information
This brief statement causes a lot of confusion. Does it mean that when a parameter is a reference type, a copy of
the object the actual parameter refers to is made and assigned to the formal parameter? It is important to elaborate on
the phrase “All parameters in Java are passed by value” with examples. Even veteran Java programmers have problems
understanding the parameter passing mechanism in Java. To be more elaborate, Java supports the following four types
of parameter passing mechanisms:
Pass by value
Pass by constant value
Pass by reference value
Pass by constant reference value
Note that all four ways of passing parameters in Java includes the word “value.” This is the reason that many
topics on Java summarize them as “Java passes all parameters by value.” Please refer to the previous section for more
details for the above-mentioned four types of parameter passing mechanisms.
The first two types, pass by value and pass by constant value, apply to parameters of primitive data types. The last
two types, pass by reference value and pass by constant reference value, apply to the parameters of reference type.
When a formal parameter is of a primitive data type, the value of the actual parameter is copied to the formal
parameter. Any changes made to the formal parameter's value inside the method's body will change only the copy
of the formal parameter and not the value of the actual parameter. Now you can tell that swap() method to swap
two primitive values will not work in Java. Listing 6-22 demonstrates that swap() method cannot be written in Java
because primitive type parameters are passed by value. The output shows that the x and y formal parameters of the
swap() method receive the values of a and b . The values of x and y are swapped inside the method, which does not
affect the values of actual parameters a and b at all.
Listing 6-22. An Incorrect Attempt to Write a swap() Method to Swap Values of Two Primitive Types in Java
// BadSwapTest.java
package com.jdojo.cls;
public class BadSwapTest {
public static void swap(int x, int y) {
System.out.println("#2: x = " + x + ", y = " + y);
int temp = x;
x = y;
y = temp;
System.out.println("#3: x = " + x + ", y = " + y);
}
public static void main(String[] args) {
int a = 19;
int b = 37;
System.out.println("#1: a = " + a + ", b = " + b);
// Call the swap() method to swap values of a and b
BadSwapTest.swap(a, b);
System.out.println("#4: a = " + a + ", b = " + b);
}
}
 
Search WWH ::




Custom Search