A formal parameter can be declared with the keyword final preceding the parameter declaration in the method definition. A final parameter is also known as a blank final variable; that is, it is blank (uninitialized) until a value is assigned to it, (for example, at method invocation) and then the value in the variable cannot be changed during the lifetime of the variable (see also the discussion in Section 4.10, p. 146). The compiler can treat such blank final variables as constants for code optimization purposes. Whether a formal parameter is declared as final, does not affect the caller's code.
The definition of method calcPrice() from Example 3.3 is shown below, with the formal parameter pizzaPrice declared as final.
public double calcPrice(int numberOfPizzas, final double pizzaPrice) { // (2) pizzaPrice = pizzaPrice/2.0; // (3) return numberOfPizzas * pizzaPrice; }
If this definition of the calcPrice() method is compiled, the compiler will not allow the value of the final parameter pizzaPrice to be changed at (3) in the body of the method.
As another example, the definition of the method bake() from Example 3.4 is shown below, with the formal parameter pizzaToBeBaked declared as final.
public static void bake(final Pizza pizzaToBeBaked) { // (3) pizzaToBeBaked.meat = "chicken"; // (3a) Allowed. pizzaToBeBaked = null; // (4) Not allowed. }
If this definition of the bake() method is compiled, the compiler will not allow the reference value of the final parameter pizzaToBeBaked to be changed at (4) in the body of the method. Note that this applies to the reference value in the final parameter, not the object denoted by this parameter. The state of the object can be changed as before, as shown at (3a).