Objects come all different shapes and sizes and consume varying amounts memory
Ordering Elements in a Class 35
Let’s look at a few examples to help you remember this. The fi rst example contains one of each element:
import java.util.*;
package structure; // DOES NOT COMPILE
String name; // DOES NOT COMPILE
public class Meerkat { }There are two problems here. One is that the package and import statements are reversed. Though both are optional, package must come before import if present. The other issue is that a fi eld attempts declaration outside a class. This is not allowed. Fields and methods must be within a class.
36 Chapter 1 ■ Java Building Blocks
Destroying Objects
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 algorithms for garbage collection, but you don’t need to know any of them for the exam. You do need to know that System.gc() is not guaranteed to run, and you should be able to recognize when objects become eligible for garbage collection.
Let’s start with the fi rst one. Java provides a method called System.gc(). Now you might think from the name that this tells Java to run garbage collection. Nope! It meekly suggests that now might be a good time for Java to kick off a garbage collection run. Java is free to ignore the request.
|