QNA > W > What Are The Two Ways Of Invoking A Method In Java?

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:

  1. class Sample 
  2. void accept(int a, int b) 
  3. int sum = a + b; 
  4. System.out.println(sum); 
  5. public static void main (String args[]) 
  6. int a = 6; 
  7. int b = 10; 
  8. Sample obj = new Sample(); 
  9. 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:

  1. class Sample2 
  2. void Add(int x[]) 
  3. int i, p; 
  4. p = x.length; 
  5. for (i = 0; i < p; i++) 
  6. System.out.print(x[i] + " "); 
  7. System.out.println(); 
  8. public static void main (String args[]) 
  9. int a[] = {3, 6, 8, 9}; 
  10. int j, q; 
  11. q = a.length; 
  12. Sample2 obj = new Sample2(); 
  13. obj.Add(a); 
  14. System.out.println("The arguments after function call: "); 
  15. for (j = 0; j < q; j++) 
  16. System.out.println(a[j] + " "); 
  17. System.out.println(); 

THANKS!

Di Hildebrandt

How to use an array of objects and call them in methods in Java :: Come scrivere una descrizione del copyright nei nostri video di YouTube
Link utili