Previous Page TOC Next Page


— Appendix G —
Java Language Reference

From Sun Microsystems comes Java, the platform-independent programming language for creating executable content within Web pages. Based on C++, this is a fully 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 using the actual HotJava browser developed by Sun MicroSystems. You can include live audio, animation, or applications to your Web pages in the form of Java applets. The applets are pre-compiled and included in HTML documents.


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); to obtain a copy of the Java development kit:

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


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 is as 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 are 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, 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, then 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 dialogs 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 is as 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 plug-in modules. Plug-in 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 will search for a plug-in module that can handle that data type and load it, enabling the viewing/transforming (and any other modifications possible) of the object.

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

The Sound Plug-in

The Sound plug-in 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 plug-in 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 plug-in.

AUTOSTART="true"

By default, the controls unit for playing the embedded sound file is displayed and the sound file is only played 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 Plug-in

This plug-in 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 plug-in 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 over-rides 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 Plug-in)

This plug-in 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 controls menu displayed by right-clicking on the embedded world. The basic syntax is as follows:

<EMBED SRC="filename.wrl">

Quick Reference

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


This is not a grammar, nor is it 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 for 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

long

switch

byte

final

native

synchronized

case

finally

new

this

catch

float

null

throw

char

for

package

throws

class

goto

private

transient

const

if

protected

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

Hex integer

0Xhex

Hex 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 hex)

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 args)

object.method(arg,arg,arg...)

Instance method

object.classmethod()

Class method (no args)

object.classmethod(arg,arg,arg...)

Class method

Class.classmethod()

Class method (no args)

Class.classmethod(arg,arg,arg...)

Class method

Arrays


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 else

else block




switch (test) {

switch (only with integer or char types)

case value : statements

case value : statements

...


default : statement


}




for (initializer; test; change ) block

for loop



while ( test ) block

while loop



do block

do loop

while (test)




break [ label ]

break from loop or switch

continue [ label ]

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 class's constructor

super(...)

Calls superclass's constructor

return [ value ]

Returns a value

Packages, Interfaces, and Importing

import package.className

Imports specific class name

import package.*

Imports all classes in 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

Guarded statements

catch ( exception ) block

Executed if exception is thrown

[ finally block ]

Always executed



try block

Same as previous example (can

[ catch ( exception ) block ]

use optional catch or finally,

finally block

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 (that is, 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

Run-time 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

Process

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

DataOutput

Methods for writing machine-independent output streams

FilenameFilter

Methods for filtering filenames

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 filename or descriptor

FileOutputStream

An output stream to a file, constructed using a filename or descriptor

FilterInputStream

Abstract class which provides a filter for input streams (and for adding stream functionality such as buffers)

FilterOutputStream

Abstract class which 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 filenames, 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

Use 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

CardLayout

A layout manager for HyperCard-like metaphors

Checkbox

A checkbox

CheckboxGroup

A group of exclusive checkboxes (radio buttons)

CheckboxMenuItem

A toggle menu item

Choice

A popup menu of choices

Color

An abstract representation of a color

Component

The generic class for all UI components

Container

A component that can hold other components or containers

Dialog

A window for brief interactions with users

Dimension

An object representing width and height

Event

An class representing events called by the system or generated by user input

FileDialog

A dialog for getting file names from the local file system

FlowLayout

A layout manager that lays out objects from left to right in rows

Font

An abstract representation of a font

FontMetrics

Information about a specific font's character shapes and height and width information

Frame

A top-level window with a title

Graphics

A representation of a graphics context and methods to draw and paint shapes and objects

GridBagConstraints

Constraints for components laid out using GridBagLayout

GridBagLayout

A layout manager that aligns components horizontally and vertically based on their values from GridBagConstraints

GridLayout

A layout manager with rows and columns; elements are added to each cell in the grid

Image

An abstract representation of a bitmap image

Insets

Distances from the outer border of the window to lay out components

Label

A text label for UI components

List

A scrolling list

MediaTracker

A way to keep track of the status of media objects being loaded over the Net

Menu

A menu, which can contain menu items and is a container on a menubar

MenuBar

A menubar (container for menus)

MenuComponent

The superclass of all menu elements

MenuItem

An individual menu item

Panel

A container that is displayed

Point

An object representing a point (x and y coordinates)

Polygon

An object representing a set of points

Rectangle

An object representing a rectangle (x and y coordinates for the top corner, plus width and height)

Scrollbar

A UI scrollbar object

TextArea

A multiline, scrollable, editable text field

TextComponent

The superclass of all editable text components

TextField

A fixed-size editable text field

Toolkit

Binds 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

ImageObserver

Methods 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

CropImageFilter

A filter for cropping images to a particular size

DirectColorModel

A specific color model for managing and translating pixel color values

FilteredImageSource

An ImageProducer that takes an image and an ImageFilter object and produces an image for an ImageConsumer

ImageFilter

A filter that takes image data from an ImageProducer, modifies it in some way, and hands it off to a ImageConsumer

IndexColorModel

A specific color model for managing and translating color values in a fixed-color map

MemoryImageSource

An image producer that gets its image from memory; used after constructing an image by hand

PixelGrabber

An ImageConsumer that retrieves a subset of the pixels in

an image

RGBImageFilter

A filter for modifying the RBG 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 interfaces elements (for example, Motif, Macintosh, Windows 95).

Interfaces

ButtonPeer

Peer for the Button class

CanvasPeer

Peer for the Canvas class

CheckboxMenuItemPeer

Peer for the CheckboxMenuItem class

CheckboxPeer

Peer for the Checkbox class

ChoicePeer

Peer for the Choice class

ComponentPeer

Peer for the Component class

ContainerPeer

Peer 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

AppletStub

Methods for implementing applet viewers

AudioClip

Methods for playing audio files

Classes

Applet

The base applet class

Previous Page TOC Next Page