In Java, strictly speaking, there is no "call by reference" mechanism as we have seen in some other programming languages like C++.
In Java, all arguments to methods are passed by value. However, the confusion arises because when we pass an object to a method, we are actually passing the reference to that object by value.
Let's clarify this with an example:
class YourClass { int value; YourClass(int value) { this.value = value; } } public class CallByReferenceExample { public static void main(String[] args) { YourClass obj = new YourClass(10); System.out.println("Before method call: obj.value = " + obj.value); // Output: Before method call: obj.value = 10 modifyObject(obj); System.out.println("After method call: obj.value = " + obj.value); // Output: After method call: obj.value = 20 } public static void modifyObject(YourClass object) { object.value = 20; System.out.println("Inside method: object.value = " + object.value); // Output: Inside method: object.value = 20 } }
Before method call: obj.value = 10 Inside method: object.value = 20 After method call: obj.value = 20
However, it's crucial to understand that reassigning the reference within the method will not affect the original reference outside the method.
class YourClass { int value; YourClass(int value) { this.value = value; } } public class CallByReferenceExample { public static void main(String[] args) { YourClass obj = new YourClass(10); System.out.println("Before method call: obj.value = " + obj.value); // Output: Before method call: obj.value = 10 modifyObject(obj); System.out.println("After method call: obj.value = " + obj.value); // Output: After method call: obj.value = 10 } public static void modifyObject(YourClass object) { // This will not affect the original reference object = new YourClass(30); System.out.println("Inside method: with new object reference value = " + object.value); // Output: Inside method: with new object reference value = 30 } }
If we run this modified version of the example, we'll see that the value of "obj.value" remains 20, as the reference obj remains unchanged outside the method.
Before method call: obj.value = 10 Inside method: with new object reference value = 30 After method call: obj.value = 10
even though we say that Java is pass-by-value, the behaviour we observe is similar to "call by reference" because when we pass an object to a method, we are actually passing a copy of the reference to that object, not the object itself.
This means both the original reference and the copied reference point to the same object in memory. As a result, modifications made to the object's state within the method are visible outside the method.