In Java, all arguments to methods are passed by value.
This means that when we pass a parameter to a method, a copy of the value of the parameter is made and passed to the method.
Changes made to the parameter within the method do not affect the original variable passed to the method.
Let's illustrate this with an example:
public class CallByValueExample { public static void main(String[] args) { int x = 10; System.out.println("Before method call: x = " + x); modifyValue(x); System.out.println("After method call: x = " + x); } public static void modifyValue(int value) { value = 30; System.out.println("Inside method: value = " + value); } }
Before method call: x = 10 Inside method: value = 30 After method call: x = 10
the value of "x" is passed to the "modifyValue()" method. Inside the method, the parameter value is modified to 30.
However, this change does not affect the original variable x outside the method.
This demonstrates that changes made to the parameter within the method are local to that method and do not affect the original value passed to it.
It's essential to understand that while objects are passed by value in Java, what is actually being passed is a reference to the object (not the object itself).
So, modifications to the object's state can be observed outside the method.
However, if you try to reassign the reference to a new object within the method, it won't affect the original reference outside the method.
class YourClass { int value; YourClass(int value) { this.value = value; } } public class CallByValueObjectExample { public static void main(String[] args) { YourClass obj = new YourClass(10); System.out.println("Before method call: obj.value = " + obj.value); modifyObject(obj); System.out.println("After method call: obj.value = " + obj.value); } public static void modifyObject(YourClass object) { object.value = 30; System.out.println("Inside method: object.value = " + object.value); } }
Before method call: obj.value = 10 Inside method: object.value = 30 After method call: obj.value = 30
the changes made to the object's state within the method are reflected outside the method because the object reference is passed by value.
However, if we try to reassign the object reference to a new object within the method, it won't affect the original reference outside the method.