ex.htm">


Chapter 14 -- Java API Reference

Chapter 14

Java API Reference


CONTENTS


This reference presents and explains the entire Java API. The API, which stands for Application Programming Interfaces, is a set of classes and interfaces that outline a set of platform-independent behaviors that establish the foundation of all Java applets and applications. Although any program depends on the strategies of the programmer, these classes and interfaces are the tools that all programmers use in creating Java applications.

java.applet

The java.applet class provides you with only one class and three interfaces, but it is one of the most used packages because it lays the foundation for all applets. The Applet class is most important because it is required when you create an applet. Also useful is the AppletContext interface, which is employed to interact with the browser.

Classes

Applet Extends java.awt.Panel. This class is the heart of every Java applet. Derived from the java.awt.Pannel class, the Applet class possesses all the methods found in the java.awt.Container class that enable you to create a powerful and appealing user interface. Every applet that you create must extend the Applet class.

As stated above, in order to create a Java applet, you must create a class that extends the java.applet.Applet class. However, to run the applet, you must embed it in an HTML page. This is done with the <APPLET> tag, which must specify the name, height, and width of the applet. You may also specify additional parameters: information that the applet can obtain. The HTML page shown in specifies two parameters: NAME and KEY (see Listing 14.1).


Listing 14.1  Sample HTML Page for an Applet
<HEAD>
<TITLE>Applet Example</TITLE>
<BODY>
This text is above the applet.<P>

<applet code="examp.class" width=500 height=100 >
<param name=NAME value="Mike">
<param name=KEY value = "j">
</applet>
<P>This text is below the applet.<P>
</BODY>

This document will load the examp class that will be stored in a file named examp.class. Listing 14.2 is the complete source code for that class.


Listing 14.2  Sample Applet
import java.applet.Applet;
import java.awt.*;

public class ExampleApplet extends Applet
{
   String userName;
   char favoriteKey;
   int appletWidth, appletHeight, fontHeight;
   Font fontToUse;
   FontMetrics fm;

   /* This class will be called before the applet is  
      started.  As a result, it can be used to perform  
      preparatory operations. */

   public void init() {
     userName = new String();// creates a new, empty string
     appletWidth = this.size().width - 2; // uses    
                                        //Component.size ()
     appletHeight = this.size().height - 2;   
     fontToUse = new Font("TimesRoman", Font.PLAIN, 20);   
                              // creates a new Font object
     fm = getFontMetrics(fontToUse);     // obtains the
                                   //FontMetrics for the font
     fontHeight = fm.getMaxAscent(); /* maximum size that
                           one of the font's characters may
                                       extend upwards     */
     getInfo();     // gets info from HTML tag   }


   /* This method uses the getParameter() method to obtain  
        the information passed to the applet in the applet
       tag.  This method assumes that there will be two   
       tags, titled "NAME" and "KEY" in the HTML page. */

   void getInfo() {
     userName = getParameter("NAME");
     favoriteKey = getParameter("KEY").charAt(0);  
      // we want the first character in the returned string
      }

      /* This method is automatically called whenever the
         mouse is depressed within the applet */

   public boolean mouseDown(Event evt, int x, int y) {
     showStatus("Mouse Click at ("+x+","+y+")" );
     return true;
   }

     /* This method is automatically called whenever a key is  
        depressed within the applet */
   public boolean keyDown(Event evt, int key) {
     if (key == favoriteKey) {
       showStatus("You pressed " + favoriteKey +
                                    ", my favorite key!");
       return true;
     }
     return false;
   }

   /* This method is automatically called whenever the
      applet needs to be drawn */

   public void paint(Graphics g) {
     g.setFont(fontToUse);
     g.drawRect(0,0,appletWidth, appletHeight);
     g.drawString("Hello " + userName +
       ".  Welcome to the world of Java!",10,fontHeight + 3);
   }
}

The classes used in this example, Font, FontMetrics, and Graphics, are explained in the AWT package section. However, you should note that of the five methods in this applet, only one, getInfo(), is explicitly called by the applet. The others will be called by either the browser or by one of the classes on which the java.applet.Applet class is based. Methods, such as init(), are called by the browser itself at particular times. Methods, including keyDown() and mouseDown(), are called to handle specific user events within the applet. More such methods can be found in the java.awt.Component class.

Methods

Interfaces

AppletContext. The AppletContext interface provides you with a means to interact with the browser. Every applet can obtain its AppletContext through the getAppletContext( ) method. Although the inner workings of the AppletContext depends on the browser, you are guaranteed that it will be capable of performing the following tasks.

See Listing 14.18, "Runnable Example-HTML," p. 550
Methods

Options for target are shown in the following table:

ValueDocument Display
"_self" Current Frame.
"_parent" Parent Frame.
"_top" Top-most Frame.
"_blank" In a new and unnamed browser window.
"aNameofYourChoice" Creates a new browser window with the specified name. You may later display other documents in this window by using the same name as the target.

Displays a string at the bottom of the browser.

AppletStub. The AppletStub interface is primarily used when creating an applet viewer. However, it is used by the Applet class to retrieve information and interact with the browser. Because all of this interaction is already handled by the Applet class, there is generally no need for you to use the AppletStub class.

Methods

AudioClip. The AudioClip interface is a high-level representation of the behavior of an audio clip. While interface objects cannot be created, objects that extend the AudioClip interface may be handled through this interface. Consequently, while the getAudioClip() in the Applet class returns an object we know little about, knowing that it implements the AudioClip interface enables us to make use of the loop(), play(), and stop() methods.

Methods

java.awt

The Java Abstract Window Toolkit (AWT) consists of resources to enable you to create rich, attractive, and useful interfaces in your applets. Possessing managing tools, such as LayoutManager and Container, the AWT also has several concrete interactive tools, such as Button and TextField.

Classes

BorderLayout Implements LayoutManager. A BorderLayout is a class that may be used for designing and managing components within your user interface. A BorderLayout is a landscape onto which you may place up to five components. Components may be anchored by specifying either "North," "South," "East," "West," or "Center" when adding the component to the layout.

Methods

Options for location are as follows:

"North"
"South"
"West"
"East"
"Center"

Button Extends Component. The Button class creates a standard button for use in your interfaces. A Button is a standard component that may be added to any of the layout manager classes. The label string for each button serves not only to identify the button to the user, but to the programmer as well. Whenever a button is depressed, an ACTION_EVENT will be posted to the container in which the button resides. To distinguish between the various buttons on the screen, the Event will contain an arg string containing the label of the button that was depressed.

See Listing 14.6, "GridbagLayout Example," p. 446
Methods

Canvas Extends Component. The Canvas class provides you with a simple background on which you can build. The Canvas class establishes a peer and paints a simple gray background. However, if you choose to extend the Canvas class, you are able to create your own custom components-something very useful.

Methods

CardLayout Implements LayoutManager. A CardLayout enables you to scroll through a series of components. Generally, the "cards" are containers-each with a specific theme. Each card is referred to by a title and is furthermore sequentially indexed. Therefore, you are to scroll through the cards either in order or by selecting a specific card by name.

The code in Listing 14.3 was used to create the applet. As you can see, the applet uses a Choice component to enable the user to scroll through the various cards.


Listing 14.3  CardLayout Example Source Code
import java.awt.*;
import java.applet.Applet;

public class CardLayoutExample extends Applet {
  
  
 Frame sidecard;
   private static String LINKS = "Links from Here";
   private static String ORDERFORM = "Order Form";

   public CardLayoutExample() {
    Choice selector = new Choice();  // creates a selector
                            // on the original page
    selector.addItem(LINKS);
    selector.addItem(ORDERFORM);
    add(selector);

    sidecard = new Frame("Multi-Purpose Window");  
                     // creates the side frame
    sidecard.setLayout(new CardLayout());  

    Panel p = new Panel();  // create the individual panels
    p.add(new Button("Our Homepage"));
    p.add(new Button("Other Products") );
    sidecard.add(LINKS, p);

    p = new Panel();
    p.setLayout( new FlowLayout() );
    p.add(new TextField("Name", 20));
    p.add(new TextField("Address", 50) );
    p.add(new TextField("Phone", 20) );
    p.add(new Button("Order") );
    sidecard.add(ORDERFORM, p);

    sidecard.show();      // shows the side frame
   }

   public boolean action(Event evt, Object arg) {
    CardLayout display;

    if (evt.target instanceof Choice) { /* if the event
                             occurred in a Choice */
      display = (CardLayout)sidecard.getLayout();  
                       // obtains control of the frame
      display.show(sidecard,arg.toString());      
         // displays the panel with the corresponding title
      return true;
    }
    return false;
   }

   public synchronized boolean handleEvent(Event evt) {
    if (evt.id == Event.WINDOW_DESTROY) {
      this.hide();
          return true;
    }
    return super.handleEvent(evt);
}
}

Methods

Checkbox Extends Component. A checkbox provides you with an easy way of obtaining input from the user. It resembles a standard checkbox: a text label and a box on the client's machine.

See "CheckboxGroup," p. 416
See "CheckboxMenuItem Extends MenuItem," p. 416
 See Listing 14.6, "GridbagLayout Example," p. 446
Methods

CheckboxGroup. By employing a CheckboxGroup, you are able to create a radio button group: a set of Checkboxes, only one of which can be selected at a time. This is useful for exclusive choices (the user can only choose one of the options), such as "How do you want to pay for your purchase?"

To employ a CheckboxGroup, first create and layout your checkboxes as you normally would. Then assign them to the CheckboxGroup by using the setCheckboxGroup( ) method.

See "Checkbox Extends Component," p. 415
Methods

CheckboxMenuItem Extends MenuItem. A CheckboxMenuItem is a MenuItem whose status may be toggled. Placed within a Menu column, a CheckboxMenuItem will display a check mark when selected.

See "Checkbox Extends Component," p. 415
Methods

Choice Extends Component. The Choice component creates a standard pop-up menu from which the user can select one item.

See Listing 14.6, "GridbagLayout Example," p. 446
Methods

Final Color. The Color class provides you with the various colors that you can employ in your programs as well as the capability to create and customize your own colors.

See "Abstract Graphics," p. 438
Fields
Methods

Abstract Component Implements ImageObserver. The Component class is the basis for the various components in the AWT that may be employed, such as Button and Scrollbar. While the specific components posses methods pertinent to their function, the Component class provides them with a myriad of methods designed to facilitate a base functionality-such as event handling.

You will also note that the Component class relies heavily on the java.awt.peer classes for much of its implementation because the system commands to create a component on UNIX machines are different from those to create the component on Windows-based machines. Instead of directly interacting with these methods, the peers serve as intermediaries, translating your Java-based code into platform-dependent commands.

Methods
This method returns true if the event has been handled successfully. If you override this method but still want to employ the component's default method handling abilities, call super.handleEvent(evt).
This method will be called by the system when more information becomes available about the Image. Therefore, this method should only be used if you want to add some functionality to the method.

Abstract Container Extends Component. The Container class is a basic class that may hold other Components. The Container class serves as the basis for the other container-type classes such as Frame, Panel, and FileDialog. Note that you cannot create a Container explicitly, but rather must either use one of the derived classes or create your own Container class.

Methods
Sets the layout manager for the component.

Dialog Extends Window. A Dialog is a type of Window that is used to accept user input. A Dialog must exist in a Frame object. A modal Dialog is a type of Dialog that will capture all the input from the user.

Methods

Dimension. The Dimension class provides you with a simple way of handling the dimensions of graphical tools. Most often, the Dimension class is used to enable a single method to return two values: width and height.

Fields
Methods

Event. The Event class, used as a means of responding to user interactions, delivers a lot of information about a user event in a single object. Through its constants and instance variables, each Event object is capable of providing you with many specific details regarding each event.

All final fields serve as constants against which you may compare information contained in the Event objects that you receive. In general, the fields fall into two categories: those that represent certain keys (e.g., F1 and HOME) and those that represent certain events (e.g., GOT_FOCUS and KEY_PRESS).

See Listing 14.3, "CardLayout Example Source Code," p. 413
See Listing 14.7, "Menu Example," p. 458
Fields
Methods

FileDialog Extends Dialog. A FileDialog creates a window to provide the user with a selection of files. The FileDialog itself will resemble the appearance of file dialog boxes on the client's machine.

The FileDialog was created with the code in Listing 14.4. Although the code is obviously too simple to serve as a complete applet, it nevertheless demonstrates the technique for creating a FileDialog.


Listing 14.4  FileDialog Example
import java.applet.Applet;
import java.awt.*;

public class FDialogExample extends Applet {

   public void init() {
    
 Frame f;
     f = new Frame();

     Dialog d;
     d = new FileDialog(f,"FileDialogExample");

     f.show();
     d.show();
   }
}

Fields
Methods

FlowLayout Implements LayoutManager. The FlowLayout class is a relatively simple layout manager. It places components in rows and continues on the next line when the current line becomes full.

Fields
Methods
Returns the minimum size necessary for the components in the specified container. This value is based on the minimum sizes of the components added to the amount of spacing for the container.

Font. The Font class serves as an intermediary between your code and the client's machine, providing you with specific styles for your text. Although it will not affect the appearance of the output to the output streams (e.g., System.out), the current font will determine the appearance of any text created in displaying a Component-particularly an Applet.

See Listing 14.2, "Sample Applet," p. 406

Note
To actually change the display font, you must first create a new Font and then set the current font. This is done using either the java.awt.Component.setFont( ) or java.awt.Graphics.setFont( ) method.

Fields
Methods

FontMetrics. The FontMetrics class provides you with information regarding a given font. This class is very useful for such tasks as animation of text because it is often necessary to know exactly where each character will be. By creating a FontMetrics for the font and then using the accessor methods to obtain information, you can determine the exact size of your characters and strings.

See "Font," p. 433

Note
To employ a FontMetrics in your program, declare an instance of a FontMetrics and then use the java.awt.getFontMetrics( ) method to provide the FontMetrics with information.

Field
Methods

Frame Extends Window Implements MenuContainer. A Frame is a Window that has added capabilities. In terms of appearance, a Frame possesses a border and a title. In terms of functionality, you can add a menu to a Frame and specify the image that appears when the Frame is minimized.

See "MenuBar Extends MenuComponent Implements MenuContainer," p. 457
See "Window Extends Container," p. 471

Tip
When using a Frame, remember to invoke the show( ) method. Otherwise, your frame will be invisible!

Fields
Methods

Abstract Graphics. The Graphics class provides you with a wide variety of graphical tools, ranging from the generic drawing tools, such as drawLine(), to editing tools, such as clipRect().

If you are creating an applet, the creation of a graphics object will be done for you by the browser environment. Therefore, you can use the Graphics objects passed as parameters to the paint() and update() methods without worrying about how drawLine() actually does its chore.

See Listing 14.2, "Sample Applet," p. 406

The Graphics class provides you with a wide variety of graphical tools to create attractive interfaces. Listing 14.5 gives a brief sample of these tools and demonstrates the form for creating graphics.


Listing 14.5  Graphics Example
import java.applet.Applet;
import java.awt.*;


public class GraphicsExample extends Applet
{

   public void paint(Graphics g) {

   g.setFont( new Font("TimesRoman", Font.PLAIN, 14) );  
             // sets the font for the drawString() statement
   g.drawString("This is a sample of what the Graphics class can do!",30,20);

     g.setColor(Color.red);

    
 g.fill3DRect(10,60,20,10,true);         
     g.fill3DRect(50,60,20,10,false);  
     int xpoints[ ] = {120,130, 150, 140, 180 };  
                          // x-coordinates for polygon
     int ypoints[ ] = {60,50, 90, 170, 60};            
     g.fillPolygon( xpoints, ypoints, 5);

     g.fillRoundRect(200,80,100,100,10,5);
     g.setColor(Color.blue);
     g.fillArc(10,150,100,100,0,360);

     g.setColor(Color.white);
     g.fillArc(35,175,50,50,0,270);

     g.setColor(Color.magenta);
     g.drawLine(300,180,350,180);
     g.drawLine(300,180,300,220);
     g.drawLine(300,220,350,180);
   }
}

Methods

Tip
Be careful when setting the clipping area. Once this is done, it cannot be undone! Therefore, it is often wise to create a temporary Graphics object with the create( ) method. You can set the clipping area and paint with this new object. When you want to display on the full screen again, you can revert to the original Graphics object.

Note
The java.awtComponent class implements the ImageObserver interface. Therefore, in most applets, you may use the this keyword as the ImageObserver.

GridBagConstraints Implements java.lang.Cloneable. The GridBagConstraint class enables you to customize the layout attributes of each component in a GridBagLayout. By first creating a GridBagConstraint and setting its fields, you are able specify the shape, size, and behavior of the component once added to the layout.

See "GridBagLayout Implements LayoutManager," p. 445
Fields
Methods

GridBagLayout Implements LayoutManager. The GridBagLayout is the most versatile and commonly used layout manager for components. A GridBagLayout enables you to place any number of components in virtually any layout that you can imagine.

To control the layout of components in a GridBagLayout, you must employ the GridBagConstraints class. After setting the values of the GridBagConstraints class, you can add a component to the layout using the constraints. This flexibility enables you to specify a great deal of information about how the components will be laid out.

See "GridBagConstraints Implements java.lang.Cloneable," p. 443

The constraints for a GridBagLayout are set through the fields in the GridBagLayout, as described in the following table:

FieldsPurpose
anchor Can be used to place the component in a particular region of the container (for example, SOUTHWEST).
fill Determines how the component will act if the container provides it with room to grow. Valid values are NONE, HORIZONTAL, VERTICAL, and BOTH.
insets Specifies the amount of space between components on the side of the container and the container edge.
ipadx, ipady Specifies the amount of space between components.
gridx, gridy Defines the upper lefthand corner of the component.
gridwidth, gridheight Defines the size of the component.
weightx, weighty Defines the relative importance of the components; to be used only when the container is resized.


Listing 14.6  GridbagLayout Example
import java.applet.Applet;
import java.awt.*;

public class GridBagExample extends Applet
{
   GridBagLayout gridbag;
   GridBagConstraints c;
   
   public void init() {
     Button button;
     Checkbox checkbox;
     TextArea textarea;
     TextField textfield;
     Choice choice;

     gridbag = new GridBagLayout();
     c = new GridBagConstraints();
     setLayout(gridbag);

     c.ipadx=2;c.ipady=2;  // padding between components
     c.insets=new Insets(5,5,5,5);    /* padding
     between the components and the edge of the container*/

     button = new Button("Button One");
     gridbag.setConstraints(button,c);
     add(button);

     c.gridwidth = GridBagConstraints.REMAINDER;  
     /* Button will occupy the remainder of this row.  
        Forces the next component onto the next row.   */

     button = new Button("Button Two");
     gridbag.setConstraints(button,c);
     add(button);

     c.gridwidth = 1;    
    // back to defaults - components continue on same row


     checkbox = new Checkbox("Checkbox");
     gridbag.setConstraints(checkbox,c);
     add(checkbox);

     c.gridwidth = GridBagConstraints.REMAINDER;
     textfield = new TextField("This is a TextField");
     gridbag.setConstraints(textfield,c);
     add(textfield);

     c.gridwidth = 1;
     c.gridheight = GridBagConstraints.REMAINDER;  
     choice = new Choice();
     choice.addItem("Selection One");
     choice.addItem("Selection Two");
     gridbag.setConstraints(choice,c);
     add(choice);

     textarea = new TextArea("This is a Text Area",10,3);
     gridbag.setConstraints(textarea,c);
     add(textarea);         
   }
}

Fields
The class consists only of the following fields and one constructor method.
Unless you are creating a new class in the java.awt package that extends the GridbagLayout class, you will not need to use this class-nor will you be able to.
  int width, height;   // number of cells in each direction
  int startx, starty;  // start of layout  
  int minWidth[ ];      // largest minWidth for each column  
  int minHeight[ ];     // largest minHeight for each row  
  double weightX[ ];    // largest weight for each column
  double weightY[ ];    // largest weight for each row
Methods

GridLayout Implements LayoutManager. A GridLayout provides you with slightly less control over the layout than the GridBagLayout class. A GridLayout is created by specifying a number of rows and columns. Each subsequent add() statement will place the specified component in the layout, adjusting the size of all components. As a result, all components in a GridLayout are of the same size.

Methods

Abstract Image. The Image class provides you with an platform-independent manner of handling images. Regardless of the source of the image or the platform, all the following methods may be used on all Images.

One problem often encountered with images is that they often take some time to completely load. As a result, in all methods where this could be problematic, it is necessary to specify an ImageObserver (an object that implements the ImageObserver interface). If the method is unable to return the requested information, it will return a value of -1 or a null string. However, once the information does become available, the information will be sent along to the imageUpdate() method of the specified ImageObserver.

See "java.awt.Image," p. 472
Field
Methods
This method is useful when using ImageFilters. By first invoking this method, you can obtain the source of the Image to be used when creating a new java.awt.image.FilteredImageSource.

Insets Implements Cloneable. The Insets class is a tool to be used by layout managers, particularly GridBagLayoutManager. An Inset may be used to set and track the amount of space that will be inserted between the components of the layout and the border of the container.

See Listing 14.6, "GridbagLayout Example," p. 446
Fields
Methods
Returns a string containing the class name and the four spacing values.

Label Extends Component. A Label is a convenient way of placing a single line of text on the screen. Because it is a Component, it may be placed in a layout manager.

Fields
Methods

List Extends Component. A List is a useful scrollable index of textual headers. When using a List, you may not only add items to the end of the list, but may also insert them within the list. Furthermore, during execution, you can query the list for information regarding the user's actions or even scroll the list yourself using the makeVisible() method.

Methods
Scrolls the list to make the specified index visible.

MediaTracker. A MediaTracker is a means of managing a number of media objects, such as images and audio clips. (However, as of the 1.0 JDK, only Images were supported.) Somewhat like an array, the MediaTracker assigns each a reference number. However, it also keeps track of the status of each image, allowing you to determine the status of each or lock up the tracker until all images have been loaded.

Fields
Methods

Menu Extends MenuItem Implements MenuContainer. A Menu is a column in a MenuBar. Like the standard "File" and "Help" headers in most applications, a Menu defines the title on the MenuBar as well as the headings in the column. When creating a menu, you must first create Menu items and then add them to your MenuBar.

 See the following section, "MenuBar Extends MenuComponent Implements
MenuContainer"
 See "Frame Extends Window Implements MenuContainer," p. 437
Methods

MenuBar Extends MenuComponent Implements MenuContainer. A MenuBar is a container for Menu items and serves as the head of the menu when displayed. In order to create a menu in your program, you must first create Menu items, and then add them to a MenuBar. By adding a MenuBar to the Frame, you are able to make the menu visible to the user.

See "Menu Extends MenuItem Implements MenuContainer," p. 456
See "Frame Extends Window Implements MenuContainer," p. 437

Also note the use of the Display class to enable the applet to monitor the user's
selections.


Listing 14.7  Menu Example
import java.applet.Applet;
import java.awt.*;

public class MenuExample extends Applet
{
   private Menu category;
   private MenuBar bar;
   private Display picture;

   public void init() {
     bar = new MenuBar();
     category = new Menu("Document");
     category.add("Option One");
     category.add("Option Two");
     category.add("Option Three");
     bar.add(category);

     category = new Menu("Session");
     category.add("Reset");
     category.add("Restart");
     bar.add(category);
      
     category = new Menu("Screen");
     category.add("Change colors");
     category.add("Display Titles");
     bar.add(category);


     picture = new Display();
     picture.setMenuBar(bar);
     picture.setTitle("Menu Example");
     picture.show();
   }
}

class Display extends Frame {
   public boolean action(Event evt, Object arg) {
     if(arg.equals("Option Two")) {
       System.out.println("Option Two was Selected");
     return true;
     }
   return super.handleEvent(evt);
   }

   public boolean handleEvent(Event evt) {
     if (evt.id == Event.WINDOW_DESTROY) {
       hide();   // closes the frame when appropriate
     return true;
     }
   return super.handleEvent(evt);
   }
}

Methods

Abstract MenuComponent. MenuComponent is the superclass for all classes dealing with menu related components.

See "Menu Extends MenuItem Implements MenuContainer," p. 456
Methods

MenuItem Extends MenuComponent. A MenuItem is a class that contains a string representation of an option on a menu. It is used and extended by the more useful menu classes.

See "CheckboxMenuItem Extends MenuItem," p. 416
Methods

Panel Extends Container. Panel is a simple container class that may be extended to create richer subclasses. java.applet.Applet is a subclass of Panel.

See Listing 14.3, "CardLayout Example Source Code," p. 413
Methods

Point. Point is a simple class to keep track of and manage an ordered pair.

Fields
Methods

Polygon. A Polygon is a class that enables you to define an arbitrary polygon. This class does not draw a polygon on the screen, but rather specifies the coordinates that can be used by the methods in the Graphics class.

To track the vertices, the class maintains two parallel arrays (xpoints[] and ypoints[]). For example, if point #2 is (4,5), then xpoints[3] will equal 4 and ypoints[3] will
equal 5.

See Listing 14.5, "Graphics Example," p. 439
Fields
Methods

Rectangle. The Rectangle class defines the vertices of a rectangle. While it does not actually draw the rectangle on the screen, it does enable you to create and track rectangular objects.

Fields
Methods

Scrollbar Extends Component. A Scrollbar is a versatile component used to create scrollbars in your programs. The Scrollbar class enables you to create both vertical
and horizontal scrollbars and to set the value range for the scrollbar. Like any other
Component, a Scrollbar can be placed by a layout manager.

The code in Listing 14.8 creates a very simple calculator that uses scrollbars to facilitate input. Although the scrollbars adjust themselves automatically, note how the Calculate button updates the TextField.


Listing 14.8  Scrollbar Example
import java.applet.Applet;
import java.awt.*;


public class ScrollbarExample extends Applet
{
   Scrollbar sb1, sb2;
   TextField info;
   Button trigger;

   public void init() {
   
     setLayout(null); // won't use one of the layout managers
     add(sb1);
     sb1.reshape(10,10,100,20);

     sb2 = new Scrollbar(Scrollbar.HORIZONTAL,30,20,0,100);
     add(sb2);
     sb2.reshape(10,70,100,20);

     trigger = new Button("Calculate");
     add(trigger);
     trigger.reshape(200,105,80,50);

     info = new TextField("0");
     add(info);
     info.reshape(10,150,75,75);
        
     refresh();
   }
   void refresh() {
     int sum = sb1.getValue() + sb2.getValue();
     info.setText("" + sum);
   }

   public boolean action(Event evt, Object arg) {
     if(arg.equals("Calculate")) {
       refresh();
       return true;
     }
     return false;
   }
}

Fields
Methods

TextArea Extends TextComponent. A TextArea is used for displaying and editing multiple lines of text. Because of this, a TextArea is created with the capability of being scrolled.

See Listing 14.6, "GridbagLayout Example," p. 446
Methods

TextComponent Extends Component. TextComponent is the basic building block for the text displaying components, TextArea and TextField. Nevertheless, its constructor method has a restricted level of access-preventing you from making use of it unless you are developing within the java.awt package. Therefore, while establishing several useful methods, this class is not usually used directly.

Methods

TextField Extends TextComponent. A TextField is a simple component that is used to display and edit a single line of text.

Methods

Toolkit. The Toolkit class serves as the link between the abstract methods of the AWT and the platform-specific native implementation of these methods. Generally, you will not have to interact with the Toolkit. However, it is occasionally convenient to use some of the Toolkit methods, such as getImage(). In such cases, you must employ the getToolkit() method in the Component class to obtain the current Toolkit. Note that the getToolkit() method returns the Toolkit of the Frame in which the component resides.

Methods

Window Extends Container. A Window is a simple container that serves as a pop-up window spawned from a Frame. Because the Frame class extends the Window class and builds upon it, you may want to use a Frame instead of a Window.

Methods

Interfaces

LayoutManager. The LayoutManager defines a behavior that is implemented by all layout managers.

MenuContainer. The MenuContainer interface is implemented by all containers that deal with menus.

Methods

java.awt.image

Although related to the java.awt package, this package consists of tools designed to handle images coming across a network. Because all classes and interfaces in this package are closely related, you will see that many of the methods appear multiple times.

Classes

Abstract ColorModel. This abstract class declares the functionality necessary for any ColorModel-a class that translates a color identifier (red, green, blue, or alpha) into the actual color to be displayed.

Field
Methods

CropImageFilter Extends ImageFilter. The CropImageFilter class is an image filter that enables you to create a new image based on a portion of another image.

The image in the upper left-hand corner of the applet was created by extracting a portion of the larger image in the middle using the CropImageFilter class in Listing 14.9.
Although each image filter is different, the steps taken here are the general steps to make use of any image filter.


Listing 14.9  CropImageFilter Example
import java.applet.*;
import java.awt.*;
import java.awt.image.*;

public class CropImageFilterExample extends Applet {

   Image newimage, image;

   public void init() {

     image = getImage(getCodeBase(), "fract.jpg");  
     ImageFilter filter = new CropImageFilter(0,0,50,50);  
                          // set the properties for the filer

     /* The following statement creates an ImageProducer.    
       producer will be able to produce a new image using
       the source of the old image and the specified filter*/

     ImageProducer producer = new FilteredImageSource(image.getSource(),
                            
          filter);  

     newimage = createImage(producer);      
   }

   public void paint (Graphics g) {
     g.drawImage(newimage,10,10,50,50,this);
     g.drawImage(image,200,85,100,100,this);
   }
}

Methods

DirectColorModel Extends ColorModel. This class is used to translate machine-
dependent pixel values into their alpha, red, green, and blue components.

Methods

FilteredImageSource Extends Object Implements ImageProducer. A FilterImageSource enables you to pass the information that defines an image through a filter-somehow changing the appearance of the image. In most cases, the only method of this class that you will use is its constructor in conjunction with the createImage() method from the java.awt.Component class.

See Listing 14.9, "CropImageFilter Example," p. 473
See Listing 14.10, "MyImageFilter Example," p. 476
Methods

ImageFilter Implements ImageConsumer, Cloneable. The ImageFilter class, as it is, does essentially nothing. It receives information from an ImageProducer and sends the same information on to an ImageConsumer. If you are simply loading and displaying images, you have no reason to explicitly use this class. However, the ImageFilter class also provides you with the framework on which you can build your own image filters: objects that will somehow transform the image after it is created by an ImageProducer and before it is received by an ImageConsumer.

To create your own image filter, you must extend the ImageFilter class and override at least one of its methods. The six methods that provide you with access to the image data are setColorModel(), setDimensions(), setHints(), setPixels() (two versions), setProperties(), and imageComplete().

See Listing 14.9, "CropImageFilter Example," p. 473

The two images in the applet were both created from the same source file. However, as you can see, the image in the upper left-hand corner has been transposed and shifted somewhat. This transformation was achieved with the code in Listing 14.10.


Listing 14.10  MyImageFilter Example
import java.applet.*;
import java.awt.*;
import java.awt.image.*;

public class MyFilterExample extends Applet {

   Image newimage, image;

   public void init() {
     image = getImage(getCodeBase(), "fract.jpg");

     ImageFilter filter = new MyImageFilter(100);
     ImageProducer producer = new
          
FilteredImageSource(image.getSource(), filter);
     newimage = createImage(producer);
   }

   public void paint (Graphics g) {
     g.drawImage(newimage,10,10,100,100,this);
     g.drawImage(image,200,85,100,100,this);
   }
}

public class MyImageFilter extends ImageFilter {
   private int width ;
   private int shift;

   public MyImageFilter (int translation ) {
     shift = translation;
   }

   public void setDimensions(int width, int height) {
     consumer.setDimensions(width, height);
     this.width = width;
   }

/* This implementation of setPixels() shifts all columns
   over by the value of the shift field.  All columns that
   are pushed off the screen (to the left) are displayed on
   the right


To do this, the method scrolls through each column on  
   the screen.  If the column still fits once shifted, it is
   displayed in its new position.  If it is pushed off the  
   screen, it is wrapped around relative to its original
   position.  */

   public void setPixels(int x, int y, int w, int h,
   ColorModel model, byte pixels[ ], int off, int scansize) {  
     for (int line = x; line < (x+w); line++) {
       if ( (line + shift) <= width)
         consumer.setPixels(line, y, 1, h, model, pixels,
                  off+shift, scansize);  
       else   
         consumer.setPixels(line, y, 1, h, model, pixels,
         off -width + shift, scansize);
     }
   }

/* Shifts all columns over by the value of the shift field.  
   All columns that are pushed off the screen (to the left)
   are displayed on the right */

   public void setPixels(int x, int y, int w, int h,
      ColorModel model, int pixels[ ], int off, int scansize) {  
     for (int line = x; line < (x+w); line++) {      
       if ( (line + shift) <= width)               
         consumer.setPixels(line, y, 1, h, model, pixels,
                  off+shift, scansize);  
      else   
        consumer.setPixels(line, y, 1, h, model, pixels,
                 off -width + shift, scansize);
     }
   }
}

You will note that this image filter only uses three of the six available methods. In general, the most important method is the setPixels() method inasmuch as it assigns each pixel a location. All other methods may be useful, but are not as important as the setPixels() method.

Note
The shifting of pixels is the result of placing them in a different position in the array (pixels[]) that contains the image. As a rule, pixel (u,v) is stored in pixels[ v * scansize + u + off].
If you wanted to store (u,v) in (u,v), you could simply substitute the following statement in Listing 14.10:
consumer.setPixels(line, y, 1, h, model, pixels, off, scansize);
However, in this example you want to shift the pixels in the x direction. To advance each pixel to the left, use the following statement:
consumer.setPixels(line, y, 1, h, model, pixels, off + shift, scansize);

Field
Methods

IndexColorModel Extends ColorModel. This class enables you to create a lookup table for a set of colors. The table will contain information regarding the individual components of the colors.

Methods

MemoryImageSource Implements ImageProducer. A MemoryImageSource enables you to create your own images. After storing the "picture" in an array of either bytes or integers, you are able to load the image from that array-not a saved file.

Methods

PixelGrabber Implements ImageConsumer. The PixelGrabber class is a special type of ImageConsumer designed to "grab" a rectangle of pixels belonging to an image. Note that you may grab pixels from either an ImageProducer or an already loaded image.

To grab a set of pixels, first create a pixel grabber, specifying what rectangle of pixels you want as well as the array in which you would like to store them. To actually grab the pixels, you must invoke the grabPixels() method.

Methods

Abstract RGBImageFilter Extends ImageFilter. The RGBImageFilter class provides you with a very convenient way to manipulate the appearance of an image by changing the colors of individual pixels. To use the RGBImageFilter class, you must override the class, creating a new class and defining the filterRGB() method. This method can be used to adjust the display of the pixels by manipulating the individual color components.

What happened? As you can see, the appearance of the image in the upper left-hand corner has been changed. This was done with the code in Listing 14.11.

You will see that the only important method in the RGBFilterClass is the filterRGB() method. Implementing it in the MYRGBImageFilter class not only makes this class non-abstract, but also performs the actual chore of changing the value of the pixels.


Listing 14.11  MyRGBImageFilter Example
public class ImageFilterExample extends Applet {

   Image newimage, image;

   public void init() {

     image = getImage(getCodeBase(), "fract.jpg");
     ImageFilter filter = new MyRGBFilter();
     ImageProducer producer = new
           FilteredImageSource(image.getSource(), filter);
     newimage = createImage(producer);
   }

   public void paint (Graphics g) {
     g.drawImage(newimage,10,10,100,100,this);
     g.drawImage(image,200,85,100,100,this);
   }
}

public class MYRGBFilter extends RGBImageFilter {
   private int width;
   private int shift;

   public int filterRGB(int x, int y, int rgb) {
     return( rgb >> 1);
   }
}

Fields
Methods
If x and y are equal to -1, the given pixel was obtained from an IndexColorModel.

Interfaces

ImageConsumer. The ImageConsumer interface defines a set of behaviors to be implemented by classes that will load ("consume") images. In addition to establishing the behavior of these classes, this class can also be used as a reference-type variable to refer to the following methods and fields that must be defined in any ImageConsumer class.

Fields
A status value sent to imageComplete() to indicate that the creation encountered an error.
A value sent to setHints() to indicate that the pixels will be delivered in a random order.
A hint value sent to setHints() to indicate that the image contains a single frame.
A status value sent to imageComplete() to indicate that a frame of an image has been completely sent but more frames are yet to come.
A value sent to setHints() to indicate that the image has been completely delivered.
Methods

ImageObserver. The ImageObserver interface defines a set of behaviors that are implemented by classes that deal with images, and provides for asynchronous updates of
an Image. This is necessary because not all information pertaining to an Image may
be available when it is first used. Specifying an ImageObserver in such methods as Graphics.drawImage() will cause that Object to receive updated information on the Image as it arrives.

Fields
Method

ImageProducer. The ImageProducer class declares a set of behaviors common to any class that will produce an image, such as FilteredImageSource or MemoryImageSource.

See Listing 14.9, "CropImageFilter Example," p. 473
See Listing 14.11, "MyRGBImageFilter Example," p. 483
Methods

java.io

The java.io package serves as the standard input/output library for the Java language. Providing you with types as simple as a StringBufferInputStream or as complex as a RandomAccessFile, this package enables a virtually unlimited number of communication possibilities.

The java.io package is composed primarily of two types of classes: those that create streams and those that manage them. The following table is a summary showing where these classes fit into this model:

Stream CreatorsStream Managers
ByteArrayInputStreamBufferedInputStream
ByteArrayOutputStreamBufferedOutputStream
FileInputStreamDataInputStream
FileOutputStreamDataOutputStream
PipedInputStreamFilterInputStream
PipedOutputStreamFilterOutputStream
StringBufferInputStreamLineNumberInputStream
 PrintStream
 PushbackInputStream
 RandomAccessFile
 SequenceInputStream
 StreamTokenizer
 StringBufferInputStream

In general, a stream manager may be created using the syntax:

     StreamManagerType instanceofManager = new StreamManagerType( StreamCreatorType);

where StreamManagerType and StreamCreatorType are both the names of classes.

Classes

BufferedInputStream Extends FilterInputStream. The buffered stream classes provide you with a more efficient way of reading information from an InputStream. Instead of allowing information to pile up on the stream and wait for you to read it, the BufferedInputStream will read in all data on the stream and place it in a buffer every time you invoke one of the read() methods. Therefore, subsequent information may come from the buffer, not the stream-saving you time.

The BufferedInputStream will continue to read from the buffer until it becomes empty. If you attempt to read from an empty buffer, the BufferedInputStream will block it until there is sufficient data from the stream to satisfy your request. Any additional data waiting in the stream will be stored in the buffer.

Fields
Methods

BufferedOutputStream Extends FilterOutputStream. A BufferedOutputStream is an OutputStream manager that enables you to write to the stream in a more efficient manner. Instead of writing to the stream in small pieces every time you invoke a write() method, a BufferedOutputStream will write your information to a temporary buffer. This information is then written to the stream either when the buffer becomes filled or when you invoke the flush() method.

Caution
Make sure that you invoke the flush() method before closing the OutputStream! If you fail to do so, some of your information may be caught in limbo-left in the buffer and never sent.

Fields
Methods

ByteArrayInputStream Extends InputStream. A ByteArrayInputStream is a type of InputStream and thus can be handled like any other InputStream. However, a ByteArrayInputStream does not receive its information from a standard stream, but rather from an array that you have already created.

When you create a ByteArrayInputStream, you must specify the contents of the buffer that you want to use. This InputStream will then read from this buffer when read commands are invoked.

Fields
Methods

ByteArrayOutputStream Extends OutputStream. A ByteArrayOuputStream is a special OutputStream that can be used to accumulate data. Instead of writing directly to a stream, the ByteArrayOutputStream will write to a temporary buffer that will grow as needed to accommodate your data.

After you have written your data to the buffer, you can

Fields
Methods

DataInputStream Extends FilterInputStream Implements DataInput. A DataInputStream allows you to read basic data types from a stream. For example, instead of reading a string from a stream byte by byte, you may use the readLine(), which will read until a newline character is encountered.

See "DataOutputStream Extends FilterOutputStream Implements DataOutput," p. 494
Methods

DataOutputStream Extends FilterOutputStream Implements DataOutput. The counterpart of the DataInputStream class, the DataOutputStream class, enables you to write data to a stream in the form of basic data types, such as characters or doubles rather than a series of bytes.

See "DataInputStream Extends FilterInputStream Implements DataInput," p. 492
Field
Methods

File. The File class provides you with a means of performing basic file management operations. Although it does not provide you with direct access to the information contained in the files, it does enable to you perform "housekeeping" operations, such as making directories, finding the length of a file, or comparing the versions of two separate files. Because of the nature of its operations, this class relies heavily on native methods.

See "DataInputStream Extends FilterInputStream Implements DataInput," p. 492
See "DataOutputStream Extends FilterOutputStream Implements DataOutput," p. 494
See "FileDialog Extends Dialog," p. 431

Caution
Although Java per se has no problems with the functionality in the class, many of the tasks performed by the methods in this class raise several security concerns. Therefore, while your code compiles, you may not be able to perform many of these tasks if you are running your code as an applet in either the appletviewer or Netscape.

Fields
Methods

FileDescriptor. The FileDescriptor class is used internally by Java classes that deal with files. This class encapsulates the machine-based view of a file-describing each file as an integer. Uses of the FileDescriptor object, therefore, can be found in the FileInputStream and FileOutputStream. Due to the nature of the class, all fields and method are based on native properties.

Fields
Methods

FileInputStream Extends InputStream. A FileInputStream, as its name implies, is a specialized InputStream designed to obtain input from a file. In contrast to a standard InputStream, a FileInputStream does nothing more-save the capability to direct the input stream to a file.

Due to this limited capacity, FileInputStreams are generally managed with more robust input stream managers, such as DataInputStream. A DataInputStream can be created from a FileInputStream simply by specifying the FileInputStream as the parameter in the DataInputStream constructor.

See "DataInputStream Extends FilterInputStream Implements DataInput," p. 492
Methods

FileOutputStream Extends OutputStream. A FileOutputStream is a simple extension of the OutputStream class than enables you to write data to a file. Like FileInputStream, FileOutputStreams are generally managed with a more robust stream manager, such as DataOutputStream.

See "DataOutputStream Extends FilterOutputStream Implements DataOutput," p. 494
Methods

FilterInputStream Extends InputStream. A FilterInputStream is a non-abstract version of InputStream. It may be used to handle any input stream in a basic, yet useful, manner. Unfortunately, a FilterInputStream requires you to read your information as a series of bytes-complicating matters if you are reading more complex data types, such as doubles or even Strings. Therefore, FilterInputStreams are usually managed with more powerful stream managers, such as DataInputStream. FilterInputStream is
also the basis for all other InputStream managers, such as DataInputStream and PushBackInputStream.

How does FilterInputStream Differ from InputStream?
Why can you create an instance of a FilterInputStream, but not an InputStream? You cannot create an instance of an InputStream because it is abstract-its read() method is not defined. However, when creating a FilterInputStream, you must specify an InputStream that you want to manage, such as FileInputStream or ByteArrayInputStream. Because these classes have defined read() methods, the FilterInputStream manager employs the methods of the InputStream class in accomplishing its tasks.

Field
Methods

FilterOutputStream Extends OutputStream. The FilterOutputStream class provides you with a simple but effective manner of managing OutputStreams. This class is the basis for all other classes designed to manage OutputStreams, such as BufferedOutputStream and DataOutputStream.

See "FilterInputStream Extends InputStream," p. 499
Field
Methods

Abstract InputStream. The InputStream class is a basic class for handling input across a stream. While it serves as the basis for all input stream classes, it is nevertheless abstract-which means that you cannot create an instance of an InputStream. However, because all input stream classes derive from the InputStream class, you can handle all InputStreams by using the methods found in the InputStream class.

You will see that the input stream handlers (such as DataInputStream) accept an InputStream as a parameter. Although it is impossible to supply these handlers with a pure InputStream, the stream that you do pass to a handler will be derived from the InputStream class and thus may be treated as a type of InputStream.

Methods

LineNumberInputStream Extends FilterInputStream. A LineNumberInputStream is a input stream manager. Slightly elaborating upon the FilterInputStream, it allows you not only to read information from the stream, but also to keep track of the number of lines that you have read from this stream.

Methods

Abstract OutputStream. The OutputStream class is an abstract class that establishes the foundation for all types of OutputStream classes. Although you cannot create an instance of an OutputStream-because all output streams are based on this class-it provides you with a convenient means of handling all types of output streams.

Methods

PipedInputStream Extends InputStream. The PipedInputStream class works in conjunction with the PipedOutputStream class. By connecting a PipedInputStream to a PipedOutputStream, you are able to create two separate threads-each running independently-with the capability to send information to each other in an extremely convenient manner.

See "PipedOutputStream Extends OutputStream," p. 506

The output was produced by linking instances of the PipedInputStream and PipedOutputStream classes-each being managed by a separate thread (see Listing 14.12). Due to the idiosyncrasies of thread management, the sleep() statement in the Writer class is necessary to shift control to the Reader class. Without the sleep() statement, the Reader class would first write all of its data, relinquish control to the Reader class, and then allow it to read in all the data.

Also note that in this example, I use the error handling of the Reader class to exit the program. Once the Writer class completes its task, the output pipe is shut down. This causes an exception in the Reader class-causing the entire program to terminate.


Listing 14.22  An Example of PipedInputStream and PipedOutputStream
class Reader extends Thread {

   PipedInputStream in;
   boolean running;

   Reader(PipedOutputStream out) {
     try {
       in = new PipedInputStream(out);
       running = true;
     }
     catch (Exception e)
       System.out.println(e.toString() );
   }

   PipedInputStream getStream() {
      return (in);
   }

   public void run() {
     while (running) {
       try {
         System.out.println("Reading " +in.read());
       }
       catch(Exception e) {
         System.out.println("Done");  
         System.exit(1);
       }
     }
   }
}


class Writer extends Thread {
   public PipedOutputStream out;
   boolean running;

   Writer() {
     out = new PipedOutputStream();
     running = true;
   }

   PipedOutputStream getStream() {
     return (out);
   }

   void connectTo(PipedInputStream in) {
     try {
       out.connect(in);
     }
     catch (Exception e) {
       System.out.println(e.toString() );
       running = false;
     }
   }

   public void run() {
     try {
       for (int i = 1; i <= 10; i++)     {
         out.write(i);
         System.out.println("Wrote " + i + "  ");
         yield();
         sleep(2000);
        }
     catch(Exception e) {
       System.out.println(e.toString() );
     }
   }
}


public class PipedExample {
   public static void main(String args[ ]) {
     Writer w = new Writer();
     Reader r = new Reader( w.getStream() );
     w.connectTo( r.getStream() );
     r.start();
     w.start();
   }
}

Methods

PipedOutputStream Extends OutputStream. Working with a PipedInputStream, a PipedOutputStream enables two concurrently running Threads to communicate via a stream.

See "PipedInputStream Extends InputStream," p. 504
Methods

PrintStream Extends FilterOutputStream. A PrintStream is a very straightforward stream manager that prints out all types of data as strings.

Caution
Because a PrintStream prints everything as a String, all data types-even integers and doubles-will be printed as a string. Consequently, be careful when later reading this information. All data types except strings and characters must be first read as strings or bytes and then converted to their natural data types.

Methods

PushbackInputStream Extends FilterInputStream. A PushbackInputStream is a stream manager that is quite useful when parsing a stream. It enables you to "take a peek" at the next byte in the stream without completely removing the byte from the stream. If you decide that you don't want the specific byte, you may return it to the stream via the unread() method. This will "push" the specified byte back onto the stream, making it the next character to be returned by any future read() statements.

How Do You Place a Character Back on a Stream?
You don't. A PushBackInputStream does not actually place the character back on the stream. However, it stores it in a protected field named pushBack. The next time you read from the stream, it will return the pushBack byte-not the next byte from the stream.
Field

RandomAccessFile Implements DataOutput DataInput. Closely resembling a random access file in C, the RandomAccessFile class provides you with an extremely flexible tool for file input and output. Furthermore, by enabling you to specify the type of access allowed-either read-only or read and write-this class supplies you with a degree of security.

Methods

SequenceInputStream Extends InputStream. A SequenceInputStream enables you to link multiple InputStreams to form one pseudo-stream. The SequenceInputStream will read from one stream until completion, at which time it will read from the next stream.

Methods

StreamTokenizer. A StreamTokenizer is a heavy-duty tool used for parsing streams. Using the nextToken() method, you are able to scan the stream for any tokens-characters defined by you to be important. When such a character is encountered, the StreamTokenizer will return a flag. The flag will either be the character itself or a special flag, such as TT_EOF (which signifies the end of the stream).

Fields
Methods

StringBufferInputStream Extends InputStream. A StringBufferInputStream enables you to read information from a String as if it were an InputStream.

See "PushbackInputStream Extends FilterInputStream," p. 508
Fields
Methods

Interfaces

DataInput. This interface declares a set of methods defining the behavior of a machine-independent input stream. It is implemented by the DataInputStream class.

Methods

DataOutput. This class declares a set of methods that enable machine-independent output of data. It is implemented by the DataOutputStream class.

Methods

FilenameFilter. A FilenameFilter is a tool to be used when screening directories. It is used in the File and java.awt.FileDialog classes.

Method

java.lang

These classes are essentially the heart of the java language. This package includes not only wrappers for the basic data types, such as Integer and String, but also a means of handling errors through the Throwable and Error classes. Furthermore, the SecurityManager and System classes supply you with some degree of control over the client's system, albeit the command prompt or the Java Console in Netscape.

Classes

Boolean. While a boolean is a primitive data type, the Boolean class serves as a wrapper class-providing you with a means of better handling boolean values. Wrapper classes for primitive data types are also useful in using hashtables, which only accept objects-not primitive data types.

Fields
Methods

Character. The Character class serves as a wrapper class for handling char values.

Fields
Methods

Class. To the Virtual Machine, every class is an Object. However, within the Virtual Machine, every class (and interface) is handled with the Class class. While the Object class gives you information regarding an instance of the class (the actual object), this class gives you information regarding the code used in creating the class. Because you cannot create an instance of a Class, you must use the forName() method to return a Class object.

Methods

Abstract ClassLoader. A class loader can be used to load a class from a source other than the current server-such as a network. Because the process depends heavily on your particular circumstances, the actual loading of the class is left up to you.

Because the ClassLoader class is abstract, you must first extend the class and override the loadClass() method if you want to use a ClassLoader. Once this is done, you must employ the defineClass() method to create a Class object describing the class-which also enables you to create an instance of the class.

Methods

Compiler. This class is designed to provide an interface with future Java technology that will provide you with more control over the Java compiler. However, there is no complete set of libraries or means of creating a Compiler object as of the 1.0 JDK.

Methods

Double Extends Number. Double is a wrapper class designed to handle double values.

Fields
Methods

Float Extends Number. Float is a wrapper class designed to handle float values.

Fields
Methods

Integer Extends Number. Integer is a wrapper class designed to handle int values. Often, Integer objects are returned by methods in the API as a means of providing you with a number and a means to manage it.

Fields
Methods

long Extends Number. long is a wrapper class designed to handle long values.

Fields
Methods

Math. The Math class provides you with a wide variety of mathematical methods, as well as some handy constants, such as e and Pi.

Fields
Methods

Abstract Number. The Number class serves as the basis for all wrapper classes designed to handle number data types, such as Integer, Float, and Double.

Although int, double, and float are data types in their own right, they are considered primitive data types because they are much more basic that the richer objects used in Java. Although these primitive types facilitate more efficient code, they are often not robust enough for certain circumstances, such as hashtables, where it is necessary to treat each item as a full Object. Furthermore, each of these Number-type classes provides you with a means of handing data in a class-dependent nature. This gives you a very simple means of obtaining primitive values from more complex objects, such as Strings.

Methods

Object. The Object class is the basis for all classes in the Java programming language. Every class, even if you don't declare a superclass, will be derived from the Object class. Therefore, all methods in this class are accessible to all classes. However, this is not to say that you will ever have need to actually work with these methods.

Methods

Abstract Process. The Process class provides a handle for managing operations begun by Java programs. Returned by the exec() methods in the Runtime class, the Process class is generally used to monitor-not to control-the ongoing operation.

See the following section, "Runtime"
Methods

Runtime. The Runtime class enables you to interface with the system on which your program is running, as well as the Java Virtual Machine.

Caution
Although the exec() method is allowed under the appletviewer, it will cause a security restriction in Netscape.

The Runtime class enables you to perform tasks normally associated with the prompt, such as starting a file. The Runtime class is used to begin a game of Solitaire.

See "Abstract Process," p. 530

Listing 14.13  Runtime Example
public class RuntimeExample  {
   public static void main(String argv[ ]) {
     Runtime r=java.lang.Runtime.getRuntime();
     try{
       r.exec("\\winnt\\system32\\sol.exe");
     }
     catch (Exception e) {
       {System.out.println(e.toString() );
     }
   }
}

Methods

Abstract SecurityManager. The SecurityManager provides you with a means of instituting and configuring many security inspections that monitor the power of your programs. These checks are necessary when you consider that Java applets have the ability to run on both intranets and the Internet-networks where security and privacy are important issues.

To create your own security restrictions, it is necessary to subclass this class and define those methods that are important to your program. You will note that most methods in this class that check the validity of an action do not return any data types. Instead, they throw SecurityExceptions when the action is not allowed.

Field
Methods

String. The String class provides the basic nature and functionality for a string. Because the value of a String cannot change once created, this class is therefore primarily used for parsing, handling, and obtaining string values-not creating them. Although there are some methods that enable you to somewhat modify and add to the value of the string, these methods do not modify the String itself, but rather return a new String with the desired value.

Methods

StringBuffer. A StringBuffer is a dynamic string class that enables you to modify and add to string values. Extremely flexible, this class is used in creating string values-especially those obtained from a separate source, such as a socket connection or the applet tag parameters, as shown in Listings 14.14 and 14.15.


Listing 14.14  StringBuffer Example Using Applet Tag Parameters-HTML
<HEAD>
<TITLE>StringBuffer Example</TITLE>

<BODY>

<applet code="sbufe.class" width=300 height=300 >
<param name=linenum0 value="This is the">
<param name=linenum1 value="message I'm">
<param name=linenum2 value="trying to show.">
</applet>
</BODY>


Listing 14.15  StringBuffer Example
import java.applet.Applet;
import java.awt.Graphics;

public class StringBufferExample extends Applet {
   String message;

   /* This method parses the applet parameters, and returns  
      them in one string separated by spaces */
   public  void init() {
     StringBuffer mes;
     String val;
     int i = 0;

     mes = new StringBuffer();

     do {
       String paramName = "linenum" + i++;  
       val = getParameter(paramName);
       if (val != null) {     // continues until end
         mes.append(val);        // adds the message
         mes.append(' ');        // adds the space
       }
     } while (val != null);
     message = mes.toString();  // saves the message
                              // as a String
   }

   public void paint(Graphics g) {
     g.drawString(message,10,10);
   }
}

Methods

Caution
If the length is reduced, data may be lost.

System. Java programs, especially applets, are handled by the Java Virtual Machine in a manner that hides a great deal of functionality from you, the programmer. This is primarily the result of Java's aim to be completely platform-independent. However, in conjunction with the Runtime class, the System class enables you gain control of some system-related functions-such as garbage collection-all in a system-independent manner.

To use the System class, it is not necessary (and is in fact impossible) to create a System object. However, because all methods in the class are static, you may use the methods shown in Listing 14.16.


Listing 14.16  System Example
public class SystemExample  {

   public static void main(String argv[ ]) {

     System.out.print("This is an example of the standard");
     System.out.println("output stream.");

     String s = System.getProperty("java.version");
     System.out.println("I am using Java " + s + ".");
   }
}

Fields
Methods

Thread Implements Runnable. Threads are one of the most important topics in the Java language. Threads are individual processes that can run at the same time. By creating multiple threads, you are thus able to perform several tasks at once.

Threads are particularly useful in programs that deal with multiple sources of input. For example, you can create an applet that will accept input from both the user and a separate input stream, such as a networked socket. To do so, create the applet to deal with user input as you would normally, and then create a separate thread that reads and parses information from the stream.

Listing 14.17 demonstrates the use of a simple threaded class: Counter. While the threadex class is waiting for user input, the Counter class is counting in the background. Therefore, when the user presses the enter key, the value returned by the getCount() method has grown tremendously.

In particular, note the process used to create and begin the Counter class. To start execution of a thread, you must invoke the start() method. Furthermore, only the run() method of the threaded class has the ability to run concurrently.

See "Runnable," p. 550

Listing 14.17  Thread Example
public class ThreadEx  {

   public static void main(String argv[ ]) {
     Counter c = new Counter();
     c.start();                     // starts the counter

     for (int i = 1; i <= 5; i++) {                
       try {
         System.in.read();                
       }
       catch (Exception e) {
           System.out.println( e.toString() );
       }
       System.out.println(c.getCount() );
     }  // end for loop

     c.stop();
     System.exit(1);
   }
}


class Counter extends Thread {
     private int count;

     public void run() {
       count = 0;
       while(true)         // creates a continual loop
         count++;
     }
     public int getCount() {
       return count;
     }
}

Fields
Methods
Places in the array every active Thread in the ThreadGroup of this Thread. It returns the number of Threads placed in the array.

ThreadGroup. Because threads are somewhat independent processes, it is often advantageous to place some constraints on them in order to manage them better. The ThreadGroup class enables you to create collections of Threads. Furthermore, it enables you to create a hierarchy of ThreadGroups in which a Thread can access all
Threads in the same group, but no Threads above it in the current hierarchy.

Methods

Throwable. A Throwable object can be thrown by a method. The Throwable class defines a common set of behaviors for all objects that are thrown from methods. All exceptions and errors are derived from the Throwable class.

See "Exceptions," p. 579
See "Errors," p. 581
Methods
java.lang.ArithmeticException: / by zero
         ppletname.init(appletname.java:6)
        sun.applet.AppletPanel.run(AppletPanel.java:243)
       at java.lang.Thread.run(Thread.java:289)

Interfaces

Cloneable. Although this interface consists of no methods, it nevertheless provides you with a lot of flexibility. It serves as a flag to the Object class. If a class used implements the Cloneable interface, you can create a copy of such an object.

Runnable. The Runnable interface is a chief example of the power of interfaces. By implementing the Runnable interface, you can create a class-most often an applet-that can also serve as a thread.

In Listing 14.18 and Listing 14.19, a simple applet class is created that serves as a message scroller. Using the status bar at the bottom of the browser screen, you are able to scroll through a series of messages that have been obtained from the applet tag parameters.

See "Thread Implements Runnable," p. 543

Listing 14.18  Runnable Example-HTML
<HTML>
<HEAD>


<TITLE>Power Computers Inc. Homepage</TITLE>
</HEAD>


<center>
<h2>Power Computers Inc.<br>
How Computers Should be Built</h2>

<hr width=45%>

<a href="\products.html">Our Products</a><P>   
<a href="\stocks.html">Investment Information</a><P>  
<a href="\operators.html">Consumer Support</a><P>  
</center>

<applet code="runne.class" width=0 height=0 >
<param name=linenum0 value="This is the message.">
<param name=linenum1 value="It keeps going,">
<param name=linenum2 value="and going...">
<param name=linenum3 value="...and going.">
</applet>
<hr width=45%>
</BODY>
</HTML>

Listing 14.19  Runnable Example-Java Code
import java.applet.Applet;

public class RunnableEx extends Applet implements Runnable
{
   Thread display;
   int pos, max_mes;
   String message[ ];

   /* This method obtains the applet parameters and stores
      them in message[ ].  It also sets the max_mes value */

   public void init() {   
     String val;
     int i = 0;
   
     message = new String[30];
                              // can accept up to 30 messages
     do {
       String paramName = "linenum" + i;
       val = getParameter(paramName);
       if (val != null) {
         message[i] = val;
        i++;
       }
     } while (val != null);
    
     max_mes = i-1;    /* we don't want to display the null
              message that caused the do loop to terminate */
     pos = 0;

     for (int j = 0; j <= max_mes; j++)
     System.out.println(j+message[j]);
   }

   /* This method creates and begins the thread. */
   public void start() {
     if (display == null)
       display = new Thread(this);
       display.start();
   }

   public void stop() {
     if (display != null) {
       display.stop();
       display = null;
     }
   }

   public void run() {
  /* We don't want the scroller to receive too
    much attention. */
   Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
   
   while (display != null) {
     getAppletContext().showStatus( message[pos++]);
     if (pos > max_mes)
       pos = 0;

       try {
         Thread.sleep(1000);    // pauses
       }
       catch (Exception e) {
         System.out.println( e.toString() );
       }  // end catch
     }  // end while
   }  // end method
}  // end class

For the sake of simplicity, an array of Strings is used to store the lines of text. To create a more efficient and flexible model, it would be advisable to use a more adaptive construct, such as a Vector.

Method

java.net

Because Java is a network-based language, this comparatively small package is very useful. Most importantly, it provides you with the capability to communicate with other sources of information by creating or connecting to sockets or making use of URLs and Internet addresses.

Classes

Abstract ContentHandler. This class is used to return a specific type of Object from an URL. It is called by the ContentHandlerFactory when an appropriate object is found in an URL.

Methods

DatagramPacket. A DatagramPacket is a bundle of information that can be transmitted across a networking stream. Such an object encapsulates a lot of information about the bundle, including the information contained, its length, and the host from which it was sent.

The following are private fields within the class:

private byte[ ] buf;
private int length;
private InetAddress address;
private int port;

These fields cannot be accessed explicitly in your code; however, it is advantageous to know what a DatagramPacket does and does not contain.

See "DatagramSocket," p. 553
Methods

DatagramSocket. A DatagramSocket is a socket that is used in transmitting a DatagramPacket. A DatagramSocket is different from a standard Socket in that it implements no means of error checking. It does not ensure that all packets are sent or received in their entirety. Therefore, it is referred to as unreliable.

See "DatagramPacket," p. 552
Methods

Final InetAddress. An InetAddress is a convenient manner of handling Internet addresses. It can be used to store both raw IP addresses, as well as more friendly host names.

Methods

ServerSocket. ServerSocket creates a server-side socket to be used in communications. By default, it is created based on the PlainSocket SocketImpl, which performs no security checks. However, you can specify the socketImpl for the ServerSocket to enhance security restrictions.

Methods

Socket. Socket creates a client-side socket to be used in communications. By default, it is based on the PlainSocket SocketImpl, which performs no security checks. However, you can specify the socketImpl for the ServerSocket to enhance security.

When using a Socket, you must consider whom you will be speaking to. In general, you will communicate with a socket server residing on a specific port. In such a case, will you be writing the server? What protocol will be used? Will the host name and port be fixed?

Furthermore, you must remember to use the getInputStream() and getOutputStream() methods to communicate with the socket, inasmuch as these streams are not accessible outside of the sun packages.

The code in Listing 14.20 lays the foundation for a standard socket communication. The DataInputStream in and the OutputStream out will enable you to freely communicate over the socket if the connection has been successful.


Listing 14.20  Socket Example
import java.net.Socket;
import java.io.*;
public class Client {
   String host = "host.name.com";
   int port = 1500;

   try {
     me = new Socket(host,port);
     in = new DataInputStream(me.getInputStream());
     out = me.getOutputStream();
   }
   catch (Exception e) {
       System.out.prinln( e.toString()  );
   }
    .
    .
    .
}

Methods

Abstract SocketImpl. The SocketImpl class defines a set of behaviors necessary for communication between sockets. This functionality is integral to socket communication and is used by the Socket and ServerSocket classes. However, most programmers find little need to use it explicitly.

Fields
Methods

URL. The function of the URL class is twofold. Most simply, it enables you to handle the semantic operations of URL, such as parsing out the file or host name of the URL. More importantly, however, it also serves as a handle for the retrieval of the information stored at the specific URL.

Methods

For example, examine the following code:

URL u1 = new URL("http","www.xyz.com",1500,"/foo.html#abc");
URL u = new URL(u1, "funny.html");
System.out.println( u1.toString() );
System.out.println( u.toString() );

The output will look as follows:

http://www.xyz.com:1500/foo.html#abc
http://www.xyz.com:1500/funny.html

Abstract URLConnection. The URLConnection class is an abstract class that can be used to assist in managing a connection based on an URL object.

Fields
Methods

URLEncoder. This class is simply a means of translating standard strings into x-www-form-urlencoded format. This process involves such conversions as changing spaces to '+' symbols and representing non-alphanumeric characters with hexadecimal numbers. This is the format that you will see used in standard URLs when passing information to CGI scripts.

Method

Abstract URLStreamHandler. An URLStreamHandler is a rather simple class used to transform an URL into an URLConnection.

Methods

Interfaces

ContentHandlerFactory. A ContentHandlerFactory can be used to create a manager that will return the appropriate ContentHandler for a specified MIME type. Such classes are used by the URLConnection class to correctly handle incoming data.

Method

SocketImplFactory. The SocketImplFactory enables you to make use of the SocketImpl class. The SocketImplFactory class will return a SocketImpl in response to a request to create a socket. By using the setSocketFactory in the java.net.severSocket class, you can specify which SocketImplFactory you want to use and thus which SocketImpl will be employed.

URLStreamHandlerFactory. By means of the CreateURLStreamHandler() method, the URLStreamHandlerFactory class creates URLStreamHandlers for specific types of data streams. This class is generally not explicilty used in programs.

Method

java.util

This package is essentially a smorgasbord of useful classes that do not truly fit into any of the other packages. Among these handy classes are the Date class, designed to manage and handle operations with dates; the Hashtable class; and ADTs, such as Stack and Vector.

Classes

BitSet Implements java.lang.Cloneable. A Bitset is a dynamic collection of bits that has the added capability of basic logical operations. Although you may perform some logical operations on a BitSet, the methods do not return a new BitSet, but rather modify the current BitSet. As shown in Listing 14.21, the logical operation will result in a change of the original BitSet.


Listing 14.21  BitSet Example
import java.util.BitSet;

public class BitsetExample {
   public static void main(String argv[ ]) {

     BitSet a = new BitSet();
     BitSet b = new BitSet();

     a.set(0);
     a.set(1);
     a.set(2);

     b.set(0);
     b.set(1);
     b.set(8);
     b.set(9);

     System.out.println("This is the first set: " + a);
     System.out.println("This is the second set: " + b);
     a.and(b);     // places all elements in both sets into a
     System.out.print("The following elements are in both");
     System.our.println(" sets: " + a );
   }
}

Methods

Date. The Date class provides you with a convenient means of managing dates and times. Rather flexible, this class enables you to set and manipulate the date in a number of ways, and can handle time zone and daylight-saving time conversions.

Methods
To obtain the current time in milliseconds since 00:00:00 GMT, January 1, 1970, use the System.currentTimeMillis().

Abstract Dictionary. This class defines the behavior of a Hashtable. While all of its methods serve a purpose in a Hashtable, they are all abstract in this class.

Methods

Hashtable Extends Dictionary Implements java.lang.Cloneable. The Hashtable class is a simple implementation of a hashtable ADT. A hashtable provides you with a convenient and efficient means of storing information based on a distinct relationship. Like an array, whose elements are each paired with a specific index, each element in a hashtable is paired with a specific key. By using this key, you are able to retrieve the information stored in the table.

One important consideration when using the Hashtable class is that every key and element must be an Object. As you can see, this is not a problem when dealing with strings (see Listing 14.22).


Listing 14.22  Hashtable Example Using String Objects
import java.util.*;
import java.io.DataInputStream;

public class HashtableExample  {

   public static void main(String argv[ ]) {
     Hashtable phones = new Hashtable();
     String name = null;
     String phone = null;

     phones.put("Danny", "555-0718"  );
     phones.put("Jason", "555-0031"  );
     phones.put("Jaime", "555-2191" );
     phones.put("Jeff",  "555-1391" );

     System.out.print("Please enter a name ==> ");
     System.out.flush(); // forces the prompt to be displayed
     DataInputStream din = new DataInputStream(System.in);

     try {
       name = din.readLine();
     }
     catch (Exception e) {
       System.out.println( e.toString() );
     }

     if (phones.containsKey(name)) {     /* checks to see if
                                         the name is valid */
       phone = (String)phones.get(name);
       System.out.println(name + "'s phone number is " +phone + "." );
     }
     else {
       System.out.print("Sorry.  I don't know who ");
       System.out.println(name + " is.");
     }
}

The requirement to use full-blown Objects poses a slight problem when dealing with primitive data types, such as an int or a float. As shown in Listing 14.23, it is necessary to create a wrapper Object to handle such primitive data types. This wrapper must be used initially to store the value and again used when retrieving the information.

Listing 14.23  Hashtable Example Using Integer Objects
import java.util.*;
import java.io.DataInputStream;

public class HashtableExample2  {

   public static void main(String argv[ ]) {
     Hashtable ages = new Hashtable();
     String name = null;
     Integer age = null;

     ages.put("Danny", new Integer(13) );
     ages.put("Jason", new Integer(7)  );
     ages.put("Jaime", new Integer(39) );
     ages.put("Jeff", new Integer(54)  );

     System.out.print("Please enter a name ==> ");
     System.out.flush();
      DataInputStream din = new DataInputStream(System.in);

    
     try {
       name = din.readLine();
     }
     catch (Exception e) {
       System.out.println( e.toString() );
     }

     if (ages.containsKey(name)) {
       age = (Integer)ages.get(name);
       System.out.print(name + "is " +age.intValue())';
       System.out.println(" years old." );          }
     }
     else {
       System.out.print("Sorry.  I don't know who ");  
       System.out.println(name + " is.");
     }
   }
}

Methods

Observable. The Observable class enables you to create an Object containing data that will be manipulated in close connection with other objects. To use this class, you must extend it to create your own "observable" class. This class will have the ability to communicate with a number of Observer classes via the notifyObservers() method. As a result, any change in the Observable class can trigger an appropriate response in all Observers.

See "Observer," p. 578
Methods

Properties Extends Hashtable. The Properties class is a Hashtable that may be saved and/or loaded. It is generally used to handle system properties, inasmuch as it is often necessary to retrieve these properties and sometimes convenient to be able to store them.

See "System," p. 541
Field
Methods

Random. The Random class encapsulates the behavior necessary for creating random numbers.

Methods

Stack Extends Vector. The Stack class implements a standard stack ADT. A stack follows the Last In First Out (LIFO) algorithm in which new items are placed on top of the stack-thereby making them the first items removed. In Java, each item in a stack must be a full-blown Object.

Methods

StringTokenizer Implements Enumeration. The StringTokenizer class enables you to parse a string consisting of several sub-strings.

In using a StringTokenizer, there are two internal fields that may be altered: the
delimiters string and the value retTokens. The delimiters string contains all tokens that are important. When parsing the string, the StringTokenizer will return a string if the current characters are in delimiters. retTokens is a flag that specifies whether or not to return the delimiter characters as separate tokens.

Methods

Vector Implements java.lang.Cloneable. A Vector is a dynamic array, most useful when dealing with an unknown quantity of data that will be changed frequently. Although based on the structure of an array, a Vector will automatically grow to provide new memory when needed. Furthermore, this capability enables you to perform more manipulative tasks, such as removing an element from a Vector or inserting an element into the middle of the Vector.

When using a Vector, keep in mind that-like a Hashtable-all elements must be Objects. Therefore, if you want to store simple data, such as an int or float, you must use the wrapper classes in the java.lang package.

Fields
Methods

Interfaces

Enumeration. An Enumeration is a simple way to handle a set of items without having to worry about the number of items contained in the set. This is necessary when dealing with many groups of data that do not provide you with a simple manner of dealing with each element in a sequential manner, such as Hashtables and the applets in an AppletContext. By using an Enumeration, you are able to scroll through the items-such as the keys in a set of Properties, the applets in an AppletContext, or the sub-strings in a StringTokenizer-in a very simple manner.


Listing 14.24  Enumeration Example
import java.util.Enumeration;
import java.util.Properties;

public class EnumerationExample {

   public static void main(String args[ ]) {

     Enumeration propNames = System.getProperties().propertyNames();
     int index = 1;

      while (propNames.hasMoreElements() )
        System.out.print("Property " + (index++) + ": ");
        System.out.println(propNames.nextElement() );
     }
}

Methods

Observer. The Observer interface is used in conjunction with an Observable class. By adding an Observer to the Observable class list of observers, the Observable class will be informed of any important changes in the Observable class. (This communication transpires whenever the notifyObservers() method is invoked in the Observable class.)

Method
See "Observable," p. 572

Exceptions

Exceptions provide you with a means of managing the ordinary runtime problems that may be encountered during execution of your program. All exceptions are derived from the java.lang.Exception class and most consist only of two constructor methods. Consequently, only the constructor methods for the java.lang.Exception class are listed here.

Unless otherwise noted, all exceptions may be created with no parameters or with a descriptive string as a parameter. Exceptions are handled by using the try...catch construct. Once an exception has been caught, it may be dealt with or thrown to the calling method. Listing 14.25 is an example of a simple division method that sets the result equal to zero if division by zero occurs.


Listing 14.25  Catching an Exception
int divide(int a, int b) {
   int val;
   try {
      val = a / b;
   }
   catch(ArithmeticException e) {
     System.out.println("Invalid data.  val set to 0.");
     val = 0;
   }
   return (val);
}

To throw an exception, you must use the throw statement, as shown in Listing 14.26 and Listing 14.27.


Listing 14.26  Throwing a Caught Exception

void connect(String host, int port) throws IOException {
  try {
    s = new Socket(host,port);
  }
  catch(IOException e) {
    throw e;
  }
}


Listing 14.27  Throwing a New Exception
static void connect(String host, int port) throws IOException {
  /* Makes sure the port satisfies our system policy */
  if (port < 1600)
    throw new SocketException("Port under 1600");

   try {
     s = new Socket(host,port);
   }
   catch(IOException e) {
     throw e;
   }
}

java.awt

AWTException

AWTException(String message)

java.io

EOFException Extends IOException

FileNotFoundException Extends IOException

IOException Extends java.lang.Exception

InterruptedIOException Extends IOException

UTFDataFormatException Extends IOException

java.lang

ArithmeticException Extends RuntimeException

ArrayIndexOutOfBoundsException Extends IndexOutOfBoundsException

Constructors
ArrayIndexOutOfBoundsException( )
ArrayIndexOutOfBoundsException(int invalid_index)
ArrayIndexOutOfBoundsException(String message)

ArrayStoreException Extends RuntimeException

ClassCastException Extends RuntimeException

ClassNotFoundException Extends Exception

CloneNotSupportedException Extends Exception

Exception Extends Throwable

Methods

IllegalAccessException Extends Exception

IllegalArgumentException Extends RuntimeException

IllegalMonitorStateException Extends RuntimeException

IllegalThreadStateException Extends RuntimeException

IndexOutOfBoundsException Extends RuntimeException

InstantiationException Extends Exception

InterruptedException Extends Exception

NegativeArraySizeException Extends RuntimeException

NoSuchMethodException Extends Exception

NullPointerException Extends RuntimeException

NumberFormatException Extends IllegalArgumentException

RuntimeException Extends Exception

SecurityException Extends RuntimeException

StringIndexOutOfBoundsException Extends IndexOutOfBoundsException

Constructors
StringIndexOutOfBoundsException( )
StringIndexOutOfBoundsException(int invalid_index)
StringIndexOutOfBoundsException(String)

java.net

MalformedURLException Extends java.lang.IOException

ProtocolException Extends java.lang.IOException

SocketException Extends java.lang.IOException

UnknownHostException Extends java.lang.IOException

UnknownServiceException Extends java.lang.IOException

java.util

EmptyStackException Extends java.lang.RuntimeException

Constructors
EmptyStackException( )

NoSuchElementException Extends java.lang.RuntimeException

Errors

Although errors and exceptions are both based on the java.lang.Throwable class, errors are designed to manage more critical runtime errors. Errors may be handled in a similar manner to exceptions. However, unless you clearly understand the problem and have devised a suitable way of resolving it, error handling is not something that shou