Appendix A
Answers to Review Questions
CONTENTS
- Probably the three most important reasons that Java is so
suitable for Internet applications are the language's robustness,
simplicity, and, most importantly, its security features.
- A Java applet is a small program that is embedded in an HTML
document and is run when the document is loaded. A Java standalone
application doesn't need to be embedded in an HTML document and
can be run just like any other application.
- Java applets are compiled into byte-code files that can be
executed by any computer that has a Java interpreter.
- Applets are handled in an HTML document similarly to elements
like images. The applet is referenced in the HTML document, which
causes the HTML document to load and run the applet.
- Java is platform-independent so that it can run on any system.
Java is also multithreaded, which means it can handle multiple
tasks concurrently and run fast.
- Use the Appletviewer tool included with the JDK.
- The required attributes are code, width,
and height.
- The codebase attribute specifies the location of
an applet's code (the .CLASS file). The given folder is relative
to the folder of the HTML document that contains the reference
to the applet.
- Other optional attributes include alt, align,
name, hspace, and vspace.
- Applet parameters enable a user to configure an applet to
fit his specific needs.
- You can provide alternate content for non-Java browsers. You
do this by placing standard HTML script commands for the alternate
content right before the ending </applet> tag.
- A local applet is located on your computer system.
- A remote applet is located on another computer system and
must be downloaded onto your computer before it can be run.
- The client is the computer that requests information (in this
case, an applet) from another computer. The computer that supplies
the information is the server.
- Once applets can flow both from and to a remote computer,
the client/server relationship will become less important. This
is because computers will keep switching from being a client and
a server.
- The Java interpreter validates every applet before the applet
is run. This prevents applets that have been modified (maybe by
having a virus attached) from affecting the destination system.
The validation process also ensures that an applet cannot crash
the system.
- When you use top-down programming, you divide a program up
such that the detail goes from general to specific as you work
your way down the program.
- Top-down programming enables you to separate the general tasks
that must be completed by a program from the details that implement
those tasks, making a program easier to understand and organize.
- OOP offers another organizational level to the programmer.
Not only can the programmer divide tasks up into logical chunks
in top-down, structured fashion, but he can also separate logical
elements of the program into objects.
- The two main elements of a class are data fields and the methods
that operate on the data fields.
- A class is like a template or blueprint for an object. An
object is an instance of the class.
- The three main OOP concepts are encapsulation, inheritance,
and polymorphism.
- Encapsulation is the act of enclosing both the data and the
functions that act on the data within the object. Inheritance
is the ability of a new object (a derived object) to inherit data
and functions from a base object. Polymorphism is the ability
of a derived object to implement a function of the base class
in a different way.
- A constant is a value that can't be changed during a program's
execution. Constants have symbolic names like PI or NUMBEROFITEMS.
- A variable is a value that can be changed as much as needed
during a program's execution. Like constants, variables have symbolic
names. Examples of variable names are count and area_of_circle.
- Constants and variables replace hard-to-understand values
with English-like names. Moreover, variables enable you to name
a value that must change many times during program execution.
- Java's eight data types are byte, short,
int, long, float, double,
char, and boolean.
- Variable scope determines where in a program a variable can
be accessed. A variable goes into scope at the beginning of the
program block in which the variable is declared and goes out of
scope at the end of the block.
- Graphical text is text that must be drawn on the screen just
like other shapes such as circles and squares, rather than printed
using a built-in character set as is done under MS-DOS.
- In a proportional font, each letter takes up only the amount
of space it needs, whereas every letter in a non-proportional
font takes up exactly the same amount of space.
- Arguments are values that are sent to a method when the method
is called.
- The three arguments for the drawString() method are
the text string to display, and the column and row at which to
display the text.
- The paint() method draws whatever needs to be displayed
in the applet's display area. Java calls paint() whenever
the applet needs to be redrawn.
- One way to get user input is to add a TextField control
to your applet.
- Java calls the init() method almost immediately after
an applet starts up in order to enable you to initialize objects
needed by the applet.
- Java calls the action() method whenever the user
does something with the applet's controls. For example, when the
user types text into a TextField control and presses
Enter, Java calls action() so that the applet can respond
to the user's input.
- To convert a numerical value to a string, you call the String
class's valueOf() method.
- The addition, subtraction, multiplication, and division operators
are +, Ð, *, and /, respectively.
- 5*3 equals 15.
- 3 Ð 2 + 5 + 6 Ð1 equals 11.
- The ++ operator increments the variable, so num ends
up equal to 13.
- 12 % 5 equals 2.
- If num equals 25, the expression num += 5
makes num equal to 30.
- You set the text is a TextField object by calling
TextField's setText() method.
- 12 + 3 * 6 / 2 equals 21.
- You can change 3 / 5 from integer to floating-point
division by changing one or both of the numbers to a floating-point
value, like this: 3f / 5f.
- You cast the result of 56 Ð 34.56f to integer
like this: (int)(56 Ð 34.56f).
- You convert digits in a string to an integer by calling the
Integer class's parseInt() method.
- (12 Ð 8) * 10 / 2 * 2 equals 40.
- An expression is a line of program code that can be reduced
to a value or that assigns a value to a variable or constant.
- The three types of expressions are numerical, assignment,
and logical.
- The expression (3 < 5) equals true.
- The expression (3 < 5) && (5 == 4 + 1)
equals true.
- Expressions are recursive because they can contain other smaller
expressions, which in turn may contain other expressions.
- The six comparison operators are == (equals), !=
(not equal), < (less than), > (greater
than), <= (less than or equals), and >=
(greater than or equals).
- The four logical operators are ! (NOT), &&
(AND), || (OR), and ^ (exclusive OR).
- The result of the expression (3 < 5) || (6 == 5) ||
(3 != 3) is true.
- The result of the expression (5 != 10) && ((3
== 2 + 1) || (4 < 2 + 5)) is true.
- The result of the expression !(5 == 2 + 3) &&
!(5 + 2 != 7 - 5) is false.
- Program flow is the order in which program statements are
executed.
- Conditional branching occurs when a program branches to a
new section based on the value of some data. Unconditional branching
is when a computer instruction causes the program to branch regardless
of any conditions.
- Two ways to control program flow are if and switch
statements.
- No. The second line will execute only when choice
equals 3.
- You can write an if statement without opening and
closing braces when only one program line will execute if the
condition evaluates to true.
- There is no difference between a logical and a Boolean expression.
They are both expressions that evaluate to true or false.
- The program skips over both the if and the else
if.
- The if and switch statements are similar
in that they both enable the computer to choose a path of execution
based on the value of a control variable. They are different in
that a switch statement is more appropriate for situations
in which there are many possible outcomes.
- The variable num ends up with the value 3. If your
answer was 2, you didn't notice that the second case
has no break statement, causing program execution to
drop through to the third case.
- You should use a loop when your program must perform some
sort of repetitive task.
- The body of the loop comprises the program lines that are
executed each time the loop's conditional expression is true.
- When the conditional expression evaluates to false,
the loop ends.
- There is no guarantee on how many times a while loop
will execute. It could be any number of times from 0 on up. A
do-while loop, on the other hand, always executes at
least once.
- You must properly initialize the loop control variable because
the loop's conditional expression relies on the value of the variable
to determine how many times to loop.
- An infinite loop occurs when a loop's conditional expression
can never result in false, causing the loop to repeat
endlessly.
- Both the while and do-while loops can be
used to perform repetitive tasks in a program. However, the while
loop may execute any number of times, including 0, whereas a do-while
loop always executes at least once. This is because a do-while
loop's conditional expression is at the end of the loop, whereas
a while loop's conditional expression is at the beginning
of the loop.
- The loop will execute six times, and count will be
equal to 16 at the end of the loop.
- You should use a for loop when you have a repetitive
task that must be performed a specific number of times.
- The three parts of a for loop are the initialization,
condition, and increment sections.
- A for loop stops looping when the condition section
becomes false.
- A for loop can count backward by decrementing the
control variable in the increment section, rather than incrementing
it.
- A for loop can count by tens by adding 10 to the
control variable in the increment section.
- It's possible to create an infinite loop with a for
loop, but it's unlikely because the loop control variable is handled
by the loop itself.
- The loop will execute five times, and x will be equal
to 13 at the end of the loop.
- Top-down programming means organizing source code into levels
that go from general functions to more detailed functions the
further down the hierarchy you go.
- Functions make top-down programming possible by enabling you
to organize source code into well-defined tasks.
- All functions have a return type, but the return type of void
means that the function returns no actual value.
- Arguments are values that you pass to a function when you
call it. The receiving function can then access the values almost
as if they were local to the function.
- Defining a function is the act of writing the function's source
code.
- You return a value from a function by using the keyword return
followed by the value to be returned. The returned value must
be the same type as the function's defined return type.
- The arguments in the function call must be in the same order
and be of the same type as the arguments given in the function's
definition.
- The best way to break source code up into functions is to
locate the groups of commands that perform a specific task and
then replace those lines with a function call. The lines that
are replaced become the body of the new function.
- An array is a data structure that enables you to store many
related values under one variable name.
- You can access the values of an array using loops, which greatly
reduces the amount of source code needed to handle large numbers
of related values.
- An array subscript identifies a specific element of an array.
The subscript is a number or variable enclosed in square brackets.
A subscript and an index are exactly the same thing.
- A two-dimensional array can store values in a table, with
a specific number of columns and rows.
- The largest subscript you can use with a fifty-element array
is 49.
- If you try to access a nonexistent array element, Java generates
an exception.
- A for loop is perfect for array access because you
can use the loop control variable as an array subscript.
- To initialize a two-dimensional array with for loops,
you'd use nested loops. The outer loop counts through the columns
and the inner loop counts through the rows.
- A class is a template from which you create an object. A class
usually contains data fields and methods.
- A class provides an additional level of program abstraction
that enables you to organize data fields, and the methods that
interact with those data fields, within a single structure.
- The three parts of a simple, empty class are the keyword class,
followed by the name of the class and the braces that mark off
the body of the class.
- The two program elements that you must add to the empty class
in order to create a complete class are data fields and methods.
- To create an object of a class, you use the new operator
followed by a call to the class's constructor.
- To use a class that's defined in a different file, you place
the import keyword, followed by the class's name, at
the top of the file that needs access to the class. You must also
be sure that the compiler can find the class, usually by placing
the class files all in the same directory.
- Using inheritance, a new class (subclass) derived from a base
class (superclass) inherits the data fields and methods defined
in the base class. The programmer then only needs to add whatever
additional functionality is required by the new class.
- A subclass is a class that's been derived from another class
using the extends keyword. A superclass is the class
from which a subclass is derived. That is, the terms subclass
and base class are equivalent.
- You create a subclass by using the extends keyword
like this:
class SubClass extends SuperClass
{
}
- To override a method, you provide, in your subclass, a method
with exactly the same name, return type, and arguments as the
method of the superclass you want to override. Then, Java will
call your class's version of the method rather than the superclass's
version.
- All applets must be derived from Java's Applet class.
- Applet classes must be public so that the system can run the
applet. If you fail to declare an applet as public, it
will compile fine, but it will not run.
- The five life-cycle stages of an applet are initialization,
start, paint, stop, and destroy.
- The paint cycle isn't an "official" stage in the
applet's life cycle. It isn't, in fact, even defined within the
Applet class. Instead, the paint() method is
inherited from Java's Component class.
- The initialize cycle occurs only once in the applet's life
cycle (when the applet is loaded and prepared to run), whereas
start can occur numerous times (after initialization or whenever
the applet is restarted).
- The init(), start(), stop(), and
destroy() methods as they are implemented in the Applet
class do absolutely nothing. They are only placeholders that you
can override in your applet class. The same is true of the paint()
method.
- The area of an applet in which you can draw is called the
canvas.
- The origin of Java's graphical coordinate system is in the
upper left corner with values of X increasing to the right and
values of Y increasing downwards.
- The drawRect() method draws a hollow rectangle, whereas
the fillRect() method draws a filled (solid) rectangle.
- The four arguments for the drawRect() method are
the X,Y coordinates of the rectangle's upper left corner and the
width and height of the rectangle.
- The first four arguments for both drawRect() and
drawRoundRect() are exactly the same, being the X,Y coordinates,
width, and height of the rectangle. The drawRoundRect()
method, however, has two additional arguments that are the width
and height of a rectangle that determines the size of the rounded
corners.
- The drawPolygon() method uses arrays to store its
coordinates because a polygon can have any number of sides, which
means that the method call must have a way to pass differing numbers
of points. The arrays enable you to define as many sides as you
need while keeping the method's argument count consistent.
- The six arguments required by the drawArc() method
are the X,Y coordinates, width, and height of the bounding rectangle,
as well as the starting drawing angle and the number of degrees
around to draw.
- The Polygon class provides several methods that enable
you to manipulate a polygon in various ways.
- To get a reference to the currently active font object, you
call the Graphics class's getFont() method.
- To get a font's name, you can call the Font class's
getName() method.
- To get a font's height, you can call the Font class's
getHeight() method.
- You need to know a font's height so you can properly space
lines of text.
- You get a reference to a FontMetrics object by calling
the Graphics class's getFontMetrics() method.
The Font object for which you want the metrics is the
method's single argument.
- Use a FontMetrics object when you want to know more
detailed information about a font. The Font class offers
only general information about a font.
- You can determine the width of a text string by calling the
FontMetrics class's stringWidth(). The method's
single argument is the string to measure.
- A point is a unit of measurement of a font's height. A point
equals 1/72 of an inch.
- Leading is the amount of white space between lines of text.
Ascent is the height of a character, from the baseline to the
top of the character. Descent is the size of the area that accommodates
the descending portions of letters, such as the tail on a lowercase
"g."
- A font's height is the sum of the font's leading, ascent,
and descent.
- Use the new operator to call the Font class's
constructor. The constructor's three arguments are the font name,
style, and size. Styles you can use are any combination of Font.PLAIN,
Font.BOLD, and Font.ITALIC.
- If the font you request is not available, Java substitutes
a default font. This is one reason it's so important to get a
font's size after you create the font.
- The two arguments required by the Label class's constructor
are the text for the label and the label's alignment value.
- When an applet containing labels is resized, the labels automatically
reposition themselves as appropriate.
- After creating controls, you add the controls to the applet
with the add() method.
- The single argument needed by the Button class's
constructor is the text label for the button.
- The values for setting a label's alignment are represented
by the Label class's Label.LEFT, Label.CENTER,
and Label.RIGHT fields.
- The Label class provides methods for setting the
label's text and alignment.
- You can change a button's text label by calling the Button
class's setLabel() method.
- For a button click, the action() method receives
a reference to the button object and the selected button's text
label.
- You can determine which button was selected by examining the
text label passed as the action() method's second parameter.
- Nothing happens when a user clicks a label object, because
label objects do not generate events.
- The three arguments required by the Checkbox class's
constructor are the text for the label, a reference to the CheckboxGroup
object (or null), and checkbox's state (true
or false).
- Checkboxes that are set to exclusive mode are also called
radio buttons.
- The two arguments needed by the TextField class's
constructor are the default text and the width (in characters)
of the control.
- To change the state of a checkbox control call the Checkbox
class's setState() method.
- When checkboxes are in nonexclusive mode, the user can select
as many checkboxes at a time as he likes. In exclusive mode, the
user can select only one checkbox at a time.
- To create a group of checkbox controls (in exclusive mode),
you must first create an object of the CheckboxGroup
class.
- You use echo characters whenever the information being entered
into a textfield control should not be readable on the screen,
such as when the user is entering a password.
- You select an echo character for a textfield control by calling
the TextField class's setEchoCharacter() method.
- To determine which checkbox generated an event, you cast the
first parameter sent to the action() method to an object
of the Checkbox class. You can then call the checkbox
object's getLabel() method to get the checkbox's label.
- The Choice class's constructor accepts no arguments.
- You add items to a choice menu by calling the Choice
class's addItem() method.
- The two arguments needed by the List class's constructor
are the number of visible rows in the box and a boolean value
indicating whether the control will accept multiple selections.
- You add items to a list by calling the List class's
addItem() method.
- You would use a TextArea control when you need to
display, and enable the user to edit, more than one line of text.
The TextField control can display only a single line.
- To determine the selected item in a choice menu, examine the
second parameter of the event() method. The selected
item's text string gets passed to event() as that parameter.
- You create a multiple-selection list exactly the same way
you create a single-selection list, except that the value of the
constructor's second argument should be true rather than
false.
- You retrieve the selected item from a list by calling the
List class's getSelectedItem() method. If you
want the index of the selected item, call getSelectedIndex().
- To create a string containing multiple lines of text, add
each line of the text to the string using the concatenation operator
(+). Make sure each line of text ends with the newline character
(\n).
- To retrieve multiple selections from a scrolling list, call
the List class's getSelectedItems() method.
This method returns a string array containing the selected items.
- Yes. You can delete items from a list by calling the List
class's deleteItem() or deleteItems() methods.
- The Scrollbar constructor's five arguments are the
scrollbar's orientation, value, page size, minimum value, and
maximum value.
- A canvas is a blank component on which you can draw graphics.
- The Canvas class's constructor requires no arguments.
- Use a page size of zero when you want the scroll box to be
centered on the selected value and when you want the user to be
able to select a value from anywhere within the entire range.
- The easiest way to respond to a scrollbar change is to override
the handleEvent() method. In the method, watch for a
component target of Scrollbar. When you receive an event
message from the scrollbar, call the scrollbar's getValue()
method to determine its setting.
- A scrollbar can generate SCROLL_ABSOLUTE, SCROLL_LINE_DOWN,
SCROLL_LINE_UP, SCROLL_PAGE_DOWN, and SCROLL_PAGE_UP
event messages.
- To create a custom canvas component, derive a new class from
Java's Canvas class.
- To draw a canvas's display, override the class's paint()
method.
- You can use multiple panels in order to organize sets of controls
in a display. Each panel can have its own layout manager.
- Java's five layout managers are FlowLayout, GridLayout,
BorderLayout, CardLayout, and GridBagLayout.
- The default layout manager is FlowLayout.
- The FlowLayout manager positions components one after
the other in rows. When a component won't fit on the current row,
the layout manager starts the next row.
- The GridLayout constructor's four arguments are the
number of columns and rows in the grid, and the horizontal and
vertical spacing of the cells in the grid.
- The component positions you can use with the BorderLayout
manager are North, South, East, West, and Center.
- To add a component to an applet using the BorderLayout
manager, you call a special version of the add() method
that has the position string (North, South, etc.) and a reference
to the component as arguments.
- You can use CardLayout to simulate property sheets
because the layout manager enables you to create "cards"
that contains groups of controls. Each card can be displayed separately.
- When using the CardLayout manager, you can switch
from one card to another by calling the manager's first(),
next(), last(), previous(), or show()
method.
- The constraints determine where in the layout a component
will be placed.
- GridBagConstraints.fill determines whether components
will stretch vertically or horizontally to fill their cells.
- To add a component when using the GridBagLayout manager,
you first initialize and set the constraints. You then call add()
as you normally would.
- To create a frame window, call the Frame class's
constructor with the title of the window as the constructor's
single argument.
- To display a frame window, call the window's show()
method.
- To determine whether a frame window is visible, call the isShowing()
method, which returns true if the window is currently
visible and false otherwise.
- You use MenuItem objects for regular items in a menu,
whereas you use CheckboxMenuItem objects for items that
can be checkmarked.
- To create a custom frame-window class, you extend the Frame
class, which itself extends the Window class.
- To initialize a custom frame window's superclass (Frame),
you call the super() method with the window's title string
as the method's single argument.
- You can draw in a frame window in exactly the same way you
can draw in an applet's display area, by overriding the class's
paint() method.
- The six steps for creating a menu bar are create the MenuBar
object, call setMenuBar(), create Menu objects,
add the Menu objects to the MenuBar object,
create MenuItem objects, and add the MenuItem
objects to the menus.
- To add components to a frame window, first create and set
a layout manager for the window. Then create and add the components
to the window as appropriate for the type of layout manager you
chose.
- You respond to selected menu items by watching for their strings
in the action() method, which you must override in the
window's class.
- A menu separator is just a normal MenuItem object
that has a single hyphen as its string.
- The Dialog constructor's three arguments are a reference
to the dialog box's parent frame window, the dialog's title, and
a boolean value indicating whether the dialog is modal.
- You can display or hide a dialog box by calling the class's
show() or hide() methods.
- A dialog box must have a frame window as a parent window.
The first argument in Dialog's constructor is, in fact,
a reference to this frame window.
- Every dialog box should have at least an OK button that enables
the user to dismiss the dialog box.
- Modal dialog boxes must be dismissed before the user can continue
with the program. Modeless dialog boxes do not need to be dismissed
in order to continue using the program.
- In order to add components to a dialog box, you must first
create and set a layout manager for the dialog. Then, you create
the controls you need and call the dialog box's add()
method to add the controls to the layout.
- The most commonly used mouse event is MOUSE_DOWN,
which indicates that the user pressed his mouse button.
- An applet receives more MOUSE_MOVE event messages
than any other type of mouse event. An applet receives hundreds
of these messages as the user moves his mouse over the applet.
- The six mouse event messages are MOUSE_DOWN, MOUSE_UP,
MOUSE_MOVE, MOUSE_DRAG, MOUSE_ENTER,
and MOUSE_EXIT.
- The two most important keyboard events are KEY_PRESS
and KEY_RELEASE.
- To determine the type of object that generated a event, check
the Event object's target data field.
- To determine the event type, check the event object's
id field.
- The coordinates of the mouse event are passed as the second
and third arguments of the specific mouse method. If you're overriding
handleEvent(), you can get the mouse coordinates from
the Event object's x and y data fields.
- If the user single-clicked the mouse, the Event object's
clickCount data field will be 1. With a double-click,
clickCount will be 2.
- The two methods associated with the KEY_PRESS and
KEY_RELEASE event messages are keyDown() and
keyUp(), respectively.
- The keyDown() method receives as arguments an Event
object and an integer holding the key's ASCII code.
- The mouseDown() event receives as arguments an Event
object and the X and Y coordinates of the mouse click.
- You use the SHIFT_MASK and CTRL_MASK constants
to determine whether the user had the Shift or Ctrl keys pressed.
- To handle all events in a single method, you should override
the handleEvent() method.
- Parameterized applets are easier for users who want to add
the applets to their own Web pages. The parameters enable them
to customize the applet to more closely fit their needs.
- The <PARAM> tag's two parts are NAME,
which specifies the parameter's name, and VALUE, which
associates a value with the parameter.
- To retrieve the value of a parameter, you call the getParameter()
method, whose single argument is the name of the parameter you
want.
- You specify parameter values in the HTML document, as part
of the applet's definition.
- No. The whole point of parameters is that your applet can
change the way it looks and acts without recompiling.
- You can have as many applet parameters as you need.
- The getParameter() method always returns the given
parameter's value as a string. Therefore, you may need to convert
the returned parameter to an integer or some other data type.
- If you fail to define default values for all parameters, your
applet may generate errors as it tries to use nonexistent or invalid
parameter values.
- Java can load only GIF or JPEG files.
- The two parameters required by many of the image and sound
methods are the base URL and the relative location of the file
to load.
- Java recognizes only AU audio files.
- To display an image after it's loaded, you call the Graphics
object's drawImage() method.
- No. You can store images and sounds in any directory relative
to the base URL.
- To scale an image, simply supply the drawImage()
method with the width and height with which you want the image
displayed.
- To determine the normal width and height of an image, call
the Image object's getWidth() and getHeight()
methods.
- The document base URL is the location of the HTML document,
whereas the code base URL is the location of the applet's CLASS
file.
- You have more control over sounds with an AudioClip
object because the AudioClip class provides the play(),
stop(), and loop() methods, whereas the applet
can only play an audio file from beginning to end.
- The single argument is a string containing the URL from which
the URL object should be constructed.
- An AppletContext object represents the application
containing the applet. This application is usually a Web browser.
- To obtain an AppletContext object, call the applet's
getAppletContext() method.
- To ensure that you have a valid URL object, you handle
the exception that may be generated by the URL class.
- To create an exception handler, you must create try
and catch program blocks.
- To connect to an URL, call the AppletContext object's
showDocument() method.
- The URL class throws a MalformedURLException exception
if the URL's string is syntactically incorrect.
- A package is a group of related classes and interfaces.
- To tell Java that a class uses a particular package, you use
the import keyword followed by the full name of the package.
- To add a class or interface to a package, place the package
keyword at the top of the class's or interface's source code followed
by the name of the package to which the class or interface will
be added.
- To tell Java that a class implements a particular interface,
add the implements keyword to the class's declaration
line, followed by the name of the interface.
- The biggest difference between an interface and a class is
that an interface declares, but never implements, its methods.
An interface's methods must be defined in any class that implements
the interface.
- Interfaces and classes are similar in that they are declared
in almost exactly the same way.
- The complete name of a package mirrors the folder hierarchy
on your hard disk into which the package files must be stored.
- You use a try block to hold the program statements
that may generate the exceptions you want to handle.
- You use a catch block to hold the program statements
that should be executed when a particular exception is thrown.
- You don't have to catch all types of exceptions in your applets,
because Java has default handlers for many of them.
- If you call a method that's declared with a throw
phrase, you must handle the exception in your program.
- You can have as many catch blocks as you need in
order to respond to all appropriate exceptions.
- To pass an exception on to a calling method, you declare the
called method with the throws phrase. Java will then
pass the exception to the calling function, where it must be handled
or thrown again.
- Java throws exceptions that must be handled in your program,
as well as throws system, runtime exceptions that you may or may
not decide to handle in your program.
- Threads are like small programs within the main program. Just
as a multitasking system can run two or more applications simultaneously,
so can an applet or application run more than one thread simultaneously.
- All Java threads must implement the Runnable interface,
which contains the run() method needed to start a thread.
- To start a thread, you call the thread object's start()
method.
- When you start a thread, Java calls the thread object's run()
method.
- You'll usually stop your applet's threads in either the stop()
or destroy() method.
- When you suspend a thread, you put it to sleep so that it
remains ready to run when you next need it. When you stop a thread,
you kill the thread, meaning that you'll have to create a new
thread object when you want to run the thread again.
- To ensure that all threads get a chance to run, you should
call, in any thread that takes a while to run, the sleep()
or yield() method.
- When retaining a thread's state is not an issue, you can both
create and start the thread in the applet's start() method.
- When you want to retain a thread's state while the user switches
to and from the Web page containing your applet, you should create
the threads in init(), start or resume the threads in
start(), suspend the threads in stop(), and
stop the threads in destroy().
- Use the synchronized keyword to mark a method or
a block of code as a potential area of conflict for threads trying
to access the same resources.
- When a thread enters a synchronized area of code, Java gives
the thread the class's monitor object. Until the thread releases
the monitor object, no other thread can enter the synchronized
area. In this way, a monitor object is much like a key that unlocks
a synchronized method or block of code.
- The one method that you'll find in every application, but
not in an applet, is main(), which is where a Java application's
execution begins.
- To run a Java application, you compile it using javac, and
then run the byte-code .CLASS file with the Java interpreter,
java.
- The single parameter received by main() is the application's
command-line parameters.
- The parameters come into the main() method as an
array of strings. Each parameter is in one element of the array,
so you can access the elements by indexing the array.
- To convert an applet to an application, you must add the main()
method.
- You must instantiate an object from a class before you can
call its methods because a class is just a template for an object,
much the same way a blueprint is a template for a manufactured
object.
- To create and display an application's window, you call the
Frame class's constructor, and then call the Frame
object's resize() and show() methods.
- To run more than one applet at a time with Appletviewer, create
an HTML document that loads the applets you want to see. Appletviewer
will load and run each applet in its own window.
- Although HotJava is a good example of the type of programs
you can create with Java, it hasn't been kept up to date with
the Java programming language. For this reason, HotJava cannot
run applets created with the latest version of Java. Netscape
Navigator 2.0, on the other hand, can load and run these newer
applets.
- A doc-comment block, which is placed at the top of a class
or right before a method, provides the information javadoc needs
to create useful HTML documentation files.
- To start a program that's been loaded into the Java debugger,
type run.
- To document a method's return value and parameters in a doc-comment,
you use the @return and @param doc tags.
- To start a debugging session with appletviewer, type appletviewer
-debug applet.html, where applet.html is the HTML
document that loads the applet.
- To create hyperlinks in javadoc's HTML documents, add @see
doc tags where appropriate in your doc-comment blocks.
- To start a debugging session with jdb, type jdb app.class,
where app.class is the .CLASS file of the application
you want to debug.
- The javap tool is a disassembler that converts byte-code .CLASS
files into a description of the source code.
- Native methods are methods written in a language other than
Java.
- The javah tool helps you implement native methods by creating
the header files you need to gain access to data fields in Java
classes from your C source code.
- To set a breakpoint with the debugger, type stop at class:line,
where class:line is the class's name and breakpoint line
number separated by a colon.
- You must use the compiler to convert your source-code files
into byte-code (.CLASS) files that Java's interpreter can read
and run.
- If you fail to include the .java extension when specifying
a source-code file in the javac command line, the compiler will
not compile the file and will instead generate an illegal argument
error.
- The options for the javac command line go between the javac
command and the name of the source-code file.
- Yes, you can specify multiple options in one command line.
Just place them one after the other between the javac
command and the name of the source-code file.
- To set a target directory for the compiler's output files,
use the -d option followed by the name of the directory.
- The -g command-line option instructs the compiler
to add debugging information to the byte-code files it generates.
- The -nowarn command-line option instructs the compiler
to suppress warning messages as it compiles a file. The compiler
will still generate error messages.
- To instruct the compiler to generate status information as
it works, specify the -verbose command-line option.
- Byte-code files are the same format on every computer system.
Each type of computer has a Java interpreter specially written
for it. The interpreter reads and executes the byte-code files.
- Everything will run fine if you leave off the file extension.
In fact, the interpreter won't accept the file extension and will
generate an error if you include it.
- Byte-code files have the .CLASS file extension. These are
the types of files that the interpreter can load and execute.
- You can specify verbose output from the interpreter with the
-verbose or -v command options. The second is
just a short version of the first.
- When writing a Java application, you must compile the source
code before the interpreter can load and execute the program.
- To get a list of options supported by the interpreter, type
the command javac -help.
- The interpreter is the only tool that can run a Java application.
This is because the compiler produces Java byte-code files rather
than regular executable files like most other compilers.
- The -checksource (or -cs) command-line option
instructs the interpreter to recompile any source-code files that
have been changed since the last compilation.
- The six main Java packages are lang, awt,
applet, io, util, and net.
- The classes needed to write applications and applets that
run in a windowed environment are found in the awt package.
- You would use the Math class whenever you need to
perform sophisticated mathematical calculations that require functions
like sin, cosine, tangent, and so on.
- By creating an object of the String class, you can
use the class's many methods to manipulate the string.
- To join (or concatenate) two strings, call the String
class's concat() method.
- No, you do not instantiate an object from the Math
class. Because the class's methods are all static, you can call
them like this: Math.Method(), where Method
is the name of the method you want to call.
- The data-type wrapper classes provide methods for manipulating
Java's primitive data types, such as int, float,
and boolean. To use the classes, you can either call
static methods through the class's name (such as, Integer.parseInt())
or create an object of the class and call the methods through
that object.
- The System class provides two methods-getProperty()
and getProperties()- that enable you to obtain information
about the system.
- The io package features many classes that you can
use to perform various types of I/O operations using input and
output streams. Usually, you create an object of the appropriate
class and then manipulate the stream through the object's methods.