Chapter 36

The Java Class Libraries


CONTENTS

This book has given you a peek into the process of creating applets with Java. However, the key word is "peek" because Java is a huge development system that couldn't be fully covered in a book twice this size. For this reason, now that you have some Java programming experience under your belt, it's time to set off on your own to discover how much more you can do with Java. The first step in that journey is to explore the class libraries that come with Java. You'll discover all sorts of treasures there.

To give you a nudge in the right direction, this final chapter provides a brief overview of Java's most important class libraries. However, you should take it upon yourself to explore the latest documentation available from Sun at their Web site, as well as to peruse Java's source code. The language and its classes are changing constantly, so you have to make an effort to keep up.

The Packages

The Java class libraries are divided into two groups. The first group is the Java packages, which include the libraries for the Java programming language. These packages include the following:

The second group is called the HotJava packages and includes the libraries needed to create applets and to communicate over the Internet. The HotJava packages include the following:

In this chapter, you'll get a brief look at some of these packages and the classes they contain.

The java.lang Package

Although you may not been aware of it, you've been using the lang package since the beginning of this book. That's because this is the one package that Java automatically imports into every program. Without the lang package, you wouldn't be able to write Java programs, because this package contains the libraries that make Java what it is. Table 36.1 is a list of the commonly used classes included in the lang package.

Table 36.1  Commonly Used Classes in the java.lang Package.

ClassDescription
BooleanRepresents the boolean data type.
CharacterRepresents the char data type.
DoubleRepresents the double data type.
FloatRepresents the float data type.
IntegerRepresents the int data type.
LongRepresents the long data type.
MathContains methods that implement mathematical functions.
NumberThe superclass for all number-related classes, such as Float and Integer.
ObjectThe root of the entire class library. All Java classes can trace their ancestry back to Object.
StringRepresents text strings.
StringBufferRepresents a string buffer that can grow dynamically.
SystemContains methods for performing system-level function calls.
ThreadThe superclass from which thread objects are derived.

Of these classes, the ones that are most useful to you at this time are the data-type wrappers-Boolean, Character, Double, Float, Integer, Long-, as well as String, Math, System, and Thread. The following sections provide general descriptions and usage tips for these classes-except for Thread, which you learned about in Chapter 31, "Threads."

NOTE
The java.lang package also includes the Runnable interface, which is used to convert classes into threads. For more information on this topic, see Chapter 31, "Threads."

Data-Type Wrappers

The data-type wrapper classes enable you to perform various operations on values in your programs. For example, in previous programs in this book, you've used the Integer.parseInt() method to convert strings containing digits to integer values, like this:


int value = Integer.parseInt(str);

Often, you can call static methods of the class, like parseInt(), to perform an operation on a value. But, you can also create objects of the class and operate directly on that object's value. To give you some idea of what you can do with the wrapper classes, table 36.2 lists the methods of the Integer class.

Table 36.2  Methods of the Integer Class.

MethodDescription
Integer(int)One of the class's constructors.
Integer(String)One of the class's constructors.
doubleValue() Returns the integer as a double value.
equals(Object)Compares the integer to another object.
floatValue()Returns the integer as a float value.
getInteger()Gets a property of an integer.
hashCode()Returns a hashcode for the integer.
intValue()Returns the integer as an int value.
longValue()Returns the integer as a long value.
parseInt(String, int)Converts a string to an int value.
parseInt(String)Converts a string to an int value.
toString(int, int)Converts an integer to a string.
toString(int)Converts an integer to a string.
toString()Converts an integer to a string.
valueOf(String, int)Creates an Integer object from a string.
valueOf(String)Creates an Integer object from a string.

Example: Using the Data-Type Wrappers

Suppose that you need an integer data field in a class, but you want to be able to use all of the Integer class's methods in order to manipulate that value. First, you declare an object of the Integer class and then call the class's constructor. Then, you can access the class's methods, as shown in Listing 36.1. Figure 36.1 shows the applet running under Appletviewer.

Figure 36.1 : This is IntApplet running under Appletviewer.


Listing 36.1  IntApplet.java: Using the Integer Class.

import java.awt.*;

import java.applet.*;



public class IntApplet extends Applet

{

    public void paint(Graphics g)

    {

        Integer value = new Integer(125);



        long longValue = value.longValue();

        float floatValue = value.floatValue();



        String str = value.toString() + "    " +

            String.valueOf(longValue) + "    " +

            String.valueOf(floatValue);

        g.drawString(str, 50, 75);

    }

}


Tell Java that the applet uses the classes in the awt package.
Tell Java that the applet uses the classes in the applet package.
Derive the IntApplet class from Java's Applet.
Override the paint() method.
Create an Integer object with a value of 125.
Convert the integer to long and float values.
Create a display string and display it.

The System Class

The System class enables you to make system-level function calls to do things like perform simple I/O, get the current time, handle directories, copy arrays, get environment variables, get information about memory, and so on. You would use the class's I/O methods, for example, in a standalone applet in order to display text on the screen. Table 36.3 lists the more useful of the System class's methods and their descriptions.

NOTE
In addition to its many methods, the System class also defines standard input and output streams that you can use in your programs. For example, when you call the println() method, you're using an output stream.


Table 36.3  The Most Useful Methods of the System Class.

MethodDescription
arraycopy()Copies an array.
CurrentTimeMillis()Gets the current time in milliseconds.
ex0it(int)Ends the program.
GetProperties()Returns the current system properties.
GetProperty()Returns a specific property.
load()Loads a dynamic library.
setProperties()Set the system properties.

Example: Getting System Properties

Frequently, it's handy to know something about the system on which your application is running. That's why the System class makes it easy for you to find this information. Listing 36.2, for example, is a stand-alone application that displays Java's version, Java's class path, the OS name, and the OS version. Figure 36.2 shows the output from the program.

Figure 36.2 : The SystemApp application displays system properties


Listing 36.2  SystemApp.java: An Application That Displays SystemInformation.

public class SystemApp

{

    public static void main(String args[])

    {

        System.out.println("");

        System.out.println("------------------------------");



        String str = "Java Version: " +

            System.getProperty("java.version");

        System.out.println(str);



        str = "Java Class Path: " +

            System.getProperty("java.class.path");

        System.out.println(str);



        str = "OS Name: " +

            System.getProperty("os.name");

        System.out.println(str);



        str = "OS Version: " +

            System.getProperty("os.version");

        System.out.println(str);



        System.out.println("------------------------------");

    }

}


Declare the SystemApp.
Define the main() method.
Display blank and dashed lines.
Get and display the Java version number.
Get and display Java's class path setting.
Get and display the OS name.
Get and display the OS version number.
Display an ending dashed line.

NOTE
The System class's getProperty() method accepts a string identifier for the property you want. The strings you can use are file.separator, java.class.path, java.class.version, java.home, java.vendor, java.vendor.url, java.version, line.separator, os.arch, os.name, os.version, path.separator, user.dir, user.home, and user.name.

The Math Class

If you need to do a lot of mathematical work in your applets and applications, you'll be glad to have the Math class at your disposal. Using the Math class, you can perform many types of calculations just by calling the appropriate methods. Table 36.4 lists the Math class's methods and their descriptions:

Table 36.4  Methods of the Math Class.

MethodDescription
abs()Returns the absolute value of a given number.
Acos()Returns the arc cosine of a value.
asin()Returns the arc sine of a value.
atan()Returns the arc tangent of a value.
atan2()Converts rectangular coordinates to polar coordinates.
ceil()Returns the smallest whole number greater than or equal to the given value.
cos()Returns the cosine of an angle.
floor()Returns the largest whole number less than or equal to the given value.
IEEEremainder()Returns the remainder of a floating-point division.
log()Returns the natural log of a value.
max()Returns the greater of two values.
min()Returns the smaller of two values.
random()Returns a random number between 0.0 and 1.0.
round()Rounds a floating-point or double number.
sin()Returns the sine of an angle.
sqrt()Returns the square root of a value.
tan()Returns the tangent of an angle.

To call any of the math methods, reference them through the Math class, like this:


Math.Method()

For example, to get the square root of 10, you use this line:


double result = Math.sqrt(10);

The String Class

You're no stranger to the String class. You've used it in a number of programs in order to store and manipulate text strings. However, because this class is so useful to a programmer, you'll take a closer look at it here. As you'll see, the String class is powerful, enabling you to manipulate strings in more ways than you may have realized. Table 36.5 shows the most commonly used methods of the String class.

Table 36.5  Methods of the String Class.

MethodDescription
charAt()Returns the character at the given string index.
compareTo()Compares a string to another string.
concat()Joins two strings.
copyValueOf()Copies a character array to a string.
endsWith()Checks a string for the given suffix.
equals()Compares a string to another object.
equalsIgnoreCase()Compares a string to another object with no regard for upper- or lowercase.
getBytes()Copies selected characters from a string to a byte array.
getChars()Copies selected characters from a string to a character array.
hashCode()Returns a string's hashcode.
indexOf()Finds the index of the first occurrence of a given character or substring in a string.
lastIndexOf()Finds the index of the last occurrence of a given character or substring in a string.
length()Returns the length of a string.
regionMatches()Compares a portion of a string to a portion of another string.
replace()Replaces all occurrences of a given character with a new character.
startsWith()Checks a string for the given prefix.
substring()Returns a substring of a string.
toCharArray()Converts a string to a character array.
toLowerCase()Converts all characters in the string to lowercase.
toUpperCase()Converts all characters in the string to uppercase.
trim()Removes whitespace characters from the beginning and end of a string.
valueOf()Returns a string representation of an object.

Example: Using the String Class

Listing 36.3 is an applet that shows you how a few of the String methods you haven't tried yet work. When you run the applet with Appletviewer, you see the window shown in Figure 36.3. The applet takes whatever text strings you type in the two text boxes, and compares them for equality without considering upper- or lowercase. It then concatenates the strings and displays the new concatenated string along with its length.

Figure 36.3 : This is StringApplet running under Appletviewer.


Listing 36.3  StringApplet.java: An Applet That Manipulates Strings.

import java.awt.*;

import java.applet.*;



public class StringApplet extends Applet

{

    TextField textField1;

    TextField textField2;



    public void init()

    {

        textField1 = new TextField(20);

        textField2 = new TextField(20);



        textField1.setText("STRING");

        textField2.setText("String");



        add(textField1);

        add(textField2);

    }



    public void paint(Graphics g)

    {

        String str1 = textField1.getText();

        String str2 = textField2.getText();

        

        boolean equal = str1.equalsIgnoreCase(str2);

        if (equal)

            g.drawString("The strings are equal.", 70, 100);

        else

            g.drawString("The strings are not equal.", 70, 100);



        String newStr = str1.concat(str2);



        g.drawString("JOINED STRINGS:", 70, 130);

        g.drawString(newStr, 80, 150);



        g.drawString("STRING LENGTH:", 70, 180);

        int length = newStr.length();

        String s = String.valueOf(length);

        g.drawString(s, 80, 200);

    }



    public boolean action(Event evt, Object arg)

    {

        repaint();

        return true;

    }

}


Tell Java that the application uses the awt package.
Tell Java that the application uses the applet package.
Derive the StringApp class from Applet.
Declare the class's data fields.
Override the init() method.
Create two TextField controls.
Set the controls' contents.
Add the controls to the applet's layout.
Override the paint() method.
Get the contents of the two text boxes.
Compare the two strings.
Display the appropriate message about the strings' equality.
Concatenate the two strings.
Display the joined strings.
Get and display the new string's length.
Override the action() method.
Force Java to repaint the applet.
Tell Java that the action was handled okay.

The io Package

Although Java applets are extremely limited in their I/O abilities, Java applications are free to create, load, and save files just like any other application. All of Java's file-handling abilities are housed in the io package. This package includes many classes that enable you to handle files and other types of input and output streams. Table 33.6 lists the more commonly used of these classes and their descriptions:

Table 36.6  Commonly Used Classes in the io Package.

ClassDescription
BufferedInputStreamAn input stream that buffers data.
BufferedOutputStreamAn output stream that buffers data.
DataInputStreamAn input stream for reading primitive Java data types.
DataOutputStreamAn output stream for writing primitive Java data types.
FileRepresents a file.
FileInputStreamAn input stream associated with a file.
FileOutputStreamAn output stream associated with a file.
InputStreamThe superclass from which input classes are derived.
OutputStreamThe superclass from which output classes are derived.
PrintStreamAn output stream that can be used for printing.
PushbackInputStreamAn input stream that enables a program to return read values back into the stream.
RandomAccessFileRepresents random-access files.
StringBufferInputStreamAn input stream whose data source is a string.

Example: Reading a File

There are many ways to read files using Java's I/O classes. The most basic, however, is to read a file byte-by-byte. Suppose, for example, you wanted to display on the screen the source code in the file test.java. Listing 33.4 shows such an application. Although this example is very basic, it demonstrates how to use one of Java's I/O classes, FileInputStream. Creating a file using an output stream isn't much different; you just need to create an output stream object and write, rather than read, data. Figure 36.4 shows FileApp's output.

Figure 36.4 : The FileApp application reads and displays a text file.


Listing 36.4  FileApp.java: An Application That Reads a File.

import java.io.*;



public class FileApp

{

    public static void main(String args[])

    {

        System.out.println("");

        System.out.println("------------------------------");

        System.out.println("");



        try

        {

            FileInputStream inputStream =

                new FileInputStream("test.java");



            String str = "";

            int b = 0;



            while(b != -1)

            {

                b = inputStream.read();

                str += (char)b;

            }



            inputStream.close();

            System.out.println(str);

        }

        catch (FileNotFoundException e)

        {

            System.out.println("File not found!");

        }

        catch (IOException e)

        {

            System.out.println("I/O Error!");

        }



        System.out.println("------------------------------");

    }

}


Tell Java that the application uses the io package.
Declare the FileApp class
Define the main() method.
Display blank and dashed lines.
Create a FileInputStream object.
Initialize the input variable and buffer.
Loop until the last byte in the file is read.
Read a byte from the input stream.
Add the byte as a character to the string buffer.
Close the input stream.
Display the data read from the stream.
Catch any exceptions and print error messages.
Display the bottom dashed line.

The awt Package

You're already familiar with the awt package, which contains the classes you need to create and run applets in windowed environments. The awt package contain the Graphics class that you used to create displays for your applets, and all the control classes you used throughout the book to handle user interactions with applets. The awt package even has the classes for handling events and creating windows with menus. You've already explored much of the awt library, but for your reference table 36.7 lists the package's classes and their descriptions. Feel free to explore any of the classes with which you're not familiar.

Table 36.7  Classes of the AWT Package.

ClassDescription
BorderLayoutOne of Java's layout managers.
ButtonRepresents button controls.
CanvasRepresents a surface on which a program can draw.
CardLayoutOne of Java's layout managers.
CheckboxRepresents a checkbox control.
CheckboxGroupRepresents a group of check boxes used as "radio buttons."
CheckboxMenuItemA menu entry that can be checked.
ChoiceA type of pop-up menu.
ColorRepresents color values in Java programs.
ComponentThe superclass from which all Java components are derived.
ContainerRepresents an object that can hold Java components.
DialogA dialog-box type of window.
DimensionRepresents the width and height of an object.
EventRepresents various system and user events.
FileDialogA dialog box for selecting files.
FlowLayoutOne of Java's layout managers.
FontRepresents a character style.
FontMetricsThe attributes of a font.
FrameA main window that can contain a menu and other window controls.
GraphicsContains methods for drawing various shapes and controllong graphical attributes like color, fonts, clipping rectangles, etc.
GridBagConstraintsUsed in conjunction with GridBagLayout managers.
GridBagLayoutOne of Java's layout managers.
GridLayoutOne of Java's layout managers.
ImageRepresents graphical images, usually in GIF format.
InsetsUsed as spacers for components in a container.
LabelRepresents text labels.
LayoutManagerThe superclass from which all layout managers are derived.
ListRepresents a list box control.
MediaTrackerA class for organizing multiple images.
MenuRepresents menus in a menu bar.
MenuBarRepresents menu bars in frame windows.
MenuComponentThe superclass from which all menu components are derived.
MenuContainerThe superclass from which all menu containers are derived.
MenuItemRepresents an item in a pop-up menu.
PanelA simple container class.
PointRepresents an X,Y coordinate.
PolygonA list of coordinates for outlining a polygon.
RectangleAn object the represents the X,Y coordinate and width and height of a rectangle.
ScrollbarA scrollbar control.
TextAreaA simple text edit box.
TextComponentA component for editing text.
TextFieldA one-line text component.
WindowA general window class.

Summary

The Java Developers Kit is comprised of dozens of classes that do everything from define the basic language to enable programmers to create applets and applications for windowed environments. These classes are organized into six main packages: lang, util, io, awt, applet, and net. For the novice and intermediate Java programmer, the lang and awt packages, which define the Java language and supply classes for operating under a windowed environment, respectively, are by far the most important.

Although the io class enables the programmer to create various types of input and output streams, due to security considerations, Java applets are restricted on the types of I/O they can perform. For that reason, you'll probably use I/O methods mostly in Java standalone applications, if you are even interested in building applications rather than applets. Applets, of course, rely on the few classes that make up the applet package for the functionality that sets them apart from regular applications.

Finally, the util and net packages contain little of interest to any except advanced Java programmers. The util package contains classes that support the other Java classes by providing helper classes such as Properties, Stack, and Vector. Finally, the net package features the classes that enable programmers to include communication protocols for use with Internet connections in their applets and applications.

Review Questions

  1. What are the six main packages of the Java classes?
  2. Which package contains classes for operating in a windowed environment?
  3. When would you use the Math class?
  4. What's the advantage of using the String class to handle text?
  5. How do you join two strings?
  6. Do you need to instantiate an object of the Math class in order to call its methods?
  7. What are data-type wrapper classes and how are they used?
  8. How can you get information about the system on which your applet or application is currently running?
  9. How can you write file-handling code for a standalone application?

Review Exercises

  1. Write an applet that accepts a value from the user, and then displays the value's square root, logarithm, and absolute value.
  2. Write an application called SystemApp2 that displays all system properties. Figure 36.5 shows what the program's output looks like. (You canfind the solution for this exercise in the CHAP36 folder of this book's CD-ROM.)

Figure 36.5 : The SystemApp2 application should display all of the system properties.