Is Java Pass By Value or Pass By Reference?

Pass by value. This concept in Java is a little confusing because you can modify members of arguments. This example illustrates the pass by 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 by value. This example illustrates a pseudo pass by 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 by value behavior but is confusing. When one hears pass by value, they think that object members are also passed by 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.