Is Java "pass-by-reference" or "pass-by-value"?

Java is pass-by-value, but it's important to understand how this works with respect to primitive types and objects.

When you pass a variable to a method in Java, you're passing a copy of the value of that variable. For primitive types (like int, double, char, etc.), the value itself is directly passed. For objects, you're passing a copy of the reference to the object (which effectively points to the object in memory).

Let's see this with an example:

java

public class PassByValueExample {
    public static void main(String[] args) {
        int x = 10;
        System.out.println("Before: x = " + x);
        modifyValue(x);
        System.out.println("After: x = " + x);
        
        StringBuilder str = new StringBuilder("Hello");
        System.out.println("Before: str = " + str);
        modifyReference(str);
        System.out.println("After: str = " + str);
    }

    public static void modifyValue(int value) {
        value = 20;
    }
    
    public static void modifyReference(StringBuilder builder) {
        builder.append(", World!");
    }
}

In this example:

    The modifyValue method takes an int argument. However, when you call this method and pass the x variable to it, the value 10 is copied into the parameter value. Modifying value within the method does not affect the original x variable outside the method, since they are independent copies.

    The modifyReference method takes a StringBuilder argument. Even though you're passing a copy of the reference, both the original reference and the copy reference still point to the same object in memory. As a result, modifications made to the object within the method (append(", World!")) are visible outside the method as well.

In summary, Java is pass-by-value, and when you pass an object to a method, you're passing a copy of the reference to that object. This distinction is important for understanding how changes to variables and objects affect the original values outside of method calls.

Comments