Demonstration of passing object reference by value as parameter in java methods .

ATTEMPTING TO REASSIGN OBJECT .

If you reassign an object reference inside java method it do not affect the original state of object outside that method .Below is an demonstration ,that shows java passes object reference by value .

public class n {
    public static void reassign(Person pe){ // local varaible p holds refernce of object with "original name"
        pe = new Person("New name"); //local varaible p holds refernce of object with "new name"
    // this reference is no more pointing to object with " original name "
}

    public static void main(String[] args) { 
        Person p = new Person("Original name ");
        System.out.println(" Name Before  reassign ::  "+p.getName()); 

        reassign(p); // passing object reference p of Person class 
        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 :: Original name
  1. Person object is created with " original name".

  2. 'p' holds reference(memory address) of person object with "original name" .

  3. Calling reassign method passing object reference 'p' as argument . Copy of reference 'p' is passed .

  4. 'pe' is the local variable of method reassign that initially contains the copy of memory address of Object with "original name " .

  5. After that reassign 'pee' to " new person("new name") " , now 'pee' points to object with "new name " but inside the reassign method , i do not affect the 'p' with "original name " .

  6. AFTER REASSIGNING .

    The reference 'p' still have reference pointing to Object with "Original name"