Got all that? Let’s review the rules on scope:
Local variables: In scope from declaration to the end of the block
Method parameters: In scope for the duration of the method
Instance variables: In scope from declaration until the object is eligible for garbage collection
Not sure what garbage collection is? Relax: that’s our next and final section for this chapter.
Now that we’ve played with our objects, it is time to put them away. Luckily, the JVM takes care of that for you. Java provides a garbage collector to automatically look for objects that aren’t needed anymore.
Remember, your code isn’t the only process running in your Java program. Java code exists inside of a JVM, which includes numerous processes independent from your applica-tion code. One of the most important of those is a built-in garbage collector.
All Java objects are stored in your program memory’s heap. The heap, which is also referred to as the free store, represents a large pool of unused memory allocated to your Java application. If your program keeps instantiating objects and leaving them on the heap, even-tually it will run out of memory and crash. Oh, no! Luckily, garbage collection solves this problem. In the following sections, we look at garbage collection.
Garbage collection refers to the process of automatically freeing memory on the heap by deleting objects that are no longer reachable in your program. There are many different algo-rithms for garbage collection, but you don’t need to know any of them for the exam.
As a developer, the most interesting part of garbage collection is determining when the memory belonging to an object can be reclaimed. In Java and other languages, eligible for garbage collection refers to an object’s state of no longer being accessible in a program and therefore able to be garbage collected.
Does this mean an object that’s eligible for garbage collection will be immediately garbage collected? Definitely not. When the object actually is discarded is not under your control, but for the exam, you will need to know at any given moment which objects are eligible for gar-bage collection.
Think of garbage-collection eligibility like shipping a package. You can take an item, seal it in a labeled box, and put it in your mailbox. This is analogous to making an item eligible for garbage collection. When the mail carrier comes by to pick it up, though, is not in your control. For example, it may be a postal holiday, or there could be a severe weather event. You can even call the post office and ask them to come pick it up right away, but there’s no way to guarantee when and if this will actually happen. Hopefully, they will come by before your mailbox fills with packages!
Java includes a built-in method to help support garbage collection where you can suggest that garbage collection run.
System.gc();
Just like the post office, Java is free to ignore you. This method is not guaranteed to do anything.