java – do objects created in methods only live for the life of the method execution? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of java – do objects created in methods only live for the life of the method execution? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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();

Answer

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.

We are here to answer your question about java – do objects created in methods only live for the life of the method execution? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji