What are the two ways of invoking functions in java?
Answers
The two ways of invoking functions in java are
- Call by value
- Call by reference.
Call by value is a method of invoking by passing the copy of actual parameters to the formal one.
Example:
1. class Sample
2. {
3. void accept(int a, int b)
4. {
5. int sum = a + b;
6. System.out.println(sum);
7. }
8. public static void main (String args[])
9. {
10. int a = 6;
11. int b = 10;
12. Sample obj = new Sample();
13. obj.accept(a,b);
14. }
Call by reference is another method of invoking in java by passing the actual reference to the formal parameters. You can find any changes in the actual parameter that is reflected from the formal one.
Example:
1. class Sample1
2. {
3. void Add(int x[])
4. {
5. int i, p;
6. p = x.length;
7. for (i = 0; i < p; i++)
8. {
9. System.out.print(x[i] + " ");
10. System.out.println();
11. }
12. }
13. public static void main (String args[])
14. {
15. int a[] = {3, 6, 8, 9};
16. int j, q;
17. q = a.length;
18. Sample2 obj = new Sample2();
19. obj.Add(a);
20. System.out.println("The arguments after function call: ");
21. for (j = 0; j < q; j++)
22. {
23. System.out.println(a[j] + " ");
24. System.out.println();
25. }
26. }
The two ways of invoking functions in Java are as follows:
1. Declaration of the function followed by creating an object and then summoning the function
2. While dealing with functions that are static, an object reference is most likely not required for summoning the function and the class reference only.
Apart from these two, there are other ways too, but those are not so widely accepted as these two.