0
public class test {
     public static void main(String [] args) {
         Person p = new Person("ABC");
         p.setName("DEF");
         changePerson(p);
        System.out.println(p.getName());
    }

    public static void changePerson(Person p) {
         p.setName("GHI");
        p = new Person("JKL");
         p.setName("MNO");
        System.out.println(p.getName());
     }
 }

 class Person {
     String name;
 
    Person(String name) {
        this.name=name;
   }

   public void setName(String n) {
         name = n;
    }

     public String getName() {
       return name;
    }
}

output is:
MNO
GHI

Please can anybody explain this? I could not understand.

2
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by javax_
0
public static void changePerson(Person p) {
         p.setName("GHI");
         p = new Person("JKL");
         p.setName("MNO");
        System.out.println(p.getName());
     }

The above output is cause of the simple Pass by reference for objects in Java and illustrates how pointers are actually operating without you seeing them.

It is important to remember that when you declare an object like

Person p = new Person("ABC");

p is not the object, it holds a reference to the original object.
When you did p.setName("GHI"); , you actually modified the original object (created in the main) which was pointed to by "p" (local to changePerson() ), But when you did p=new Person("JKL"); , you changed object to which the version of "p" local to changePerson() was pointing to, So now "p" instead of pointing to the object that was created in you main now points to the object that was created in the changePerson() method.

But the change of value of "p" in changePerson() is local to that method cause "p" being a reference is itself passed by value, So the object which "p" points to in the main is never changed and hence GHI is printed in the main.

Sorry I couldn't make it less confusing than that.

0

Thanks for perfect explain my friend. I figured out very well.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.