1) Call by value:
When you are passing values of primitive data types as arguments to the function , then a copy of the values is created and the changes which are done are reflected in the duplicate values and hence, the original values remains unchanged. So, it is known as call by value.
Example: Let us consider the following example.
Demo.java
public class Demo
{
int a=0,b=0;
public void swap(int a,int b) // arguments
{
int t=0;
t=a;
a=b;
b=t; // values of a and b are swapped
}
}
MainClass.java - Main class
public Class MainClass
{
public static void main(String args[])
{
int a=10,b=20;
Demo ob=new Demo(); // instantiate the demo class
System.out.println("Before swapping values are "+a+" "+b);
ob.swap(a,b); // calling swap method by passing a and b as arguments
System.out.println("After swapping values are "+a+" "+b);
}
}
Output: Before swapping values are 10 20
After swapping values are 10 20
Swapping is not performed on original values because a local copy of a and b is created in the swap() method and hence, the values remains the same.
2) Call by Reference:
When you pass the values of non-primitive data types i.e Reference data types to a method as arguments , then a reference of the values in created and the changes which are done are actually reflected in the original values because a reference of those values is created. So, it is known as call by reference.
Example: Let us consider the following example.
Demo.java
public class Demo
{
int a=0,b=0;
public void swap(Demo ob) // Reference is passed as argument
{
int t=0;
t=ob.a;
ob.a=ob.b;
ob.b=t; // values of a and b are swapped
}
}
MainClass.java - Main class
public Class MainClass
{
public static void main(String args[])
{
Demo ob=new Demo(); // instantiate the demo class
ob.a=10;
ob.b=20;
System.out.println("Before swapping values are "+ob.a+" "+ob.b);
ob.swap(ob); // calling swap method by passing Demo class reference as argument
System.out.println("After swapping values are "+ob.a+" "+ob.b);
}
}
Output: Before swapping values are 10 20
After swapping values are 20 10
The original values gets changed since the reference is passed and the changes gets reflected in the object itself.
0 Comment(s)