0

Sorry for the potentially dumb question. I'm pretty new to java and I'm trying to understand objects. Have a look at this code:


public class Test {

    
    public static void main(String[] args) {
        Name name = new Name("john");;
        System.out.println(Name.returnName());
        name = new Name("jane");
        System.out.print(Name.returnName());
        
    }
    
}

Thís prints john and jane. Does that mean that when the code executes name = new Name("jane"); it deletes the previous object where the name is "john"? Thanks in advance.

Daavee18
  • 29
  • 5
  • 2
    If there are no more references to an object, then it becomes eligible for Garbage Collection. The GC will then eventually delete it. When and how it does that depends on the implementation and configuration of the GC. – Hulk Jan 17 '21 at 13:12
  • 1
    Related: https://stackoverflow.com/questions/28116708/when-does-java-calls-garbage-collector – Hulk Jan 17 '21 at 13:14
  • Also: https://stackoverflow.com/questions/1262328/how-is-the-java-memory-pool-divided?noredirect=1&lq=1 this explains how the mechanism is implemented in a few of the more popular GCs. – Hulk Jan 17 '21 at 13:15
  • Perhaps better: https://stackoverflow.com/questions/3315189/when-does-javas-garbage-collection-free-a-memory-allocation?noredirect=1&lq=1 – Hulk Jan 17 '21 at 13:29

2 Answers2

0

Remember every time you use the keyword new you're declaring a new instance of the class Name so the latest declaration will override the previous ones. If you want to store all the names.

1.You could store them in a List

ArrayList<Name> names = new ArratList<>();
names.add(new Name("John"));
names.add(new Name("Jane"));

2.Declare 2 different object of type Name like this:

Name name1 = new Name("john");;
System.out.println(name1.returnName());
Name name2 = new Name("jane");
System.out.print(name2.returnName());        
Zach_Mose
  • 357
  • 3
  • 7
0

No it doesn't happen that way.

When you assign a reference to an object to a variable, all that happens is that the previous reference (if any) stored in the variable is forgotten.

The object that the previous reference refers to is not immediately deleted. Indeed, it may never deleted. Any program whose correct behavior depends on specific objects being deleted (or finalized) is flawed.

Deletion of objects occurs when the garbage collector determines that an object can no longer be used. The specific criterion is that the object is no longer reachable; i.e. there is no way that the executing application can find the object.

One thing is guaranteed though. The JVM will always run the garbage collector in an attempt to reclaim enough space before it throws an OutOfMemoryError.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Did you mean to write “The JVM will always” instead of “Before the JVM will always”? – VGR Jan 17 '21 at 14:06