Java Reference
In-Depth Information
You need to be clear about how the argument values are passed to a method; otherwise, you may run into
problems. In Java, all argument values are transferred to a method using what is called the pass-by-value
mechanism. Figure 5-4 illustrates how this works.
FIGURE 5-4
Pass-by-value just means that for each argument value that you pass to a method, a copy of the value is
made, and it is the copy that is passed to the method and referenced through the parameter name, not the
original variable. This implies that if you use a variable of any of the primitive types as an argument, the
method cannot modify the value of this variable in the calling program. In the example shown in Figure 5-4 ,
the change() method modifies the copy of i that is created automatically and referenced using the paramet-
er name j . Thus, the value of j that is returned is 11, and this is stored in the variable x when the return from
the method executes. However, the original value of i remains at 10.
NOTE Although the pass-by-value mechanism applies to all types of arguments, the effect for
objects is different from that for variables of the primitive types. A method can change an ob-
ject that is passed as an argument. This is because a variable of a class type contains a ref-
erence to an object, not the object itself. Thus, when you use a variable of a class type as an
argument to a method, a copy of a reference to the object is passed to the method, not a copy
of the object itself. Because a copy of a reference still refers to the same object, the parameter
name used in the body of a method refers to the original object that was passed as the argu-
ment.
Final Parameters
You can specify any of the parameters for a method as final . This has the effect of preventing modification
of any argument value that is substituted for the parameter when you call the method. The compiler checks
that your code in the body of the method does not attempt to change any final parameters. Because the pass-
by-value mechanism makes copies of values of the basic types, final really makes sense only when it is
applied to parameters that are references to class objects, as you see later on. Specifying a parameter of a
 
 
Search WWH ::




Custom Search