public class Bar { private String property; public Bar (String property){ this.property = property; } public String getProperty() { return property; } public void setProperty(String property) { this.property = property; } } public class Main { public static void main(String[] args){ Bar bar = new Bar("bar"); method1(bar); // here we are changing the instance that the reference variable "bar" refers method2(bar); // here we are not changing the reference! } public static void method1(Bar m1bar) { mbar.setProperty("modifybar"); } public static void method2(Bar m2bar) { Bar newbar = new Bar("newbar"); m2bar = newbar; } }
In above example, method1() logical address bits of first instance(bar) are copied to another reference variable(m1bar), thus resulting both references to point a single memory location where actual object is stored. Remember, making another reference to null will not make first reference also null. But, in changing the property from either reference variable have impact seen in other reference also. But in method2() we are creating new reference “newbar” of same class i.e. new memory location of instance and after that change the value of the passing reference variable i.e m2bar assign to new memory location.
Let’s see step by step in java when we pass any reference of custom types as any method parameters always the memory address is copied to new reference variable. See in below picture:
1. Bar bar = new Bar(“bar”);
This statement will create an instance of class Bar, with “property” initialized to “bar”. The reference to this created instance is assigned to variable bar;
2. define public static void method1(Bar m1bar)
In this line of execution then a reference of type Bar with a name m1bar is declared and it’s initially assigned to null.
3. call of method1(m1bar)
This statement assign same memory location of object with both reference variables.
4. mbar.setProperty(“modifybar”);
This statement change the value property of instance and it is change for both reference variables.
5. in method2(m2bar) create new reference with other instance with property “newbar” as Bar
6. newbar = new Bar(“newbar”);
7. m2bar=newbar
Here, we have three reference variables bar, m2bar and newbar when statement executes, m2bar and newbar will point to same instance created inside the method. But bar is unchanged and it is continually pointing to instance, it was pointing originally.
Hope it help to clear you concept about pass by value in java.
Happy learning!!!.