Question
Does Java pass objects by value or by reference?
public class MyClass {
public static void main(String[] args) {
MyObject obj = new MyObject("myName");
changeName(obj);
System.out.print(obj.getName()); // This prints "anotherName"
}
public static void changeName(MyObject obj) {
obj.setName("anotherName");
}
}
Answer
Java passes all parameters by value. However, when it comes to objects, the value that is passed is the reference to the object, not the object itself. This can lead to confusion as it may appear that Java is passing objects by reference, but in reality, it is passing the reference value by value.
public class MyClass {
public static void main(String[] args) {
MyObject obj = new MyObject("myName");
changeName(obj);
System.out.print(obj.getName()); // Prints "anotherName"
}
public static void changeName(MyObject obj) {
obj.setName("anotherName"); // Changing the object's property
}
}
Causes
- In Java, primitive types (e.g., int, char) are passed directly by their value.
- Object references are also passed by value, meaning that the reference itself is copied, not the actual object.
Solutions
- To modify an object passed to a method, you must use the reference it points to, which can lead to changes in the original object outside of the method.
- Understanding this mechanism clarifies why changes to the object's state persist after the method call.
Common Mistakes
Mistake: Assuming Java passes objects themselves, rather than their references.
Solution: Recognize that Java passes the reference to the object, allowing you to modify its state but not the reference itself.
Mistake: Believing that changing the reference in a method will affect the original reference outside the method.
Solution: Understand that reassigning a reference within a method does not change the original reference in the calling scope.
Helpers
- Java pass by value
- Java pass by reference
- Java objects parameter passing
- Java method parameters
- Java object manipulation