0
public class Employee {

    int age = 32;
    String name = "Kevin";

    public Employee updateEmployee(Employee e) {
        e = new Employee();
        e.age = 56;
        e.name = "Jeff";
        return e;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Employee t = new Employee();
        t.updateEmployee(t);
        System.out.println("age= " + t.age + " " + "name= " + " " + t.name);

    }

}

===================

OUTPUT:-
age= 32 name=  Kevin

Why is the output not 56 and Jeff. I updated the object reference "t" in the method? Please help.

nick
  • 51
  • 5

1 Answers1

1

If you see that in an IDE may be you will get a warning from the,

updateEmployee() method

stating,

The return value is not used anywhere, you can make the return type as void

As Java is always pass-by-value, if you need to update an object's state, then assign the return (updated) value back to it.

public static void main(String[] args) {
    Employee t = new Employee();
    t = t.updateEmployee(t);
    System.out.println("age= " + t.age + " " + "name= " + " " + t.name);
}

Output:

age= 56 name=  Jeff

Edit: It would be better if your update method just work on that this ref.

public void updateEmployee() {
    this.age = 56;
    this.name = "Jeff";
}

public static void main(String[] args) {
    Employee t = new Employee();
    t.updateEmployee();
    System.out.println("age= " + t.age + " " + "name= " + " " + t.name);
}