3.18 Passing Primitive Data Values

When the actual parameter is a variable of a primitive data type, the value of the variable is copied to the formal parameter at method invocation. Since formal parameters are local to the method, any changes made to the formal parameter will not be reflected in the actual parameter after the call completes.

Note that the actual parameter can be an expression that is evaluated first, and the resulting value is then passed.

Type conversions between actual and formal parameters of primitive data types are similar to those for numeric assignment conversions (i.e., widening primitive conversions are implicitly applied). However, for parameter passing there are no implicit narrowing conversions (see Section 3.4, p. 49).

Example 3.3 Passing Primitive Values
public class CustomerOne {
    public static void main (String[] args) {
        PizzaFactory pizzaHouse = new PizzaFactory();
        int pricePrPizza = 15;
        double totPrice = pizzaHouse.calcPrice(4, pricePrPizza);      // (1)
       System.out.println("Value of pricePrPizza: " + pricePrPizza); // Unchanged.

class PizzaFactory {
    public double calcPrice(int numberOfPizzas, double pizzaPrice) {  // (2)
        pizzaPrice = pizzaPrice/2.0; // Change price.
        return numberOfPizzas * pizzaPrice;

Output from the program:

Value of pricePrPizza: 15

In Example 3.3, the method calcPrice() is defined in class PizzaFactory at (2). It is called from the CustomerOne.main() method at (1). The value of the first actual parameter, 4, is copied to the int formal parameter numberOfPizzas. Note that the second actual parameter pricePrPizza is of type int, while the corresponding formal parameter pizzaPrice is of type double. Before the value of the actual parameter pricePrPizza is copied to the formal parameter pizzaPrice, it is implicitly widened to a double. Passing of primitive values is illustrated in Figure 3.4.

Figure 3.4. Parameter Passing: Primitive Data Values


The value of the formal parameter pizzaPrice is changed in the calcPrice() method, but this does not affect the value of the actual parameter pricePrPizza on return. It still has the value 15. The bottom line is that the formal parameter is a local variable, and change of its value does not affect the value of the actual parameter.