In general, there are two ways that a computer language can pass an argument to a subroutine. The first way is 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. The second way an argument can be passed is call-by-reference. In this approach, a reference to an argument (not the value of the 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. As you will see, Java uses both approaches, depending upon what is passed.

In Java, when you pass a primitive type to a method, it is passed by value. Thus, what occurs to the parameter that receives the argument has no effect outside the method. For example, consider the following program:

Program

Call By Value –

// Primitive types are passed by value.

class Test {

void meth ( int i, int j )   {

i *= 2 ;

j /= 2 ;

}

}

class CallByValue  {

public static void main ( String args[] )   {

Test ob = new Test () ;

int a = 15, b = 20 ;

System. out. println( “ a and b before call : ”  + a + “ “ + b) ;

  1. meth(a, b) ;

System .out. println(“ a  and b after call :”  + a + “ “ + b) ;

}

}

The output from this program is shown here :

a and b before call :  15 20

a and b after call : 15 20

As you can see, the operations that occur inside meth( ) have no effect on the values of a and b used in the call ; their values here did not change to 30 and 10 .

Recommended Post   What is Inheritance in Java Programming?

Call By Referance –

// 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 ;

  1. b /= 2 ;

}

}

class CallByRef {

public static void main( String args[] )  {

Test ob = new Test ( 15, 20) ;

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

  1. meth (ob) ;

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

}

}

This program generates the following output :

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

We can see in this case, the actions inside meth( ) have affected the object used as an argument.

LEAVE A REPLY

Please enter your comment!
Please enter your name here