What are the two ways of invoking a method in Java?
HELLO THERE!
There are generally two methods to invoke or call a function (method) in Java. These are as follows:
#1. Call by Value: Call by Value is the method of invoking a method by passing a copy of the actual parameters to the formal parameters such that any change occuring in the formal parameters will not reflect on the actual parameters.
Consider the following example:
- class Sample
- {
- void accept(int a, int b)
- {
- int sum = a + b;
- System.out.println(sum);
- }
- public static void main (String args[])
- {
- int a = 6;
- int b = 10;
- Sample obj = new Sample();
- obj.accept(a,b);
- }
#2. Call by Reference: By this method, the actual reference or actual location of the actual parameters are passed to the formal parameters such that any changes occuring in the formal parameters will reflect on the actual parameters.
Consider the following example:
- class Sample2
- {
- void Add(int x[])
- {
- int i, p;
- p = x.length;
- for (i = 0; i < p; i++)
- {
- System.out.print(x[i] + " ");
- System.out.println();
- }
- }
- public static void main (String args[])
- {
- int a[] = {3, 6, 8, 9};
- int j, q;
- q = a.length;
- Sample2 obj = new Sample2();
- obj.Add(a);
- System.out.println("The arguments after function call: ");
- for (j = 0; j < q; j++)
- {
- System.out.println(a[j] + " ");
- System.out.println();
- }
- }
THANKS!