Is Java Pass By Value or Pass By Reference?

Pass value. This concept in Java is a little confusing because you can modify members of arguments. This example illustrates the pass value behavior:

public class Main {

    public static void doesNotChangeValueAfterFunction(Integer integer){
        integer = 10;
    }
    public static void main(String[] args) {
        Integer twenty = 20;

        doesNotChangeValueAfterFunction(twenty);

        System.out.println(twenty);

    }
}

The output of this program is “20” because “integer” is passed value. This example illustrates a pseudo pass reference behavior:

public class Main {

    static class IntegerWrapper{
        Integer integer;
    }

    public static void valueIsAlteredAfterFunctionCall(IntegerWrapper integerWrapper){
        integerWrapper.integer = 100;
    }
    public static void main(String[] args) {
        IntegerWrapper twentyWrapper = new IntegerWrapper();
        twentyWrapper.integer = 20;

        valueIsAlteredAfterFunctionCall(twentyWrapper);

        System.out.println(twentyWrapper.integer);

    }
}

The output of this program is “100” because we are modifying the
“integer” instance variable and not the actual method argument. This
is still pass value behavior but is confusing. When one hears pass value,
they think that object members are also passed value but that is not the
case.

It is especially important to understand the aforementioned concept when dealing with linked lists and binary trees due to the node pointers.

Leave a Reply

Your email address will not be published. Required fields are marked *