Java is pass by value but when we pass object refrence , reference value is get pass to method and from there method can change the value of object members.
Look at following code
public class Passbyvalue {
public static void main(String[] args) {
// TODO code application logic here
Animal animal=new Animal();
animal.name="Dog";
System.out.println(animal.name);
testIt(animal);
System.out.println(animal.name);
}
public static void testIt(Animal animal){
animal.name="Cat";
}
}
Output
Dog
Cat
This is because both reference( Original and method) poiting to same object.
__________
| |
| |<------------- Orignal Refernce
| Object |
| |<------------- Method Refernce
| |
|__________|
If you want to see this effect more clearly create new object in method
public class Passbyvalue {
public static void main(String[] args) {
Animal animal=new Animal();
animal.name="Dog";
System.out.println(animal.name);
testIt(animal);
System.out.println(animal.name);
}
public static void testIt(Animal animal){
animal=new Animal();
animal.name="Cat";
}
}
Output
Dog
Dog
Now method reference is poting to other Object in heap.
__________
| |
| |
| Orignal |<------------- Orignal Refernce
| Object |
| |
|__________|
__________
| |
| |
| Method |<------------- Method Refernce
| Object |
| |
|__________|
Hope this will help