-5

i create Object of class A. at that time java occupy memory for class A. but when i assign null in object of Class A then it can free memory of that object

class A{
    public long num = 28115733;

}
kosa
  • 65,990
  • 13
  • 130
  • 167

4 Answers4

6

If you assign Object of class A reference to null, then Object A is eligible for GC (it may not immediately release memory) .

When memory will be freed is upto JVM and garbage collector (GC) algorithms being used.

kosa
  • 65,990
  • 13
  • 130
  • 167
2

You cannot be sure about that. When you assign null to an object reference, then the object pointed to by that reference is eligible for Garbage Collection.

But it is completely upto the JVM when it releases the memory occupied by that object.

May be when JVM sees that the memory is getting low, then it can kick off the garbage collector to free up some memory. But that is completely a background process. You don't have to worry about that. Also, if you want to explicitly tell the JVM to recollect memory, then you can add a call to System.gc(). But again JVM will not immediately start the Garbage Collection process. That would be on JVM only.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
0

when i assign null in object of Class A then it can free memory of that object

Yes, it can but it won't free memory until it has to.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

Memory in Java is reclaimed by the garbage collector (a process which looks for unreachable objects and returns their memory for use) You do not need to explicitly set an object to null for this to happen.

DuncanACoulter
  • 2,095
  • 2
  • 25
  • 38