Passing Arguments

In this lesson, we look at the different ways to pass an argument to a method.

Parameters of a primitive type

When a formal parameter has a primitive type such as int, it is initialized to the value of the corresponding argument in the call to the method. This argument can be a literal constant—such as 51—or it can be a variable or any expression. This way of passing an argument to a method is known as a call by value. A method cannot change the value of an argument that has a primitive data type. Such an argument serves as an input value only.

📝 Note

The arguments in a call to a method must match the formal parameters of the method’s definition with respect to number, order, and data type. A match of data type need not be exact when the types are primitive, as Java allows certain implicit type casts or coercions. An argument with a data type in the following list will match a formal parameter whose data type is either the same or appears to the right in this list:

byte → short → int → long → float → double

This list is the same as the one we saw in the chapter Arithmetic Expressions when we discussed assignments.

Parameters of a class type

When a formal parameter has a class type, the corresponding argument in the method invocation must be an object of that class type. The formal parameter is initialized to the memory address of that object. The formal parameter, then, is just another name for the object. As a result, the method can change the data in the object, if the class has mutator methods. The method, however, cannot replace the object with another object.

Example

For example, if you adopt a child, you might give that child your last name. If you use the previous class Name to represent names, you can use the method giveLastNameTo to make this change of name. Recall the header for this method:

public void giveLastNameTo(Name otherName)

Notice that the method’s formal parameter has the data type Name.

Now if Jamie Jones adopts Sam Smith, the following statements would change Sam’s last name to Jones:

Name jamie = new Name("Jamie", "Jones");
Name sam = new Name("Sam", "Smith");
jamie.giveLastNameTo(sam);

The figure given below shows the argument sam and the formal parameter otherName as the method giveLastNameTo executes.

Get hands-on with 1200+ tech skills courses.