Sometimes, a Java program will create many objects which are used only once. For example, a program may create an object in the body of a loop that is used to hold ``temporary'' information that is only required for the particular iteration of the loop in which it is created. Consider the following:
for (int i = 0; i < 1000000; ++i)
{
SomeClass obj = new SomeClass (i);
System.out.println (obj);
}
This creates a million instances
of the SomeClass class and prints them out.
If the SomeClass class implements a setInt method,
we can reuse an a single object instance like this:
SomeClass obj = new SomeClass ();
for (int i = 0; i < 1000000; ++i)
{
obj.setInt (i);
System.out.println (obj);
}
Clearly, by reusing a single object instance,
we have dramatically reduced the amount of garbage produced.