Search code examples
javaoop

java - do objects created in methods only live for the life of the method execution?


I'm programming a java app and trying to educate myself on memory management. If instantiate a String object in a method of an object that's already been created, will that String object exist in memory after the method is executed? Take this example. Does newString exist in memory after i execute myObject.setNewName()? or does java destroy those objects if they are not instance variables?

public class MyObject(){

    private String name;
    private Integer id;

    public myObject(Integer id, String name){
        this.id   = id;
        this.name = name;
    }

    public void setNewName(){

        String newString = "This is a new name";
        this.name = newString;
    }
}

another file

MyObject myObject = new MyObject(4,"Bob");

myObject.setNewName();

Solution

  • If the reference to the object is held beyond the method, for example assigned to a field, then the object won't be garbage collected when the method ends.

    Objects only assigned to local variables will be "not reachable" when the method ends, so will be marked for garbage collection.

    It's all to do with scope. If the reference to the object is still in scope, it will remain in memory.