Thursday, January 21, 2016

Topic 15: Argument passing in Java

There are two ways that a computer language can pass an argument to a subroutine. 

  • Call-by-value - This approach copies the value of an argument into the formal parameter of the subroutine. Therefore, changes made to the parameter of the subroutine have no effect on the argument. 

  • Call-by-reference - In this approach, a reference to an argument is passed to the parameter. Inside the subroutine, this reference is used to access the actual argument specified in the call. This means that changes made to the parameter will affect the argument used to call the subroutine.


In Java, primitive types to a method are passed by value.

// Primitive types are passed by value.
class Test
{

void meth(int i, int j)
{
i *= 2;
j /= 2;
}

}

//Inside main class
Test ob = new Test();
int a = 15, b = 20;
System.out.println("a and b before call: " + a + " " + b);
ob.meth(a, b);
System.out.println("a and b after call: " + a + " " + b);

Output:
a and b before call: 15 20
a and b after call: 15 20


An object to a method, is effectively passed as call-by-reference. When we create a variable of a class type, we are only creating a reference to an object. Thus, when we pass this reference to a method, the parameter that receives it will refer to the same object as that referred to by the argument. Changes to the object inside the method do affect the object used as an argument. For ex:

// Objects are passed by reference.
class Test
{
int a, b;

Test(int i, int j)
{
a = i;
b = j;
}

// pass an object
void meth(Test o)
{
o.a *= 2;
o.b /= 2;
}

}

//Inside main class

Test ob = new Test(15, 20);

System.out.println("ob.a and ob.b before call: " + ob.a + " " + ob.b);

ob.meth(ob); //passing same class instance to the method i.e. ob

System.out.println("ob.a and ob.b after call: " + ob.a + " " + ob.b);

Output:
ob.a and ob.b before call: 15 20
ob.a and ob.b after call: 30 10


Click for NEXT article.


Please feel free to correct me by commenting your suggestions and feedback.

No comments:

Post a Comment