In Java, there are two ways of argument passing.
- Call by value
- Call by reference
Call by value
Whenever we call a method and passes the value of the variable to the called method, it’s called call by value.
class Demo {
void set(int i, int j) {
i = i * 2;
j = j / 2;
}
}
public class Test {
public static void main(String arg[]) {
Demo obj = new Demo();
int a = 15, b = 20;
System.out.println("Before call a=" + a + " b=" + b);
obj.set(a, b);
System.out.println("After call a="+a+" "+" b="+b);
}
}
Result
Before call a=15 b=20 After call a=15 b=20
Note: After multiplication and division value of a and b remain unchanged.
Explanation : In the above program, we are passing the value of a and b 15 & 20 respectively and set the value of i and j. After setting the value of i and j value of variable a and b remain unchanged because modifications occurs in variable i and j.
Call by reference
Whenever we call a method and passes the reference of the variable to the called method, it’s called call by reference.
class Demo {
int a, b;
Demo(int i, int j) {
a = i;
b = j;
}
void set(Demo o) {
o.a = o.a * 2;
o.b = o.b / 2;
}
}
public class Test{
public static void main(String arg[]) {
Demo obj = new Demo(10, 20); // passing value
System.out.println("Before call a=" + obj.a + " b=" + obj.b);
obj1.set(obj); //pass object obj1 as argument
System.out.println("After call a=" + obj.a + " b=" + obj.b);
}
}
Before call a=10 b=20 After call a=20 b=10
Explanation: In the above program, in

In the above figure
And when “obj.set(obj);” will execute it will pass object obj and reference of class Demo “o”