4.5 Argument Passing in Java

Any valid Java data type can be passed as an argument into a method. These can be primitive data types such as int and float, or reference data types such as objects or arrays. Both primitive and reference data type arguments are passed by value; however, the impact on the calling method can be different depending on the passed data type.

Where a primitive data type argument is being passed, the value of the argument is copied into the method's parameter. If the method changes the value of the parameter, then this change is local to the method and does not affect the value of the argument in the calling program. The following example illustrates this. The Employee class consists of just one method, increment, which adds 10 to a supplied argument of type int.

Employee

class Employee
{

public void increment(int amount)
{
amount = amount + 10;
System.out.println(''amount within method: " + amount);
}
}



CreateEmployee application sets the variable amount to 500 and invokes the Employee class increment method with amount as an argument.


CreateEmployee

class CreateEmployee
{

public static void main(String[] args)
{
int amount = 500;

Employee fred = new Employee();
fred.increment(amount);
System.out.println("amount outside method: " + amount);
}
}



The output of running the CreateEmployee application follows:

>java CreateEmployee
amount within method: 510 amount outside method: 500

So although the increment method has increased the amount to 510, the amount in the calling program remains at 500.If, however, the argument passed to a method is a reference data type, the memory address of the argument is copied to the method's parameter. Consequently, both the calling method argument and the called method parameter reference the same object. If the method changes the value of this object, then this change is reflected in the calling program. To illustrate this, the second version of Employee has the increment method modified to accept an array argument, salary, of type int. The first element of salary is incremented by 10.


Employee

class Employee
{

public void increment(int[] salary)
{
salary[0] = salary[0] + 10;
System.out.println(''amount within method: " +
salary[0]);
}
}



In the second version of the CreateEmployee application, the argument passed to the increment method is an array, fredsSalary.


CreateEmployee

class CreateEmployee
{

public static void main(String[] args)
{
int fredsSalary[] = new int [1];

Employee fred = new Employee();
fredsSalary[0] = 500;
fred.increment(fredsSalary);
System.out.println("amount outside method : "
+ fredsSalary[0]);
}
}




The output of running CreateEmployee will now be as follows:

>java CreateEmployee amount within method: 510 amount outside method: 510

No comments:

Post a Comment