The concepts of "pass by reference" with objects and "pass by value" with primitives using Java are fundamental to developers.
1. Pass by Reference with Objects:
In Java, all object references are passed by value. However, this can be confusing because it often feels like "pass by reference." When you pass an object to a method, you are passing the reference (a pointer to the memory location of the object) by value. This means the method receives a copy of the reference, not the object itself, but it can still modify the object through this reference.
Pass By Reference means you are passing the address itself rather than passing the value.
Example:
class MyClass {
int value;
MyClass(int value) {
this.value = value;
}
}
public class Main {
public static void modifyObject(MyClass obj) {
obj.value = 10;
}
public static void main(String[] args) {
MyClass myObj = new MyClass(5);
modifyObject(myObj);
System.out.println(myObj.value); // Output: 10
}
}
In this example, `myObj` is passed to the `modifyObject` method. The method modifies `myObj.value` to 10. Because the reference to `myObj` was passed (even though itâs a copy of the reference), the method modifies the original object, and the change is reflected in the output.
2. Pass by Value with Primitives:
In Java, primitive data types (like `int`, `double`, `char`, etc.) are always passed by value. This means that when a primitive is passed to a method, a copy of the value is passed, and any modification inside the method does not affect the original value.
Pass by Value means passing a copy of the value to be passed.
Example:
public class Main {
public static void modifyValue(int x) {
x = 10;
}
public static void main(String[] args) {
int num = 5;
modifyValue(num);
System.out.println(num); // Output: 5
}
}
In this example, `num` is passed to the `modifyValue` method. The method attempts to change `x` to 10, but since `x` is a copy of `num`, this change does not affect the original `num`. The output remains 5.
Key Points:
- Objects: Java passes a copy of the object reference to methods, which allows the method to modify the object itself (as shown in the first example). This behavior often feels like "pass by reference" but is technically "pass by value of the reference."
- Primitives: Java passes a copy of the primitive value to methods, so changes inside the method do not affect the original value (as shown in the second example).
This distinction is critical in understanding how data is handled and modified when passed to methods in Java.