Junior
What is the difference between passing an object by reference and by value?
sobes.tech AI
Answer from AI
In Java, objects are always passed by value. This value is a copy of the reference to the object in memory.
Pass by value:
- A copy of the value of the variable is passed.
- For primitive types (int, boolean, float, etc.), a copy of the actual value is passed. Changing the copy does not affect the original.
- For reference types (objects, arrays), a copy of the reference to the object in memory is passed. Both references point to the same object. Changing the state of the object (e.g., calling a setter) through any of the references will be visible through the other. However, if one reference is assigned a new object, it does not affect the object referenced by the other.
Pass by reference (not present in Java):
- The reference to the variable or object itself is passed.
- Changing the value of the variable or object through the passed reference will change the original.
Example with an object:
// Example with an object
class MyObject {
int value;
MyObject(int value) {
this.value = value;
}
}
public class Main {
public static void changeObjectValue(MyObject obj) {
obj.value = 100; // Changes the state of the object that 'obj' points to
}
public static void reassignObjectReference(MyObject obj) {
obj = new MyObject(200); // Changes the local reference 'obj' inside the method, does not affect the original reference
}
public static void main(String[] args) {
MyObject originalObject = new MyObject(10);
System.out.println("Original value before changeObjectValue: " + originalObject.value); // 10
changeObjectValue(originalObject);
System.out.println("Original value after changeObjectValue: " + originalObject.value); // 100
MyObject anotherObject = new MyObject(30);
System.out.println("Another value before reassignObjectReference: " + anotherObject.value); // 30
reassignObjectReference(anotherObject);
System.out.println("Another value after reassignObjectReference: " + anotherObject.value); // 30
}
}
Example with a primitive type:
// Example with a primitive type
public class Main {
public static void changePrimitiveValue(int num) {
num = 50; // Changes the copy of 'num' inside the method
}
public static void main(String[] args) {
int originalNum = 10;
System.out.println("Original num before changePrimitiveValue: " + originalNum); // 10
changePrimitiveValue(originalNum);
System.out.println("Original num after changePrimitiveValue: " + originalNum); // 10
}
}