You never need to destroy an object

Bruce Eckel’s Thinking in Java Contents | Prev | Next

an object

most programming languages, the concept of the lifetime of a variable occupies
a significant portion of the programming effort. How long does the variable
last? If you are supposed to destroy it, when should you? Confusion over
variable lifetimes can lead to a lot of bugs, and this section shows how Java
greatly simplifies the issue by doing all the cleanup work for you.


procedural languages have the concept of
This determines both the visibility and lifetime of the names defined within
that scope. In C, C++ and Java, scope is determined by the placement of curly
So for example:

  int x = 12;
  /* only x available */
    int q = 96;
    /* both x & q available */
  /* only x available */
  /* q “out of scope” */

variable defined within a scope is available only to the end of that scope.

makes Java code easier to read. Since Java is a free form language, the extra
spaces, tabs and carriage returns do not affect the resulting program.

that you
do the following, even though it is legal in C and C++:

  int x = 12;
    int x = 96; /* illegal */

of objects

objects do not have the same lifetimes as primitives. When you create a Java
object using
it hangs around past the end of the scope. Thus if you use:


String s = new String("a string");

/* end of scope */

vanishes at the end of the scope. However, the
object that
was pointing to is still occupying memory. In this bit of code, there is no way
to access the object because the only handle to it is out of scope. In later
chapters you’ll see how the handle to the object can be passed around and
duplicated during the course of a program.

turns out that because objects created with
stay around for as long as you want them, a whole slew of programming problems
simply vanish in C++ and Java. The hardest problems seem to occur in C++
because you don’t get any help from the language in making sure that the
objects are available when they’re needed. And more importantly, in C++
you must make sure that you destroy the objects when you’re done with them.

More by Author

Must Read