Java Reference
In-Depth Information
#1: a = 19, b = 37
#2: x = 19, y = 37
#3: x = 37, y = 19
#4: a = 19, b = 37
A primitive type parameter is passed by value. However, you can modify the value of the formal parameter
inside the method without affecting the actual parameter value. Java also lets you use pass by constant value. In this
case, the formal parameter cannot be modified inside the method. The formal parameter is initialized with the value
of the actual parameter by making a copy of the actual parameter and then it is a constant value, which can only
be read. You need to use the final keyword in the formal parameter declaration to indicate that you mean to pass
the parameter by constant value. Any attempt to change the value of a parameter, which uses pass by constant value,
results in a compiler error. Listing 6-23 demonstrates how to use the pass by constant value mechanism to pass the
parameter x to the test() method. Any attempt to change the value of the formal parameter x inside the test()
method will result in a compiler error. If you uncomment the "x = 10;" statement inside the test() method, you
would get the following compiler error:
Error(10): final parameter x may not be assigned
You have passed two parameters, x and y , to the test() method. The parameter y is passed by value, and hence it
can be changed inside the method. This can be confirmed by looking at the output.
Listing 6-23. An Example of Pass by Constant Value
// PassByConstantValueTest.java
package com.jdojo.cls;
public class PassByConstantValueTest {
// x uses pass by constant value and y uses pass by value
public static void test(final int x, int y) {
System.out.println("#2: x = " + x + ", y = " + y);
/* Uncommenting following statement will generate a compile-time error */
// x = 79; /* Cannot change x. It is passed by constant value */
y = 223; // Ok to change y
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);
PassByConstantValueTest.test(a, b);
System.out.println("#4: a = " + a + ", b = " + b);
}
}
 
Search WWH ::




Custom Search