TOC
BACK
FORWARD
HOME

Java 1.1 Unleashed

- 9 -
Overview of the Standard Packages

by Michael Morrison

IN THIS CHAPTER

  • The Language Package
  • The Utilities Package
  • The I/O Package
  • The Networking Package
  • The Windowing (AWT) Package
  • The Text Package
  • The Security Package
  • The RMI Package
  • The Reflection Package
  • The SQL Package


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 ten standard packages: the language package, the utilities package, the I/O package, the networking package, the windowing package, the text package, the security package, the RMI package, the reflection package, and the SQL 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

NOTE: The Java reflection package, java.lang.reflect, is technically a subpackage of the java.lang package. However, because of its significance to the overall architecture of Java, it is treated in this book as its own package. You learn about it later in this chapter and in Chapter 18, "The Reflection Package."

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

Java's fundamental data types (int, char, float, and so on) 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, you can maintain additional information--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 instead of 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 groups 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 composed entirely 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 6, "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 use the Error class; most use the Exception class to handle runtime errors.

Error handling with exceptions is covered in detail in Chapter 7, "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 Chap- ter 11, "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

  • 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 can 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 12, "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 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 13, "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 the 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 a 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 derive a class from ContentHandler and write code to build an object from a stream of data representing the object type.

The Windowing (AWT) 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, scrollbars, 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 14, "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; an applet can simply use the applet window that has been allotted to it 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 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, if you want a row of buttons arranged in a certain way across the top of an applet window, you use a layout manager to accomplish this. Following are the layout manager classes implemented in the windowing package:

  • BorderLayout: Arranges graphical elements (also called 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 fit; then the components are wrapped around to the next 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; this layout provides the programmer with a great deal of 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 x,y 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 Text Package

The Java text package, also known as java.text, is a key part of Java's support for internationalization. The text package contains classes and interfaces for handling text specific to a particular locale. In other words, the text package provides the underlying mechanism that enables text to be mapped to a specific language and region. The classes and interfaces defined in the text package rely on Unicode 2.0 character encoding and can be used to adapt text, numbers, dates, currency, and user-defined objects to the conventions of any country. You learn a great deal more about the classes and interfaces in the text package in Chapter 15, "The Text Package." Some of the more important classes included in the text package follow:

  • Formatting classes

  • The Collator class

  • The TextBoundary class

Formatting Classes

The text package provides a variety of classes for formatting data according to different cultural conventions. These formatting classes can also parse formatted strings back into their original form. The Format class is an abstract base class that encapsulates locale-sensitive formatting and parsing. Three main subclasses are derived from Format: NumberFormat, DateFormat, and MessageFormat. These derived classes are used to format numbers, dates, and messages, respectively. More specific formatting classes are derived from these classes.

The Collator Class

The Collator class provides support for the locale-sensitive comparison of strings. Using the Collator class, you can compare two strings and factor in any special naming and formatting conventions specific to a particular locale. Java's internationalization facilities require this capability for text sorting and locale-sensitive searching.

The TextBoundary Class

The TextBoundary class determines different boundaries in text such as word, line, and sentence boundaries. These capabilities are critical if Java is to manage different languages; these features enable the programmer to allow intelligent text selection and line wrapping.

The Security Package

The Java security package, also known as java.security, contains the functionality for incorporating cryptographic security into Java-based applications. The cryptography framework in the security package includes support for DSA cryptography and is designed so that new algorithms can be added later without difficulty. For example, although DSA is the only built-in digital signature algorithm in Java version 1.1, the API can easily accommodate other algorithms such as RSA without requiring significant code changes. You learn more about the classes and interfaces in the security package in Chapter 16, "The Security Package." Some of the more important classes included in the security package follow:

  • Digital signature classes

  • The MessageDigest class

  • Key management classes

Digital Signature Classes

The digital signature classes in the security package provide support for generating public/ private key pairs as well as for signing and verifying arbitrary digital data. Digital signatures are used for authentication and integrity assurance of digital data. The Signature class is used to provide the functionality of a digital signature algorithm such as DSA. The Identity class represents identities: real-world objects such as people, companies, or organizations whose identities can be authenticated using their public keys. The Signer class represents an identity that can also digitally sign data.

The MessageDigest Class

The MessageDigest class provides the functionality of a message digest algorithm, such as MD5 or SHA. Message digests are secure, one-way hash functions that take arbitrary-sized data and output a fixed-length hash value. Message digests are useful for producing "digital fingerprints" of data, which are frequently used in digital signatures and other applications that need unique and unforgeable identifiers for digital data.

Key Management Classes

The key management classes included in the security package are used to manage the public and private keys used in the digital signature process. The Key interface is the top-level interface for all keys; it defines the functionality shared by all key objects. The KeyPair class is a simple container for a key pair (that is, a public key and a private key). Finally, the KeyPairGenerator class is used to generate pairs of public and private keys.

The RMI Package

The Java RMI (Remote Method Invocation) package, also known as java.rmi, enables developers to create distributed Java-to-Java applications that rely on remote method invocation. When you use RMI, you can invoke methods of remote Java objects from other Java virtual machines--even on different hosts. The RMI support provided in the RMI package uses object serialization to process parameters being passed between methods. You learn more about the RMI package in Chapter 17, "The RMI Package."

The Reflection Package

The Java reflection package, also known as java.lang.reflect, enables Java code to examine and find detailed information regarding the structure of classes at runtime. More specifically, the reflection services can be used to discover information about the fields, methods, and constructors of classes. The reflection package accommodates applications that require access to either the public members of a target object or the members declared by a given class. You learn more about the reflection package in Chapter 18, "The Reflection Package."


NOTE: JavaBeans relies heavily on the reflection API to give application builder tools the capability of assessing the exported properties of JavaBeans components.

The SQL Package

The Java SQL package, also known as java.sql, contains the overhead required for developers to write database applications capable of performing SQL queries. The SQL package is also sometimes referred to as JDBC (Java Database Connectivity). SQL is the industry standard querying language for accessing and manipulating databases. The SQL package makes it possible for a Java application to interact with virtually any relational database using SQL. The only requirement is that the database have a SQL driver. The capability of accessing multiple databases in a consistent fashion with Java is a huge breakthrough for Java developers. For example, the SQL package makes it possible to publish a Web page containing an applet that uses information obtained from a remote database. Intranet database applications will also benefit a great deal from the SQL package. You learn more about the SQL package in Chapter 19, "The SQL Package." Some of the more important classes and interfaces included in the SQL package follow:

  • The DriverManager class

  • The Connection interface

  • The Statement and ResultSet interfaces

The DriverManager Class

The DriverManager class provides the overhead to manage a set of JDBC drivers, which is necessary to establish a connection with a particular database. When the DriverManager class is initialized, it tries to load the drivers identified in the system settings. It then attempts to select and use one of these drivers when the user tries to establish a database connection.

The Connection Interface

The Connection interface defines the functionality required of a database connection. When a successful database connection is established through the DriverManager class, a Connection-derived object is returned to the user. This object is then used as the context through which SQL statements are constructed and executed and through which subsequent results are returned.

The Statement and ResultSet Interfaces

The Statement interface defines the functionality required of a SQL statement to be executed on a database. SQL statements are always issued through a particular connection context. The results of an executed SQL statement are returned in a ResultSet-derived object. In accordance with standard relational database result handling, the ResultSet interface provides access to a tabular set of result data. The ResultSet interface is used to access this data on a row-by-row basis.

Summary

This chapter provided a thumbnail sketch of the contents of the ten standard Java packages: the language package, the utilities package, the I/O package, the networking package, the windowing package, the text package, the security package, the RMI package, the reflection package, and the SQL 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 standard Java packages provide a rich set of classes for overcoming a wide variety of programming obstacles.

This chapter has given you an idea of which standard classes you can use in your own Java programs, and which classes you will have to implement yourself.

Having seen the types of features these packages provide, you're probably eager to start learning how to use the classes included in each package. The next ten chapters focus on the standard Java packages.

TOCBACKFORWARDHOME


©Copyright, Macmillan Computer Publishing. All rights reserved.