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.

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.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.