Is Java “pass-by-reference” or “pass-by-value”?

Myth: "Objects are passed by reference, primitives are passed by value"

To make a long story short -  Java is always pass by value, there is nothing like pass by reference in java.
 
Does this sound strange and confusing?

Okay to clear your confusion, lets quickly understand what these term means-
1) pass by value means that we pass copy of actual variables
2) pass by reference  means that we pass memory address actual variables


Now, Lets see how java behaves for different cases. In java there are two types of variable-
1) Primitive variable (Holds value) and
2) Non primitive variable (Holds only address of object)


In the case of primitive types, Java behaviour is simple and non confusing:


The value is copied in another instance of the primitive type.


In case of non primitives or Objects, this is also the same but looks confusing:

Object variables are buckets(pointers) holding only Object’s address that was created using the "new" keyword.
 
In this case also, object variable is copied i.e. bucket is copied and a new bucket is created holding same object’s address.


It doesn't matter what the value is in Java: primitive or address(non-primitive) of object, it is ALWAYS passed by value.

A very small,simple and clear example to validate this.
public void example() {
    Sample sample = null;
    change(sample);

### sampleVar is still null here ###
}
private void change( Sample sampleVar) {
    sampleVar = new Sample();
}

So we can say - In Java only references are passed and are passed by value

More info-
    • C does NOT support pass by reference. It is ALWAYS pass by value.
    • C++ support pass by value and pass by reference, but pass by value is default.
    • C# supports pass by value and pass by reference
    • Python neither passes by object nor by reference. Python passes by ‘Assignment‘
    • PHP supports pass by value and pass by reference






Comments