Appendix A

Answers to Review Questions


CONTENTS

Chapter 1

  1. 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.
  2. 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.
  3. Java applets are compiled into byte-code files that can be executed by any computer that has a Java interpreter.
  4. 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.
  5. 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.

Chapter 2

  1. Use the Appletviewer tool included with the JDK.
  2. The required attributes are code, width, and height.
  3. 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.
  4. Other optional attributes include alt, align, name, hspace, and vspace.
  5. Applet parameters enable a user to configure an applet to fit his specific needs.
  6. 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.

Chapter 3

  1. A local applet is located on your computer system.
  2. A remote applet is located on another computer system and must be downloaded onto your computer before it can be run.
  3. 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.
  4. 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.
  5. 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.

Chapter 4

  1. 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.
  2. 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.
  3. 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.
  4. The two main elements of a class are data fields and the methods that operate on the data fields.
  5. A class is like a template or blueprint for an object. An object is an instance of the class.
  6. The three main OOP concepts are encapsulation, inheritance, and polymorphism.
  7. 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.

Chapter 5

  1. A constant is a value that can't be changed during a program's execution. Constants have symbolic names like PI or NUMBEROFITEMS.
  2. 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.
  3. 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.
  4. Java's eight data types are byte, short, int, long, float, double, char, and boolean.
  5. 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.

Chapter 6

  1. 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.
  2. 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.
  3. Arguments are values that are sent to a method when the method is called.
  4. The three arguments for the drawString() method are the text string to display, and the column and row at which to display the text.
  5. 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.
  6. One way to get user input is to add a TextField control to your applet.
  7. Java calls the init() method almost immediately after an applet starts up in order to enable you to initialize objects needed by the applet.
  8. 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.
  9. To convert a numerical value to a string, you call the String class's valueOf() method.

Chapter 7

  1. The addition, subtraction, multiplication, and division operators are +, Ð, *, and /, respectively.
  2. 5*3 equals 15.
  3. 3 Ð 2 + 5 + 6 Ð1 equals 11.
  4. The ++ operator increments the variable, so num ends up equal to 13.
  5. 12 % 5 equals 2.
  6. If num equals 25, the expression num += 5 makes num equal to 30.
  7. You set the text is a TextField object by calling TextField's setText() method.
  8. 12 + 3 * 6 / 2 equals 21.
  9. 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.
  10. You cast the result of 56 Ð 34.56f to integer like this: (int)(56 Ð 34.56f).
  11. You convert digits in a string to an integer by calling the Integer class's parseInt() method.
  12. (12 Ð 8) * 10 / 2 * 2 equals 40.

Chapter 8

  1. 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.
  2. The three types of expressions are numerical, assignment, and logical.
  3. The expression (3 < 5) equals true.
  4. The expression (3 < 5) && (5 == 4 + 1) equals true.
  5. Expressions are recursive because they can contain other smaller expressions, which in turn may contain other expressions.
  6. The six comparison operators are == (equals), != (not equal), < (less than), > (greater than), <= (less than or equals), and >= (greater than or equals).
  7. The four logical operators are ! (NOT), && (AND), || (OR), and ^ (exclusive OR).
  8. The result of the expression (3 < 5) || (6 == 5) || (3 != 3) is true.
  9. The result of the expression (5 != 10) && ((3 == 2 + 1) || (4 < 2 + 5)) is true.
  10. The result of the expression !(5 == 2 + 3) && !(5 + 2 != 7 - 5) is false.

Chapter 9

  1. Program flow is the order in which program statements are executed.
  2. 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.
  3. Two ways to control program flow are if and switch statements.
  4. No. The second line will execute only when choice equals 3.
  5. You can write an if statement without opening and closing braces when only one program line will execute if the condition evaluates to true.
  6. There is no difference between a logical and a Boolean expression. They are both expressions that evaluate to true or false.
  7. The program skips over both the if and the else if.
  8. 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.
  9. 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.

Chapter 10

  1. You should use a loop when your program must perform some sort of repetitive task.
  2. The body of the loop comprises the program lines that are executed each time the loop's conditional expression is true.
  3. When the conditional expression evaluates to false, the loop ends.
  4. 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.
  5. 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.
  6. An infinite loop occurs when a loop's conditional expression can never result in false, causing the loop to repeat endlessly.
  7. 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.
  8. The loop will execute six times, and count will be equal to 16 at the end of the loop.

Chapter 11

  1. You should use a for loop when you have a repetitive task that must be performed a specific number of times.
  2. The three parts of a for loop are the initialization, condition, and increment sections.
  3. A for loop stops looping when the condition section becomes false.
  4. A for loop can count backward by decrementing the control variable in the increment section, rather than incrementing it.
  5. A for loop can count by tens by adding 10 to the control variable in the increment section.
  6. 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.
  7. The loop will execute five times, and x will be equal to 13 at the end of the loop.

Chapter 12

  1. 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.
  2. Functions make top-down programming possible by enabling you to organize source code into well-defined tasks.
  3. All functions have a return type, but the return type of void means that the function returns no actual value.
  4. 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.
  5. Defining a function is the act of writing the function's source code.
  6. 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.
  7. 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.
  8. 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.

Chapter 13

  1. An array is a data structure that enables you to store many related values under one variable name.
  2. 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.
  3. 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.
  4. A two-dimensional array can store values in a table, with a specific number of columns and rows.
  5. The largest subscript you can use with a fifty-element array is 49.
  6. If you try to access a nonexistent array element, Java generates an exception.
  7. A for loop is perfect for array access because you can use the loop control variable as an array subscript.
  8. 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.

Chapter 14

  1. A class is a template from which you create an object. A class usually contains data fields and methods.
  2. 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.
  3. 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.
  4. The two program elements that you must add to the empty class in order to create a complete class are data fields and methods.
  5. To create an object of a class, you use the new operator followed by a call to the class's constructor.
  6. 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.
  7. 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.
  8. 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.
  9. You create a subclass by using the extends keyword like this:
    class SubClass extends SuperClass
    {
    }
  10. 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.

Chapter 15

  1. All applets must be derived from Java's Applet class.
  2. 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.
  3. The five life-cycle stages of an applet are initialization, start, paint, stop, and destroy.
  4. 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.
  5. 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).
  6. 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.

Chapter 16

  1. The area of an applet in which you can draw is called the canvas.
  2. 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.
  3. The drawRect() method draws a hollow rectangle, whereas the fillRect() method draws a filled (solid) rectangle.
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. The Polygon class provides several methods that enable you to manipulate a polygon in various ways.

Chapter 17

  1. To get a reference to the currently active font object, you call the Graphics class's getFont() method.
  2. To get a font's name, you can call the Font class's getName() method.
  3. To get a font's height, you can call the Font class's getHeight() method.
  4. You need to know a font's height so you can properly space lines of text.
  5. 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.
  6. 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.
  7. 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.
  8. A point is a unit of measurement of a font's height. A point equals 1/72 of an inch.
  9. 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."
  10. A font's height is the sum of the font's leading, ascent, and descent.
  11. 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.
  12. 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.

Chapter 18

  1. The two arguments required by the Label class's constructor are the text for the label and the label's alignment value.
  2. When an applet containing labels is resized, the labels automatically reposition themselves as appropriate.
  3. After creating controls, you add the controls to the applet with the add() method.
  4. The single argument needed by the Button class's constructor is the text label for the button.
  5. The values for setting a label's alignment are represented by the Label class's Label.LEFT, Label.CENTER, and Label.RIGHT fields.
  6. The Label class provides methods for setting the label's text and alignment.
  7. You can change a button's text label by calling the Button class's setLabel() method.
  8. For a button click, the action() method receives a reference to the button object and the selected button's text label.
  9. You can determine which button was selected by examining the text label passed as the action() method's second parameter.
  10. Nothing happens when a user clicks a label object, because label objects do not generate events.

Chapter 19

  1. 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).
  2. Checkboxes that are set to exclusive mode are also called radio buttons.
  3. The two arguments needed by the TextField class's constructor are the default text and the width (in characters) of the control.
  4. To change the state of a checkbox control call the Checkbox class's setState() method.
  5. 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.
  6. To create a group of checkbox controls (in exclusive mode), you must first create an object of the CheckboxGroup class.
  7. 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.
  8. You select an echo character for a textfield control by calling the TextField class's setEchoCharacter() method.
  9. 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.

Chapter 20

  1. The Choice class's constructor accepts no arguments.
  2. You add items to a choice menu by calling the Choice class's addItem() method.
  3. 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.
  4. You add items to a list by calling the List class's addItem() method.
  5. 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.
  6. 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.
  7. 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.
  8. 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().
  9. 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).
  10. 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.
  11. Yes. You can delete items from a list by calling the List class's deleteItem() or deleteItems() methods.

Chapter 21

  1. The Scrollbar constructor's five arguments are the scrollbar's orientation, value, page size, minimum value, and maximum value.
  2. A canvas is a blank component on which you can draw graphics.
  3. The Canvas class's constructor requires no arguments.
  4. 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.
  5. 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.
  6. A scrollbar can generate SCROLL_ABSOLUTE, SCROLL_LINE_DOWN, SCROLL_LINE_UP, SCROLL_PAGE_DOWN, and SCROLL_PAGE_UP event messages.
  7. To create a custom canvas component, derive a new class from Java's Canvas class.
  8. To draw a canvas's display, override the class's paint() method.

Chapter 22

  1. You can use multiple panels in order to organize sets of controls in a display. Each panel can have its own layout manager.
  2. Java's five layout managers are FlowLayout, GridLayout, BorderLayout, CardLayout, and GridBagLayout.
  3. The default layout manager is FlowLayout.
  4. 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.
  5. 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.
  6. The component positions you can use with the BorderLayout manager are North, South, East, West, and Center.
  7. 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.
  8. 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.
  9. 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.
  10. The constraints determine where in the layout a component will be placed.
  11. GridBagConstraints.fill determines whether components will stretch vertically or horizontally to fill their cells.
  12. To add a component when using the GridBagLayout manager, you first initialize and set the constraints. You then call add() as you normally would.

Chapter 23

  1. To create a frame window, call the Frame class's constructor with the title of the window as the constructor's single argument.
  2. To display a frame window, call the window's show() method.
  3. To determine whether a frame window is visible, call the isShowing() method, which returns true if the window is currently visible and false otherwise.
  4. You use MenuItem objects for regular items in a menu, whereas you use CheckboxMenuItem objects for items that can be checkmarked.
  5. To create a custom frame-window class, you extend the Frame class, which itself extends the Window class.
  6. 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.
  7. 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.
  8. 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.
  9. 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.
  10. You respond to selected menu items by watching for their strings in the action() method, which you must override in the window's class.
  11. A menu separator is just a normal MenuItem object that has a single hyphen as its string.

Chapter 24

  1. 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.
  2. You can display or hide a dialog box by calling the class's show() or hide() methods.
  3. 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.
  4. Every dialog box should have at least an OK button that enables the user to dismiss the dialog box.
  5. 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.
  6. 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.

Chapter 25

  1. The most commonly used mouse event is MOUSE_DOWN, which indicates that the user pressed his mouse button.
  2. 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.
  3. The six mouse event messages are MOUSE_DOWN, MOUSE_UP, MOUSE_MOVE, MOUSE_DRAG, MOUSE_ENTER, and MOUSE_EXIT.
  4. The two most important keyboard events are KEY_PRESS and KEY_RELEASE.
  5. To determine the type of object that generated a event, check the Event object's target data field.
  6. To determine the event type, check the event object's id field.
  7. 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.
  8. 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.
  9. The two methods associated with the KEY_PRESS and KEY_RELEASE event messages are keyDown() and keyUp(), respectively.
  10. The keyDown() method receives as arguments an Event object and an integer holding the key's ASCII code.
  11. The mouseDown() event receives as arguments an Event object and the X and Y coordinates of the mouse click.
  12. You use the SHIFT_MASK and CTRL_MASK constants to determine whether the user had the Shift or Ctrl keys pressed.
  13. To handle all events in a single method, you should override the handleEvent() method.

Chapter 26

  1. 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.
  2. The <PARAM> tag's two parts are NAME, which specifies the parameter's name, and VALUE, which associates a value with the parameter.
  3. To retrieve the value of a parameter, you call the getParameter() method, whose single argument is the name of the parameter you want.
  4. You specify parameter values in the HTML document, as part of the applet's definition.
  5. No. The whole point of parameters is that your applet can change the way it looks and acts without recompiling.
  6. You can have as many applet parameters as you need.
  7. 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.
  8. 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.

Chapter 27

  1. Java can load only GIF or JPEG files.
  2. 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.
  3. Java recognizes only AU audio files.
  4. To display an image after it's loaded, you call the Graphics object's drawImage() method.
  5. No. You can store images and sounds in any directory relative to the base URL.
  6. To scale an image, simply supply the drawImage() method with the width and height with which you want the image displayed.
  7. To determine the normal width and height of an image, call the Image object's getWidth() and getHeight() methods.
  8. 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.
  9. 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.

Chapter 28

  1. The single argument is a string containing the URL from which the URL object should be constructed.
  2. An AppletContext object represents the application containing the applet. This application is usually a Web browser.
  3. To obtain an AppletContext object, call the applet's getAppletContext() method.
  4. To ensure that you have a valid URL object, you handle the exception that may be generated by the URL class.
  5. To create an exception handler, you must create try and catch program blocks.
  6. To connect to an URL, call the AppletContext object's showDocument() method.
  7. The URL class throws a MalformedURLException exception if the URL's string is syntactically incorrect.

Chapter 29

  1. A package is a group of related classes and interfaces.
  2. To tell Java that a class uses a particular package, you use the import keyword followed by the full name of the package.
  3. 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.
  4. 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.
  5. 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.
  6. Interfaces and classes are similar in that they are declared in almost exactly the same way.
  7. The complete name of a package mirrors the folder hierarchy on your hard disk into which the package files must be stored.

Chapter 30

  1. You use a try block to hold the program statements that may generate the exceptions you want to handle.
  2. You use a catch block to hold the program statements that should be executed when a particular exception is thrown.
  3. You don't have to catch all types of exceptions in your applets, because Java has default handlers for many of them.
  4. If you call a method that's declared with a throw phrase, you must handle the exception in your program.
  5. You can have as many catch blocks as you need in order to respond to all appropriate exceptions.
  6. 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.
  7. 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.

Chapter 31

  1. 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.
  2. All Java threads must implement the Runnable interface, which contains the run() method needed to start a thread.
  3. To start a thread, you call the thread object's start() method.
  4. When you start a thread, Java calls the thread object's run() method.
  5. You'll usually stop your applet's threads in either the stop() or destroy() method.
  6. 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.
  7. 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.
  8. When retaining a thread's state is not an issue, you can both create and start the thread in the applet's start() method.
  9. 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().
  10. 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.
  11. 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.

Chapter 32

  1. 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.
  2. To run a Java application, you compile it using javac, and then run the byte-code .CLASS file with the Java interpreter, java.
  3. The single parameter received by main() is the application's command-line parameters.
  4. 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.
  5. To convert an applet to an application, you must add the main() method.
  6. 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.
  7. 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.

Chapter 33

  1. 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.
  2. 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.
  3. 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.
  4. To start a program that's been loaded into the Java debugger, type run.
  5. To document a method's return value and parameters in a doc-comment, you use the @return and @param doc tags.
  6. To start a debugging session with appletviewer, type appletviewer -debug applet.html, where applet.html is the HTML document that loads the applet.
  7. To create hyperlinks in javadoc's HTML documents, add @see doc tags where appropriate in your doc-comment blocks.
  8. 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.
  9. The javap tool is a disassembler that converts byte-code .CLASS files into a description of the source code.
  10. Native methods are methods written in a language other than Java.
  11. 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.
  12. 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.

Chapter 34

  1. You must use the compiler to convert your source-code files into byte-code (.CLASS) files that Java's interpreter can read and run.
  2. 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.
  3. The options for the javac command line go between the javac command and the name of the source-code file.
  4. 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.
  5. To set a target directory for the compiler's output files, use the -d option followed by the name of the directory.
  6. The -g command-line option instructs the compiler to add debugging information to the byte-code files it generates.
  7. The -nowarn command-line option instructs the compiler to suppress warning messages as it compiles a file. The compiler will still generate error messages.
  8. To instruct the compiler to generate status information as it works, specify the -verbose command-line option.
  9. 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.

Chapter 35

  1. 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.
  2. Byte-code files have the .CLASS file extension. These are the types of files that the interpreter can load and execute.
  3. 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.
  4. When writing a Java application, you must compile the source code before the interpreter can load and execute the program.
  5. To get a list of options supported by the interpreter, type the command javac -help.
  6. 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.
  7. The -checksource (or -cs) command-line option instructs the interpreter to recompile any source-code files that have been changed since the last compilation.

Chapter 36

  1. The six main Java packages are lang, awt, applet, io, util, and net.
  2. The classes needed to write applications and applets that run in a windowed environment are found in the awt package.
  3. You would use the Math class whenever you need to perform sophisticated mathematical calculations that require functions like sin, cosine, tangent, and so on.
  4. By creating an object of the String class, you can use the class's many methods to manipulate the string.
  5. To join (or concatenate) two strings, call the String class's concat() method.
  6. 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.
  7. 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.
  8. The System class provides two methods-getProperty() and getProperties()- that enable you to obtain information about the system.
  9. 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.