Page 229 - CA_Blue( J )_Class10
P. 229
Let us take the following example:
class calculate
{
int a, b, s;
void accept (int m, int n) // Formal Parameters
{
a=m; b=n;
}
void sum ()
{
s=a + b;
System.out.println("The result is:" +s);
}
public static void main ()
{
calculate ob= new calculate ();
int i=4, j=2;
ob.accept(i, j); // Actual Parameters
ob.sum();
}
}
In the above example, i and j are actual parameters that contain 4 and 2 as values, whereas the formal parameters m
and n receive the values in the order of 4 and 2, and the methods do the task of addition.
10.6 INVOKING A METHOD
After declaring and defining a method, we have to call it or invoke it so that the task assigned to the method can be
executed. Let us take an example:
class method
{
public static void main ()
{ void sum (int i, int j)
int a=8, b=4; {
method obj = new method(); System.out.println(i + j);
obj.sum (a, b); }
obj.diff (a, b);
a=5; b=6;
void diff (int i, int j)
obj.sum (a, b);
{
a=10; b=20;
System.out.println(i - j);
obj.sum (a, b);
}
}
}
Explanation:
1. The sum( ) method is called for three times:
st
a. 1 time with values 8 and 4, and will print 12
b. 2 time with values 5 and 6, and will print 11
nd
rd
c. 3 time with values 10 and 20, and will print 30
2. The diff( ) method will be executed once and will calculate the difference between 8 and 4, and will print 4;
There are two ways to invoke a method, which are Pass by Value and Pass by Reference. Let us study them in detail.
227
User-defined Methods 227

