Java Pass By Value or Reference
In this post, we will see java is pass by value or reference. In Java, method arguments are passed by value. This means that when you pass an argument to a method, the method receives a copy of the value of the argument, rather than a reference to the original variable.
Java Pass By Value Example Code:
public class TestPassByValue {
public static void main(String[] args) {
int x = 5;
System.out.println("Before calling the method, x = " + x);
changeValue(x);
System.out.println("After calling the method, x = " + x);
}
public static void changeValue(int x) {
x = 10;
}
}
Output:
Before calling the method, x = 5
After calling the method, x = 5
As you can see, the value of x
is not changed by the changeValue
method, because the method receives a copy of the value of x
, rather than a reference to the original variable.
It’s worth noting that if you pass an object to a method, the method can still modify the object itself, even though the method receives a copy of the reference to the object, rather than a reference to the original variable.
Java Pass By Reference Example:
public class TestPassByReference {
public static void main(String[] args) {
MyObject obj = new MyObject();
obj.value = 5;
System.out.println("Before calling the method, obj.value = " + obj.value);
changeValue(obj);
System.out.println("After calling the method, obj.value = " + obj.value);
}
public static void changeValue(MyObject obj) {
obj.value = 10;
}
}
class MyObject {
int value;
}
Output:
Before calling the method, obj.value = 5
After calling the method, obj.value = 10
This is because the changeValue
method modifies the value
field of the obj
object, even though it receives a copy of the reference to the obj
object.
Thanks for Reading..