Method Calling Mechanisms in Java.

In this article,Method Calling Mechanisms in Java is explained in detail with an example.
Based on nature of arguments used to call a user defined method in java, we have two types of method calling mechanisms.They are
  • Call by value.
  • Call by reference.
Call by Value
In this mechanism, we pass a copy of actual arguments to call a user-defined method and formal parameters are also of same data type.
Any changes done with formal parameters are NOT reflected to actual arguments.
Ex
//program related to Method Calling Mechanisms in Java--call by value.
class CallByValue
{
public static void main(String args[])
{
Test obj=new Test();
int a=50,b=60;
System.out.println("Values of A and B before call: "+a+" "+b);
obj.meth(a,b); //actual arguments..
System.out.println("Values of A and B after call: "+a+" "+b);
}
}
class test
{
void main(int i,int j) //i,j are formal parameters.
{
i*=2;
j/=2;
System.out.println("Values of I and J are: "+i+" "+j);
}
}
Output
Values of A and B before call: 50 60
Values of I and J are: 100 30
Values of A and B after call: 50 60
Call by value-Output-javform
                            To get the code file use me.

Call by reference.
In java,We don't have the concept of pointers, but still, this mechanism is done through"object reference-variables". (From topic Method Calling Mechanisms in Java)
Ex
A obj=new A();
diagram
In this Mechanism, we pass object-reference-variables as the actual argument to call a user defined method and formal parameters are also object-reference variables of same class type. Any change done with formal-parameters is directly reflected to the actual argument.
Ex
//program related to Method Calling Mechanisms in Java--call by reference.
class A
{
int a,b;
A(int i,int j)
{
a=i;
b=j;
}
void method1(A obj1) //object reference of class A
{
obj1.a*=2;
obj1.b*=2;
}
}
class CallByReference
{
public static void main(String args[])
{
A obj=new A(10,20);
System.out.println("A and B before call is: "+obj.a+" "+obj.b);
obj.method1(obj);
System.out.println("A and B After call is: "+obj.a+" "+obj.b);
}
}
Output
A and B before call is: 10 20
A and B After call is: 20 40
CallByReference-Output-javaform
                            To get the code file use me.

Continue to next topic Access Modifiers in Java.

Begin your career in Digital Marketing,What is digital marketing? Digital Marketing online course. It's an current evolving technology which can give support to establish your own startup through Digital Marketing.

Do check my new startup Surprise Planners in HyderabadLavish Surprises our services are surprise party planners in Hyderabadsurprise giftssurprise birthday party planners Hyderabad, Wedding anniversary surprisessurprise planners Hyderabad.

Hi Friends, Please comment down your views in the comment section below. Thank you...

No comments:

Connect with Us by Subscribing here for more Updates..!

* indicates required