Passing an object as parameter to method in java
In java there is only one way to pass parameter which is pass by value . It is applicable in both cases , primitive type(int , float ,etc) as well as in object reference . In both we pass copy of object reference(memory address of object).
public class n {
public static void changeName(Person p){
p .setName("New name");
}
public static void main(String[] args) {
Person p = new Person("Original name ");
System.out.println(" Name Before reassign :: "+p.getName());
changeName(p);
System.out.println("Name After reassign :: "+p.getName());
}
}
class Person{
String name;
Person(String n){
name = n;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
// OUTPUT
// Name Before reassign :: Original name
// Name After reassign :: New name
When object is passed as parameter , object itself is not pass , copy of its reference is passed holding same address.
It modifying the actual array object created in heap .
We can change the object state but not reassign object reference to new object in passing object as parameter to method.(CONTINUE IN NEXT POST).