Java supports only Call by Value, during method calling.
It doesn’t support
Call by Reference. Call by value allows, passing the values through the
parameters respectively.
Pass Primitive data types as parameter
When a variable is passed to a method, Java passes a copy of the value only. Any
changes made inside the method do not affect the original variable.
void change(int x) { Output:
x = x + 10; Before: 5
} After: 5
public static void main(String[] args){
[Link](“Before: “ + a); The value of a remain 5
int a = 5; because only the value in a
change(a); was passed, not the actual
[Link](“After: “ + a);
} variable.
Pass Objects as parameter
Whenever the Objects is passed to a method, java passes a copy of the
reference (memory address), not the object itself. Modifying the object's fields
will affect the original object, but reassigning the reference won’t.
void modify(Person p) { The name changes to "John"
// Modifies the original object
[Link] = "John";
because both p and obj point
} to the same object.
class Person {
String name;
}
public static void main(String[] args){
Person obj = new Person();
[Link] = "Mike";
modify(obj);
[Link]([Link]);
// Output: John
}
But if you reassign the reference inside the method:
void swap(Person p, Person q){ Output:
Person t;
Before Swapping (Main)
[Link](“Before Swap
Mike
(Swap)”);
Jhon
[Link]([Link]);
[Link]([Link]);
Before Swapping (swap)
Mike
Jhon
t=p;
p=q;
After Swapping (swap)
q=t;
Jhon
Mike
[Link](“After Swap
(Swap)”);
After Swapping (Main)
[Link]([Link]);
Mike
[Link]([Link]);
Jhon
}
Here, the swap method, only
class Person { swaps the references value
String name;
}
between p and q, but not the
values in name data field of
public static void main(String[] args){ the object p and q. So the
Person obj1 = new Person(); swapping operation not get
[Link] = "Mike";
reflected in the main
Person obj2 = new Person(); function.
[Link] = "Jhon"; This concludes that java
supports only the pass by
[Link](“Before Swapping
value not reference.
(Main)”);
[Link]([Link]);
[Link]([Link]); If java does the call by
reference then the swap
operations result will also
swap(obj1, obj2);
reflected in obj1 and obj2
[Link](“After Swapping at the main method.
(Main)”);
[Link]([Link]);
[Link]([Link]);
}