Developer.com Logo Click here to support our advertisers
Click here to support our advertisers
SHOPPING
JOB BANK
CLASSIFIEDS
DIRECTORIES
REFERENCE
Online Library
LEARNING CENTER
JOURNAL
NEWS CENTRAL
DOWNLOADS
COMMUNITY
CALENDAR
ABOUT US

Journal:

Get the weekly email highlights from the most popular journal for developers!
Current issue
developer.com
developerdirect.com
htmlgoodies.com
javagoodies.com
jars.com
intranetjournal.com
javascripts.com

All Categories : Java

Chapter 11

Overview of the Standard Packages

by Michael Morrison


CONTENTS


Code reuse is one of the most significant benefits of using object-oriented design practices. Creating reusable, inheritable classes can save amazing amounts of time and energy-which in turn greatly boosts productivity. Java itself takes code reuse to heart in its implementation of a wide variety of standard objects available to Java programmers. The standard Java objects are known collectively as the Java standard packages.

The Java standard packages contain groups of related classes. Along with classes, the standard Java packages also include interfaces, exception definitions, and error definitions. Java is composed of six standard packages: the language package, the utilities package, the I/O package, the networking package, the windowing package, and the applet package. In this chapter, you learn what each package is and what classes and interfaces comprise each.

The Language Package

The Java language package, also known as java.lang, provides classes that make up the core of the Java language. The language package contains classes at the lowest level of the Java standard packages. For example, the Object class, from which all classes are derived, is located in the language package.

It's impossible to write a Java program without dealing with at least a few of the elements of the language package. You'll learn much more about the inner workings of the language package in the next chapter. The most important classes contained in the language package follow:

  • The Object class
  • Data type wrapper classes
  • The Math class
  • String classes
  • System and Runtime classes
  • Thread classes
  • Class classes
  • Exception-handling classes
  • The Process class

The Object Class

The Object class is the superclass for all classes in Java. Because all classes are derived from Object, the methods defined in Object are shared by all classes. This results in a core set of methods that all Java classes are guaranteed to support. Object includes methods for making copies of an object, testing objects for equality, and converting the value of an object to a string.

Data Type Wrapper Classes

The fundamental data types (int, char, float, and so on) in Java are not implemented as classes. It is frequently useful, however, to know more information about a fundamental type than just its value. By implementing class wrappers for the fundamental types, additional information can be maintained-you can also define methods that act on the types. The data type wrapper classes serve as class versions of the fundamental data types and are named similarly to the types they wrap. For example, the type wrapper for int is the Integer class. Following are the Java data type wrapper classes:

  • Boolean
  • Character
  • Double
  • Float
  • Integer
  • Long

Type wrappers are also useful because many of Java's utility classes require classes as parameters, not simple types. It is worth pointing out that type wrappers and simple types are not interchangeable. However, you can get a simple type from a wrapper through a simple method call, which you learn about in the next chapter.

The Math Class

The Math class serves as a grouping of mathematical functions and constants. It is interesting to note that all the variables and methods in Math are static and that the Math class itself is final. This means that you can't derive new classes from Math. Additionally, you can't instantiate the Math class. It's best to think of the Math class as just a conglomeration of methods and constants for performing mathematical computations.

The Math class includes the E and PI constants, methods for determining the absolute value of a number, methods for calculating trigonometric functions, and minimum and maximum methods, among others.

String Classes

For various reasons (mostly security related), Java implements text strings as classes, rather than forcing the programmer to use character arrays. The two Java classes that represent strings are String and StringBuffer. The String class is useful for working with constant strings that can't change in value or length. The StringBuffer class is used to work with strings of varying value and length.

The System and Runtime Classes

The System and Runtime classes provide a means for your programs to access system and runtime environment resources. Like the Math class, the System class is final and is entirely composed of static variables and methods. The System class basically provides a system-independent programming interface to system resources. Examples of system resources include the standard input and output streams, System.in and System.out, which typically model the keyboard and monitor.

The Runtime class provides direct access to the runtime environment. An example of a runtime routine is the freeMemory() method, which returns the amount of free system memory available.

Thread Classes

Java is a multithreaded environment and provides various classes for managing and working with threads. Following are the classes and interfaces used in conjunction with multithreaded programs:

  • Thread: Used to create a thread of execution in a program.
  • ThreadDeath: Used to clean up after a thread has finished execution.
  • ThreadGroup: Useful for organizing a group of threads.
  • Runnable: Provides an alternative means of creating a thread without subclassing the Thread class.

Threads and multithreading are covered in detail in Chapter 9, "Threads and Multithreading."

Class Classes

Java provides two classes for working with classes: Class and ClassLoader. The Class class provides runtime information for a class, such as the name, type, and parent superclass. Class is useful for querying a class for runtime information, such as the class name. The ClassLoader class provides a means to load classes into the runtime environment. ClassLoader is useful for loading classes from a file or for loading distributed classes across a network connection.

Exception-Handling Classes

Runtime error handling is a very important facility in any programming environment. Java provides the following classes for dealing with runtime errors:

  • Throwable: Provides low-level error-handling capabilities such as an execution stack list.
  • Exception: Derived from Throwable to provide the base level of functionality for all the exception classes defined in the Java system. Used to handle normal errors.
  • Error: Derived from Throwable (as is the Exception class) but is used to handle abnormal errors that aren't expected to occur. Very few Java programs worry with the Error class; most use the Exception class to handle runtime errors.

Error handling with exceptions is covered in detail in Chapter 10, "Exception Handling."

The Process Class

Java supports system processes with a single class, Process. The Process class represents generic system processes that are created when you use the Runtime class to execute system commands.

The Utilities Package

The Java utilities package, also known as java.util, provides various classes that perform different utility functions. The utilities package includes a class for working with dates, a set of data structure classes, a class for generating random numbers, and a string tokenizer class, among others. You'll learn much more about the classes that make up the utilities package in Chapter 13, "The Utilities Package." The most important classes contained in the utilities package follow:

  • The Date class
  • Data structure classes
  • The Random class
  • The StringTokenizer class
  • The Properties class
  • The Observer classes

The Date Class

The Date class represents a calendar date and time in a system-independent fashion. The Date class provides methods for retrieving the current date and time as well as computing days of the week and month.

Data Structure Classes

The Java data structure classes and interfaces implement popular data structures for storing data. The data structure classes and interfaces are as follows:

  • BitSet: Represents a set of bits, also known as a bitfield.
  • Dictionary: An abstract class that provides a lookup mechanism for mapping keys to values.
  • Hashtable: Derived from Dictionary to provide additional support for working with keys and values.
  • Properties: Derived from Hashtable to provide the additional functionality of being readable and writable to and from streams.
  • Vector: Implements an array that can dynamically grow.
  • Stack: Derived from Vector to implement a classic stack of last-in-first-out (LIFO) objects.
  • Enumeration: This interface specifies a set of methods for counting (iterating) through a set of values.

The Random Class

Many programs, especially programs that model the real world, require some degree of randomness. Java provides randomness with the Random class. The Random class implements a random-number generator by providing a stream of pseudo-random numbers. A slot-machine program is a good example of one that would make use of the Random class.

The StringTokenizer Class

The StringTokenizer class provides a means of converting text strings into individual tokens. By specifying a set of delimiters, you can parse text strings into tokens using the StringTokenizer class. String tokenization is useful in a wide variety of programs, from compilers to text-based adventure games.

The Observer Classes

The model-view paradigm is becoming increasingly popular in object-oriented programming. This model divides a program into data and views on the data. Java supports this model with the Observable class and the Observer interface. The Observable class is subclassed to define the observable data in a program. This data is then connected to one or more observer classes. The observer classes are implementations of the Observer interface. When an Observable object changes state, it notifies all its observers of the change.

The I/O Package

The Java I/O package, also known as java.io, provides classes with support for reading and writing data to and from different input and output devices-including files. The I/O package includes classes for inputting streams of data, outputting streams of data, working with files, and tokenizing streams of data. You'll learn a lot more about the classes that make up the I/O package in Chapter 14, "The I/O Package." The most important classes contained in the I/O package follow:

  • Input stream classes
  • Output stream classes
  • File classes
  • The StreamTokenizer class

Input Stream Classes

Java uses input streams to handle reading data from an input source. An input source can be a file, a string, memory, or anything else that contains data. The input stream classes follow:

  • InputStream
  • BufferedInputStream
  • ByteArrayInputStream
  • DataInputStream
  • FileInputStream
  • FilterInputStream
  • LineNumberInputStream
  • PipedInputStream
  • PushbackInputStream
  • SequenceInputStream
  • StringBufferInputStream

The InputStream class is an abstract class that serves as the base class for all input streams. The InputStream class defines an interface for reading streamed bytes of data, finding out the number of bytes available for reading, and moving the stream position pointer, among other things. All the other input streams provide support for reading data from different types of input devices.

Output Stream Classes

Output streams are the counterpart to input streams; they handle writing data to an output source. Similar to input sources, output sources include files, strings, memory, and anything else that can contain data. The output stream classes defined in java.io follow:

  • OutputStream
  • BufferedOutputStream
  • ByteArrayOutputStream
  • DataOutputStream
  • FileOutputStream
  • FilterOutputStream
  • PipedOutputStream
  • PrintStream

The OutputStream class is an abstract class that serves as the base class for all output streams. OutputStream defines an interface for writing streamed bytes of data to an output source. All the other output streams provide support for writing data to different output devices. Data written by an output stream is formatted to be read by an input stream.

File Classes

Files are the most widely used method of data storage in computer systems. Java supports files with two different classes: File and RandomAccessFile. The File class provides an abstraction for files that takes into account system-dependent features. The File class keeps up with information about a file including the location where it is stored and how it can be accessed. The File class has no methods for reading and writing data to and from a file; it is useful only for querying and modifying the attributes of a file. In actuality, you can think of the File class data as representing a filename, and the class methods as representing operating system commands that act on filenames.

The RandomAccessFile class provides a variety of methods for reading and writing data to and from a file. RandomAccessFile contains many different methods for reading and writing different types of information, namely the data type wrappers.

The StreamTokenizer Class

The StreamTokenizer class provides the functionality for converting an input stream of data into a stream of tokens. StreamTokenizer provides a set of methods for defining the lexical syntax of tokens. Stream tokenization can be useful in parsing streams of textual data.

The Networking Package

The Java networking package, also known as java.net, contains classes that allow you to perform a wide range of network communications. The networking package includes specific support for URLs, TCP sockets, IP addresses, and UDP sockets. The Java networking classes make it easy and straightforward to implement client/server Internet solutions in Java. You learn much more about the classes that make up the networking package in Chapter 15, "The Networking Package." The classes included in the networking package follow:

  • The InetAddress class
  • URL classes
  • Socket classes
  • The ContentHandler class

The InetAddress Class

The InetAddress class models an Internet IP address and provides methods for getting information about the address. For example, InetAddress contains methods for retrieving either the text name or raw IP representation of the host represented by the address. InetAddress also contains static methods that allow you to find out about hosts without actually creating an InetAddress object.

URL Classes

The URL classes are used to represent and interact with Uniform Resource Locators (URLs), which are references to information on the Web. Following are the URL classes included in the networking package:

  • URL: Represents a Uniform Resource Locator. URL objects are constant, meaning that their values cannot change once they have been created. In this way, URL objects more closely represent physical URLs, which are also constant.
  • URLConnection: An abstract class that defines the overhead necessary to facilitate a connection through an URL. This class must be subclassed to provide functionality for a specific type of URL connection.
  • URLStreamHandler: An abstract class that defines the mechanism required to open streams based on URLs.
  • URLEncoder: Allows you to convert a string of text information into a format suitable for communication through a URL.

Socket Classes

The socket classes are perhaps the most important classes contained in the networking package. They provide the entire framework for performing network communication through a couple of different approaches. The classes that comprise Java's socket support follow:

  • SocketImpl: An abstract class that defines a base level of functionality required by all sockets. This functionality includes both member variables and a substantial collection of methods. Specific socket implementations are derived from SocketImpl.
  • Socket: Provides client-side streamed socket support. Streamed sockets are sockets that communicate in real time over a live connection with a high degree of reliability.
  • ServerSocket: Used to implement the server side of streamed socket support.
  • DatagramSocket: Contains everything necessary to perform datagram socket communication. A datagram socket is a socket that sends out packets of information with little regard for reliability or timing. Unlike streamed sockets, datagram sockets don't rely on a live connection, meaning that they send and receive data whenever it is convenient. Data being transferred with a datagram socket must be encapsulated by a DatagramPacket object.
  • DatagramPacket: Includes information critical to a packet of information being transferred with a datagram socket.

The ContentHandler Class

The ContentHandler class serves as a framework for handling different Internet data types. For example, you can write a content handler to process and display a proprietary file format. To do this, you would derive a class from ContentHandler and write code to build an object from a stream of data representing the object type.

The Windowing Package

The Java windowing package, also known as java.awt, consists of classes that provide a wide range of graphics and user interface features. This package includes classes representing graphical interface elements such as windows, dialog boxes, menus, buttons, checkboxes, scroll bars, and text fields, as well as general graphics elements such as fonts. You learn much more about the classes in the windowing package in Chapter 16, "The Windowing (AWT) Package." The most important classes included in the windowing package follow:

  • Graphical classes
  • Layout manager classes
  • Font classes
  • Dimension classes
  • The MediaTracker class

Note
The windowing package is also often referred to as the Abstract Windowing Toolkit (AWT), which is where the name java.awt comes from.

Graphical Classes

The graphical classes are all based on serving a particular graphical user input or display need. For this reason, the graphical classes are often indispensable in applet programming. The graphical classes include support for everything from checkboxes and menus to canvases and color representations.

Note
Although I mention the graphical classes here only in terms of Java applets, these classes are equally useful in graphical standalone Java applications. Just keep in mind that standalone applications must create their own frame window to house any graphical elements; applets can simply use the applet window that has been allotted on the containing Web page.

One of the most important GUI classes is the Graphics class, which serves as an all-purpose graphical output class capable of performing all kinds of different drawing functions. The Graphics class is ultimately responsible for all graphical output generated by a Java applet.

The Component class is another very fundamental graphical class and serves as the parent for many of the other graphical classes. It is used this way primarily because Component provides all the overhead necessary for a basic graphical element.

Layout Manager Classes

The layout manager classes provide a framework for controlling the physical layout of GUI elements. For example, you may want to have a row of buttons arranged in a certain way across the top of an applet window. You would use a layout manager to accomplish this. Following are the layout manager classes implemented in the windowing package:

  • BorderLayout: Arranges graphical elements, or components, along a window border, with one element in each position (north, south, east, west, and center).
  • CardLayout: Arranges components on top of each other like a stack of cards; you can flip through the "cards" to display different components.
  • FlowLayout: Arranges components from left to right across a window until no more will fit, in which case they are wrapped around to another line.
  • GridLayout: Arranges equally sized components in a grid with a specific number of rows and columns.
  • GridBagLayout: Similar to the GridLayout class except that the components in GridBagLayout don't have to be the same size, resulting in much more flexibility.

All the layout classes are derived from the LayoutManager interface, which defines the core functionality required of a graphical layout manager.

Font Classes

The font classes consist of the Font class and the FontMetrics class. The Font class represents graphical font objects with attributes such as name, size, and style. Furthermore, Font objects can also be made bold or italic. The FontMetrics class provides a means to find information about the size of a font. For example, you can use a FontMetrics object to ascertain the height of a font, or something more specific such as a font's line spacing (leading).

Dimension Classes

The dimension classes provide a convenient way to represent different graphical dimensions in Java. The following dimension classes are defined in the windowing package:

  • Dimension: Represents the basic rectangular dimensions of a graphical element. The class includes two public member variables for storing the width and height of a rectangular object.
  • Rectangle: Similar to Dimension, except that Rectangle also includes the x and y coordinates of the upper-left corner of a graphical element. In other words, the Rectangle class keeps up with the dimension of a graphical element as well as its position.
  • Point: Similar to the Rectangle class, except that Point keeps up only with an xy position.
  • Polygon: Represents a polygon, which is basically a series of connected points.

The MediaTracker Class

The MediaTracker class provides a means to track when media resources have finished transmitting across a network connection. Currently, the MediaTracker class supports only the tracking of images, but a future release of Java will no doubt add support for sounds and other media types as they gain popularity. The MediaTracker class serves a very useful purpose for applets because it allows them to know when a particular image is ready to be displayed. For some applets, this knowledge is critical.

The Applet Package

The Java applet package, also known as java.applet, contains only one class: Applet. The Applet class contains all the overhead required of a Java applet-which is quite a lot. The Applet class includes methods for accessing applet parameters, loading images, and playing sounds, along with plenty of general behind-the-scenes applet support. One other interesting component of the applet package is the AudioClip interface, which defines the basic functionality required of a Java audio clip.

Summary

This chapter provided a thumbnail sketch of the contents of the six Java standard packages: the language package, the utilities package, the I/O package, the networking package, the windowing package, and the applet package. Although you didn't learn a lot of gritty details, or how to use any of these classes in a real program, you should now have a general sense of what these packages can do. The Java standard packages provide a rich set of classes for overcoming a wide variety of programming obstacles.

A common problem when using programming environments that have a lot of support libraries is knowing what functionality is provided and what functionality you must write yourself. This chapter has given you an idea of what standard classes you can reuse in your own Java programs, and what classes you will have to implement yourself.

Having seen what each package in the Java standard packages contains, you're probably eager to start learning how to use the classes in each package. The next six chapters focus on the packages that make up the Java standard packages.



Ruler image
Contact reference@developer.com with questions or comments.
Copyright 1998 EarthWeb Inc., All rights reserved.
PLEASE READ THE ACCEPTABLE USAGE STATEMENT.
Copyright 1998 Macmillan Computer Publishing. All rights reserved.
Click here for more info

Click here for more info