Appendix I

Java Language Reference


CONTENTS


From Sun Microsystems comes Java, the platform-independent programming language for creating executable content within Web pages. Based on C++, this is a full-fledged programming language and, as such, should not be taken lightly. When mastered, Java could prove as limitless as the programmer's imagination. Indeed, some have even gone so far as to predict that the computer software industry is seriously under threat because in a few years, all applications will be in the form of applets, downloaded as and when they are required.

Recent versions of Netscape (since version 2.0) have added the capability to support executable content, previously possible only by using the actual HotJava browser developed by Sun Microsystems. You can include live audio, animation, or applications in your web pages in the form of Java applets. The applets are pre-compiled and included in HTML documents.

Note
The information provided here describes only the necessary HTML elements that allow pre-compiled Java applets to be added to your HTML documents. It does not describe how to actually write Java applets. Such information is well beyond the scope of this appendix. For more information about writing Java code, see Teach Yourself Java in 21 Days (also from Sams.net Publishing); you can obtain a copy of the Java development kit at
http://java.sun.com/

This appendix provides an overview of how you can include Java applets in your pages, a Java language reference, and a desciption of the components of the Java Class Library.

<APPLET>: Including a Java Applet

Note
Internet Explorer supports the inclusion of Java applets using the <OBJECT> object-insertion mechanism.

To add an applet to an HTML page, you need to use the <APPLET> HTML element. For example,

<APPLET CODE="Applet.class" WIDTH=200 HEIGHT=150>
</APPLET>

This tells the viewer or browser to load the applet whose compiled code is in Applet.class (in the same directory as the current HTML document), and to set the initial size of the applet to 200 pixels wide and 150 pixels high. (The <APPLET> element supports standard image type attributes, explained later in this appendix.)

Here is a more complex example of an <APPLET> element:

<APPLET CODEBASE="http://java.sun.com/JDK-prebeta1/applets/NervousText"
CODE="NervousText.class" width=400 height=75 align=center >
<PARAM NAME="text" VALUE="This is the Applet Viewer.">
<BLOCKQUOTE>
<HR>
If you were using a Java-enabled browser, you would see dancing text
instead of this paragraph.
<HR>
</BLOCKQUOTE>
</APPLET>

This tells the viewer or browser to do the following:

The viewer/browser must also set the applet's "text" attribute (which customizes the text this applet displays) to be "This is the Applet Viewer." If the page is viewed by a browser that can't execute applets written in Java, the browser ignores the <APPLET> and <PARAM> elements, displaying the HTML between the <BLOCKQUOTE> and </BLOCKQUOTE> elements.

The complete syntax for the <APPLET> element example follows :

<APPLET
[CODEBASE = URL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]
     >
[<PARAM NAME = appletAttribute1 VALUE = value>]
[<PARAM NAME = appletAttribute2 VALUE = value>]
. . .
[alternateHTML]
</APPLET>

Each of the <APPLET> attributes is presented in alphabetical order and discussed briefly in the following sections.

ALIGN = alignment

This required attribute specifies the alignment of the applet. The possible values of this attribute are the same as those for the IMG element: left, right, top, texttop, middle, absmiddle, baseline, bottom, and absbottom.

ALT = alternateText

This optional attribute specifies any text that should be displayed if the browser understands the <APPLET> element but can't run applets written in the Java programming language.

CODE = appletFile

This required attribute gives the name of the file that contains the applet's compiled applet subclass. This file is relative to the base URL of the applet. It cannot be absolute.

CODEBASE = URL

This optional attribute specifies the base URL of the applet-the directory that contains the applet's code. If this attribute is not specified, the document's URL is used.

NAME = appletInstanceName

This optional attribute specifies a name for the applet instance, which makes it possible for applets on the same page to find (and communicate with) each other.

<PARAM NAME = appletAttribute1 VALUE = value>

This element is the only way to specify an applet-specific attribute. Applets access their attributes with the getParameter() method.

WIDTH = pixels HEIGHT = pixels

These required attributes give the initial width and height (in pixels) of the applet display area, not counting any windows or dialog boxes that the applet brings up.

VSPACE = pixels HSPACE = pixels

These option attributes specify the number of pixels above and below the applet (VSPACE) and on each side of the applet (HSPACE). They're treated the same way as the IMG element's VSPACE and HSPACE attributes.

<EMBED>: Embedding Objects

The <EMBED> element allows authors to embed objects directly into an HTML page.

The basic syntax follows:

<EMBED SRC="_URL_">

Here, "_URL_" represents the URL of the object that is to be embedded.

The <EMBED> element comes into its own when used to embed objects that will be handled by plugin modules. Plugin modules are supported by Netscape. These are essentially dynamic code modules that extend the capabilities of the browser by providing code that can handle data types for which Netscape has no internal handling functions. When Netscape encounters some data it cannot handle embedded into the HTML document (via use of the <EMBED> element), it searches for a plugin module that can handle that data type and load it, enabling the viewing/transforming (and any other modifications possible) of the object.

Netscape 3.0 and above ("Atlas") comes with three standard plugin modules. These handle inline sound, video, and VRML. Possible attributes are plugin-dependent, and you can consult the Netscape documentation of the plugin module you may want to use to include objects.

The Sound Plugin

The Sound plugin that Netscape installs can be used to embed .WAV, .MID, .AU, and .AIFF sound files. Where the sound file is embedded, a simple control panel is displayed, giving the user Play, Stop, Pause, and Volume controls. The display of the embedded control unit can take standard <IMG> attributes (ALIGN, HEIGHT, WIDTH, HSPACE, VSPACE, and BORDER).

The plugin also accepts the additional attributes (listed in the following sections) with this syntax:

<EMBED SRC="filename.ext">

Here, .ext is .MID, .WAV, and so on, specific to the sound plugin.

AUTOSTART="true"

By default, the controls unit for playing the embedded sound file is displayed and the sound file is played only when the user clicks the Play button. This overrides the wait and will play the sound file as soon as it is finished loading.

VOLUME="value"

This sets the initial volume for the playback of the sound file. It accepts a numerical value, which is a percentage of the total volume possible. The default for this is 50 percent. The volume can also be controlled by using the volume lever on the control unit displayed.

The Video Plugin

This plugin allows the embedding of .AVI video clips. The display of the embedded viewing window can accept standard <IMG> attributes (ALIGN, HEIGHT, WIDTH, HSPACE, VSPACE, and BORDER).

The video plugin accepts the following attributes (listed in the following sections) with this syntax:

<EMBED SRC="filename.avi">
AUTOSTART="true"

By default, the window for playing the embedded video clip is displayed and the video clip is only played when the user clicks the display window. This overrides the wait and will play the video clip as soon as it is finished loading.

LOOP="true"

This allows the video clip to play on a continuous loop once activated. By default (unless the AUTOSTART attribute is set), the video clip will begin to play after being clicked on. (A right mouse click will bring up a control menu.)

Live3D (The VRML Plugin)

This plugin allows the embedding of VRML worlds (.WRL) into an HTML document. The display of the embedded VRML world can accept standard <IMG> attributes (ALIGN, HEIGHT, WIDTH, HSPACE, VSPACE, and BORDER). For any embedded VRML world, various display and setup options are accessible via a control menu displayed by right-clicking on the embedded world. The basic syntax follows:

<EMBED SRC="filename.wrl">

Quick Reference

This section provides a quick reference for the Java language, by language feature.

Note
This is not a grammar or a technical overview of the language itself. It's a quick reference to be used after you already know the basics of how the language works. If you need a technical description of the language, your best bet is to visit the Java Web site (http://java.sun.com) and download the actual specification, which includes a full BNF grammar.

Language keywords and symbols are shown in a monospace font. Arguments and other parts to be substituted are in italic monospace.

Optional parts are indicated by brackets ([]) except in the array syntax section. If there are several options that are mutually exclusive, they are shown separated by pipes (|) like this:

[ public | private | protected ] type varname

Reserved Words

The following words are reserved for use by the Java language itself (some of them are reserved but not currently used). You cannot use these terms to refer to classes, methods, or variable names:

abstract double int static
boolean else interface super
break extends longswitch
byte final native synchronized
case finally newthis
catch float nullthrow
char forpackage throws
class gotoprivate transient
const ifprotected try
continue implements public void
default import return volatile
do instanceof short while

Comments

The following are valid comments in Java:

/* this is a multiline comment */
// this is a single-line comment
/** Javadoc comment */

Literals

number Type int
number[l | L] Type long
0xhex Hexadecimal integer
0Xhex Hexadecimal integer
0octal Octal integer
[ number ].number Type double
number[ f | f] Type float
number[ d | D] Type double
[ + | - ] number Signed
numberenumber Exponent
numberEnumber Exponent
'character' Single character
"characters" String
"" Empty string
\b Backspace
\t Tab
\n Line feed
\f Form feed
\r Carriage return
\" Double quote
\' Single quote
\\ Backslash
\uNNNN Unicode escape (NNNN is hexadecimal)
true Boolean
false Boolean

Variable Declaration

[ byte | short | int | long ] varname Integers (pick one type)
[ float | double ] varname Floats (pick one type)
char varname Characters
boolean varname Boolean
classname varname Class types
type varname, varname, varname Multiple variables

The following options are available only for class and instance variables. Any of these options can be used with a variable declaration:

[ static ] variableDeclaration Class variable
[ final ] variableDeclaration Constants
[ public | private | protected ] variableDeclaration Access control

Variable Assignment

variable = value Assignment
variable++ Postfix increment
++variable Prefix increment
variable-- Postfix decrement
--variable Prefix decrement
variable += value Add and assign
variable -= value Subtract and assign
variable *= value Multiply and assign
variable /= value Divide and assign
variable %= value Modulus and assign
variable &= value AND and assign
variable |= value OR and assign
variable ^= value XOR and assign
variable <<= value Left-shift and assign
variable >>= value Right-shift and assign
variable <<<= value Zero-fill right-shift and assign

Operators

arg + arg Addition
arg - arg Subtraction
arg * arg Multiplication
arg / arg Division
arg % arg Modulus
arg < arg Less than
arg > arg Greater than
arg <= arg Less than or equal to
arg >= arg Greater than or equal to
arg == arg Equal
arg != arg Not equal
arg && arg Logical AND
arg || arg Logical OR
! arg Logical NOT
arg & arg AND
arg | arg OR
arg ^ arg XOR
arg << arg Left-shift
arg >> arg Right-shift
arg >>> arg Zero-fill right-shift
~ arg Complement
(type)thing Casting
arg instanceof class Instance of
test ? trueOp : falseOp Tenary (if) operator

Objects

new class(); Create new instance
new class(arg,arg,arg...) New instance with parameters
object.variable Instance variable
object.classvar Class variable
Class.classvar Class variable
object.method() Instance method (no arguments)
object.method(arg,arg,arg...) Instance method
object.classmethod() Class method (no arguments)
object.classmethod(arg,arg,arg...) Class method
Class.classmethod() Class method (no arguments)
Class.classmethod(arg,arg,arg...) Class method

Arrays

Note
The brackets in this section are parts of the array creation or access statements. They do not denote optional parts as they do in other parts of this appendix.

Type varname[] Array variable
type[] varname Array variable
new type[numElements] New array object
array[index] Element access
array.length Length of array

Loops and Conditionals

if ( test) block Conditional
if ( test ) block Conditional with elseelse block
switch (test) {
    case value : statements
 
   case value : statements
 
   ...
    default : statement
}
switch (only with integer or char types)
for (initializer; test; change ) block for loop
while ( test ) block while loop
do block
while (test)
do loop
break [ label ]
continue [ label ]
break from loop or switch
continue loops
label: Labeled loops

Class Definitions

class classname block Simple class definition

Any of the following optional modifiers can be added to the class definition:

[ final ] class classname block No subclasses
[ abstract ] class classname block Cannot be instantiated
[ public ] class classname block Accessible outside package
class classname [ extends Superclass ] block Define superclass
class classname [ implements interfaces ] block Implement one or more interfaces

Method and Constructor Definitions

The basic method looks like this, where returnType is a type name, a class name, or void.

returnType methodName() block Basic method
returnType methodName(parameter, parameter, ...) block Method with parameters

Method parameters look like this:

type parameterName

Method variations can include any of the following optional keywords:

[ abstract ] returnType methodName() block Abstract method
[ static ] returnType methodName() block Class method
[ native ] returnType methodName() block Native method
[ final ] returnType methodName() block Final method
[ synchronized ] returnType methodName() block Thread lock before executing
[ public | private | protected ] returnType methodName() Access control

Constructors look like this:

classname() block Basic constructor
classname(parameter, parameter, parameter...) block Constructor with parameters
[ public [vb] private [vb] protected] classname() block Access control

In the method/constructor body, you can use these references and methods:

this Refers to current object
super Refers to superclass
super.methodName() Call a superclass's method
this(...) Calls a class's constructor
super(...) Calls a superclass's constructor
return [ value ] Returns a value

Packages, Interfaces, and Importing

import package.className Imports a specific class name
import package.* Imports all classes in a package
package packagename Classes in this file belong to this package

interface interfaceName [ extends anotherInterface ] block
[ public ] interface interfaceName block
[ abstract ] interface interfaceName block

Exceptions and Guarding

synchronized ( object ) block Waits for lock on object
try block
catch ( exception ) block
[ finally block ]
Guarded statements
Executed if exception is thrown
Always executed
try block
[ catch ( exception ) block ]
finally block
Same as previous example (can use optional catch or finally, but not both)

The Java Class Library

This rest of this appendix provides a general overview of the classes available in the standard Java packages (the classes that are guaranteed to be available in any Java implementation). This information is intended for general reference; for more specific information about each class (its inheritance, variables, and methods), as well as the various exceptions for each package, see the API documentation from Sun at http://java.sun.com.

java.lang

The java.lang package contains the classes and interfaces that make up the core Java language.

Interfaces

Cloneable Interface indicating that an object may be copied or cloned
Runnable Methods for runnable objects (for example, applets that include threads)

Classes

Boolean Object wrapper for Boolean values
Character Object wrapper for char values
Class Runtime representations of classes
ClassLoader Abstract behavior for handling loading of classes
Compiler System class that gives access to the Java compiler
Double Object wrapper for double values
Float Object wrapper for float values
Integer Object wrapper for int values
Long Object wrapper for long values
Math Utility class for math operations
Number Superclass of all number classes (Integer, Float, and so on)
Object Generic Object class, at top of inheritance hierarchy
ProcessNT> Processes such as those spawned using methods in the System class
Runtime The Java runtime
SecurityManager Abstract behavior for implementing security policies
String Character strings
StringBuffer Mutable strings
System System-based behavior, provided in a platform-independent way
Thread Methods for managing threads and classes that run in threads
ThreadDeath Class of object thrown when a thread is asynchronously
terminated  
ThreadGroup A group of threads
Throwable A superclass for errors and exceptions
UNIXProcess UNIX-specific processes
Win32Process Windows-specific processes

java.util

The java.util package contains various utility classes and interfaces, including random numbers, system properties, and other useful utility classes.

Interfaces

Enumeration Methods for enumerating sets of values
">Observer Methods for enabling classes to be observable by Observable objects

Classes

BitSet A set of bits
Date The current system date, as well as methods for generating and parsing dates
Dictionary An abstract class that maps between keys and values (superclass of HashTable)
Hashtable A hash table
Observable An abstract class for observable objects
Properties A hashtable that contains behavior for setting and retrieving persistent properties of the system or of a class
Random Utilities for generating random numbers
Stack A stack (a last-in-first-out queue)
StringTokenizer Utilities for splitting strings into individual "tokens"
Vector A growable array, similar to a linked list

java.io

The java.io package provides input and output classes and interfaces for streams and files.

Interfaces

DataInput Methods for reading machine-independent input streams
DataOutputMethods for writing machine-independent output streams
FilenameFilter Methods for filtering file names

Classes

BufferedInputStream A buffered input stream
BufferedOutputStream A buffered output stream
ByteArrayInputStream A byte array buffer for an input stream
ByteArrayOutputStream A byte array buffer for an output stream
DataInputStream Enables you to read primitive Java types (ints, chars, booleans, and so on) from a stream in a machine-independent way
DataOutputStream Enables you to write primitive Java data types (ints, chars, booleans, and so on) to a stream in a machine-independent way
File Represents a file on the host's file system
FileDescriptor Holds onto the UNIX-like file descriptor of a file or socket
FileInputStream An input stream from a file, constructed using a file name or descriptor
FileOutputStream An output stream to a file, constructed using a file name or descriptor
FilterInputStream An abstract class that provides a filter for input streams (and for adding stream functionality such as buffers)
FilterOutputStream An abstract class that provides a filter for output streams (and for adding stream functionality such as buffers)
InputStream An abstract class presenting an input stream of bytes; the parent of all input streams in this package
LineNumberInputStream An input stream that keeps track of line numbers
OutputStream An abstract class representing an output stream of bytes; the parent of all output streams in this package
PipedInputStream A piped input stream, which should be connected to a PipedOutputStream to be useful
PipedOutputStream A piped output stream, which should be connected to a PipedInputStream to be useful
PrintStream An output stream for printing (used by System.out.printin(...))
PushbackInputStream An input stream with a 1-byte push-back buffer
RandomAccessFile A random-access input and output file that can be constructed from file names, descriptors, or objects
SequenceInputStream Converts a sequence of input streams into a single input steam
StreamTokenizer Converts an input stream into a series of individual tokens
StringBufferInputStream Uses a string buffer as an input stream to a String object

java.net

The java.net package contains classes and interfaces for performing network operations, such as sockets and URLs.

Interfaces

ContentHandlerFactory Methods for creating ContentHandler objects
SocketImplFactory Methods for creating socket implementations (instance of the SocketImpl class)
URLStreamHandlerFactory Methods for creating URLStreamHandler objects

Classes

ContentHandler A class that can read data from a URL connection and construct the appropriate local object, based on MIME types
DatagramPacket A datagram packet (UDP)
DatagramSocket A datagram socket
InetAddress An object representation of an Internet host (host name, IP address)
ServerSocket An abstract server-side socket
Socket An abstract socket
SocketImpl An abstract class for specific socket implementations
URL An object representation of a URL
URLConnection A socket that can handle various Web-based protocols (http, ftp, and so on)
URLEncoder Turns strings into x-www-form-urlencoded format
URLStreamHandler Abstract class for managing streams to object references by URLs

java.awt

The java.awt package contains the classes and interfaces that make up the Abstract Windowing Toolkit.

Interfaces

LayoutManager Methods for laying out containers
MenuContainer Methods for menu-related containers

Classes

BorderLayout A layout manager for arranging items in border formation

Button A UI pushbutton

Canvas A canvas for drawing and performing other graphics
operations 
CardLayoutA layout manager for hypercard-like metaphors
CheckboxA check box
CheckboxGroupA group of exclusive check boxes (radio buttons)
CheckboxMenuItemA toggle menu item
ChoiceA pop-up menu of choices
ColorAn abstract representation of a color
ComponentThe generic class for all UI components
ContainerA component that can hold other components or containers
DialogA window for brief interactions with users
DimensionAn object representing width and height
EventA class representing events called by the system or generated by user input
FileDialogA dialog box for getting file names from the local file system
FlowLayoutA layout manager that lays out objects from left to right in rows
FontAn abstract representation of a font
FontMetricsInformation about a specific font's character shapes and height and width information
FrameA top-level window with a title
GraphicsA representation of a graphics context and methods to draw and paint shapes and objects
GridBagConstraintsConstraints for components laid out using GridBagLayout
GridBagLayoutA layout manager that aligns components horizontally and vertically based on their values from GridBagConstraints
GridLayoutA layout manager with rows and columns; elements are added to each cell in the grid
ImageAn abstract representation of a bitmap image
InsetsDistances from the outer border of the window to lay out components
LabelA text label for UI components
ListA scrolling list
MediaTrackerA way to keep track of the status of media objects being loaded over the Net
MenuA menu that can contain menu items and is a container on a menubar
MenuBarA menubar (container for menus)
MenuComponentThe superclass of all menu elements
MenuItemAn individual menu item
PanelA container that is displayed
PointAn object representing a point (x and y coordinates)
PolygonAn object representing a set of points
RectangleAn object representing a rectangle (x and y coordinates for the top corner, plus width and height)
ScrollbarA UI scrollbar object
TextAreaA multiline, scrollable, editable text field
TextComponentThe superclass of all editable text components
TextFieldA fixed-size editable text field
ToolkitBinds the abstract AWT classes to a platform-specific toolkit implementation
Window A top-level window, and the superclass of the Frame and Dialog classes

java.awt.image

The java.awt.image package is a subpackage of the AWT that provides classes for managing bitmap images.

Interfaces

ImageConsumer Methods for receiving image data filters through an ImageProducer
ImageObserverMethods to keep track of the loading and construction of an image
ImageProducer Methods for producing image data received by an ImageConsumer

Classes

ColorModel A class for managing color information for images
CropImageFilterA filter for cropping images to a particular size
DirectColorModelA specific color model for managing and translating pixel color values
FilteredImageSourceAn ImageProducer that takes an image and an ImageFilter object and produces an image for an ImageConsumer
ImageFilterA filter that takes image data from an ImageProducer, modifies it in some way, and hands it off to an ImageConsumer
IndexColorModelA specific color model for managing and translating color values in a fixed-color map
MemoryImageSourceAn image producer that gets its image from memory; used after constructing an image by hand
PixelGrabberAn ImageConsumer that retrieves a subset of the pixels in an image
RGBImageFilter A filter for modifying the RGB values of pixels in RGB images

java.awt.peer

The java.awt.peer package is a subpackage of AWT that contains abstract classes to link AWT to the code to display platform-specific interface elements (for example, Motif, Macintosh, and Windows 95).

Interfaces

ButtonPeer Peer for the Button class
CanvasPeerPeer for the Canvas class
CheckboxMenuItemPeerPeer for the CheckboxMenuItem class
CheckboxPeerPeer for the Checkbox class
ChoicePeerPeer for the Choice class
ComponentPeerPeer for the Component class
ContainerPeerPeer for the Container class
DialogPeer Peer for the Dialog class

java.applet

The java.applet package provides applet-specific behavior.

Interfaces

AppletContext Methods to refer to the applet's context
AppletStubMethods for implementing applet viewers
AudioClip Methods for playing audio files

Classes

Applet The base applet class