0

I want to ask if garbage collector automatically deletes unused objects in a Java program or it should be manually done by assigning an object to null?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 2
    It is automatically done in Java. Null assignment is needed only for programming logic and not for garbage collection. – WonderWoman Dec 08 '18 at 11:25
  • Automatically ... – Ekrem Dec 08 '18 at 11:26
  • Setting a variable to null is not deleting an object, but it may allow a now-unreferenced object to be automatically garbage collected. – khelwood Dec 08 '18 at 11:42
  • Setting a variable to null is like deleting somebody's phone number from your phone: you can't call it any more, but their phone still exists, and can be called by anybody else who happens to have their number. – Andy Turner Dec 08 '18 at 12:48
  • 1
    @SandyC - *"Null assignment is needed only for programming logic and not for garbage collection. "* Not quite. There are some occasions where assigning a null avoids a memory leak; e.g. look at the source code for `ArrayList.clear()` ... – Stephen C Dec 08 '18 at 14:03

1 Answers1

0

From here

In a programming language like C, allocating and deallocating memory is a manual process. In Java, process of deallocating memory is handled automatically by the garbage collector.

I'd suggest you reading the full article. You will have a good grasp of how GC works in Java. HTH.

Lavish Kothari
  • 2,211
  • 21
  • 29