Java Pass-by-Reference
In Java, passing parameters can be done using one of two fundamental methods. Pass-by-value is used for the first and pass-by-reference is used for the second. One thing to keep in mind in this situation is that pass-by-value is used when passing a primitive type to a method. Java enables pass by value; pass by reference cannot be used to directly provide primitive types to a method.
However, pass-by-reference is always used to implicitly pass all non-primitive types, which include objects of any class.
Passing a variable by value essentially means sending its actual value, whereas passing a variable by reference essentially means sending the memory location of the variable where it is stored.
Refer the following example to understand how pass-by-reference work:
PassByReference.java
class PassByReference {
/* we are creating a class named passByReference through which we access the
* objects of this class
* we pass the ojects with the help of this class name to the instance
* methods of the same class.
* this means with the passed object reference we access the instance
* variables of this class
*/
int a = 10;
void refer(PassByReference pbr) {
pbr.a = pbr.a+10; // accessing or updating instance variable with object
// reference
}
public static void main(String[] args) {
PassByReference pbr = new PassByReference();
System.out.println("Before pass-by-reference: " + pbr.a);
//value before upadating
pbr.refer(pbr);
System.out.println("After pass-by-reference: " + pbr.a);
//after updating through object reference
}
}
Output:

Generally, primitive data types are passed by value, but they can be accessed through object reference.
This can be done in three ways:
- Inside a class, make the member variable public.
- Return a value from a method and update the same inside the class.
- Make a single element array and send it to the method as a parameter.
Mistakes to be rectified with object reference:
- attempting to reference-modify an immutable value.
- attempting to reference-modify a primitive variable.
- When you modify a mutable object argument in a method, the expected behaviour of the real object remains unchanged.
Points to be noted:
- Java always sends value-based parameter variables.
- Java object variables always refer to the actual object's memory heap location.
- When an object is passed to a method, its value can be altered.
- Even if a new value is supplied to an immutable object, its value cannot be altered.
- Passing a copy of the item is referred to as "passing by value."
- Passing a variable's actual memory reference is referred to as "passing by reference."