New Concepts in Java

Packages

Packages are groups of similar classes, that can be, but are not necessarily related to each other through an inheritance structure. Packages are classes organised into directories on a file system.

  • Packages are '.' separated words, where the package refers to the directory that the class files are in. For example java.awt (the directory /java/awt/ is a package that stores the classes for creating buttons, textfields, etc.

  • A package can also contain more packages in a subfolder. For example, java.awt.event contains classes for events, within the awt package.

  • Use the import keyword to load in packages.

  • Multiple classes can be loaded using the * character. So, for example,import java.awt.*; imports all the classes in the awt package, but please note, it does not include classes in the sub-packages, so, you must explicitly import java.awt.event.*;.

  • In a source file, if no package name is defined on an import e.g. import SomeClass; then it is assumed that the class SomeClass is in the same directory as the source file.

Packages are very similar to a combination of C++ namespaces and includes, only a lot easier to use.

Garbage Collection

Java does not suffer from the memory leaks like C++, due to the addition of an embedded Garbage Collector (GC) and carefully structured reference counting. The GC can be run in three ways:

  • The system calls the GC when memory is low.

  • The system calls the GC when the CPU is idle.

  • The user can call the GC directly, but since the GC runs as a thread in a threaded environment, there is no guarantee that it will run immediately.