0

Below is my code. I set the object to null, still my print statement can print the property name correctly. Can anyone tell me what's happening?

public class MyClass {
    String name;

    public String getName() {
        return name;
    }

    public void setName(String s) {
        name = s;
    }
    public static void main(String args[]) {
        MyClass obj = new MyClass();
        obj.changeName(obj);

        System.out.println("Name = " + obj.getName());
    }
    public MyClass() {
        name = "A";
    }

    public void changeName(MyClass obj) {
         obj.setName("B");
         obj = null;
    }
}

Output is:

Name = B

Supriya
  • 290
  • 4
  • 15

2 Answers2

4

obj = null only sets the local variable obj of the method changeName to null. It doesn't affect the object referenced by that variable in any way.

Eran
  • 387,369
  • 54
  • 702
  • 768
-1

I apologize if this incorrect, I have been working with Kotlin lately and it’s messing with my head.

I would try either

 public void changeName(MyClass obj) {
     obj.setName("B");
     obj.setName(null);
}

Or you might try

 public void changeName(MyClass obj) {
     obj.setName("B");
     obj.setName().empty;
}

I think it has something to do with the fact your passing an object to that method and setting the value of the object and the null must be either nulling the incorrect object or the setName value is still holding its value even though the object itself is null. So you need to set the setName value to null I think.

Vahalaru
  • 380
  • 4
  • 15
  • You might also try making the method return an object? Then you could receive that object and null it at that point? – Vahalaru Dec 31 '17 at 07:37