Errata: A Programmer's Guide to Java™ Certification

A Comprehensive Primer

(First Edition)

Khalid A. Mughal and Rolf W. Rasmussen

ISBN 0201596148

This is an exhaustive list of corrections, etc. for the FIRST PRINTING of the book.

Last updated October 6, 2002.

Acknowledgements:

Many thanks to the following readers for their diligent observations:
Michael F. Adolf, Tony Alicea, Kåre Auglænd, Jorge L. Barroso, Andre Beland, Darren Bruning, Paul Campbell, Roger Chang, Joanna Chappel, Laurian M Chirica, Arkadi Choufrine, Barry Colston, John Cotter, Frédéric Demers, Arthur De Souza, djc, William Ekiel, Darryl Failla, John Finlay, Christopher R. Gardner, Marco Garcia, Peter Gieser, George, Paul Graf, Shyamsundar Gururaj, Ray Ho, Leonardo Holanda, Zhu Hongjun, Kara Van Horn, Peter Horst, Nain Hwu, Kent Johnson, Samir Kanparia, Oleksiy Karpenko, Jeffrey Kenyon, Young Jin Kim, Kenneth Kisser, Billy Kutulas, Yi-Ming Lai, Robert M. Languedoc, Steve Lasley, Winser Lo, Naga Madipalli, Craig Main, Avinash Mandsaurwale, Thomas Mathai, S. Mehra, Yuan Meng, Simon Miller, William Moore, Anders Morch, George A. Murakami, Sandy Nemecek, Chun Pan, Abigail García Patiño, Anil Philip, Alfred Raouf, Peter Rorden, Christian Seifert, Gurpreet Singh, Christopher Stanwood, Swaminathan Subramanian, Siva Sundaram,  Manju Swamy, John Sweeney, Harmon Taylor, Andrew Tolopko, Ravi Verma, Per J. Walstrøm, Chun Wang, James Ward, Winky, Chun Wang, Jimmy Yang, Jennie Yip, Yanqu Zhou, Yingting Zhou.

Changes added October 6, 2002.

Page 22, Table 2.1 Keywords in Java

Add the keyword assert to the table.

Page 43, Casting

The following sentence is not correct:

"Casting the reference literal null, which is not of any type, to a reference type results in a compile time warning."

and should be replaced by:

"The reference literal null can be cast to any reference type."

Page 120, Review Question 4.17

Replace the choices with the following:

(a) Member variable i is accessible in  all classes in other packages. 
(b) Member variable j is accessible in all classes in other packages. 
(c) Member variable k is  accessible in all classes in other packages. 
(d) Member variable k is  accessible in subclasses only in other packages. 
(e) Member variable l is  accessible in all classes in other packages. 
(f) Member variable l is  accessible in subclasses only in other packages.

Page 123, final Members

In the middle of the page, replace the line beginning with:

" setKWH from the superclass ... "

with:

" setWatts() from the superclass ... "

Page 186, Review Question 6.5

Change choice (e) 

(e) The overriding method can have a different return value than the overridden method.

to (replace "value" with "type"):

(e) The overriding method can have a different return type than the overridden method.

Page 235, Example 7.6 Inheritance and Containment Hierarchy

With line (2) uncommented, the compiler distributed with J2SE 1.4 compiles the code without error. However, this is a recent change to the Sun compiler. We cannot see that the Java Language Specification (JLS) has been changed to allow such disambiguation, and other standards compliant compilers such as IBM's Jikes still reject the code. We don't know whether this is a case of misinterpreting the JLS, or a bug in the Sun Java compiler distributed with J2SE 1.4.

Page 284, Thread States

In the paragraph for Blocked state, make the following two changes:

Change "Blocking state" to "Blocked state".

Change the sentence:

"A thread also blocks if it fails ..."

to:

"A thread will be blocked if it fails ..."

Page 296, Section 10.1 Overview of the java.lang package

The bullet:

"The wrapper classes (Boolean, Character, Number, Byte, Short, Integer, Long, Float, Double)"

should read (delete Number):

"The wrapper classes (Boolean, Character, Byte, Short, Integer, Long, Float, Double)"

Page 320, Controlling String Buffer Capacity

In the middle of the page, change "\u0000" to '\u0000'

Page 333, Section 11.4 Lists

The sentence:

"The remove() method deletes and returns the element at the specified index, contracting the list accordingly."

should read:

"The remove(int index) method deletes and returns the element at the specified index, contracting the list accordingly."

Page 379, Example 12.12 Illustrating Menus

The following import statement can be deleted: 

import java.applet.*;

Page 469, Drawing Polygons

The sentence:

"The Polygon class has the following constructors:"

should read:

"The Polygon class has the following constructor:"

Page 569, Table 18.6 Writers

In the row for the PrintWriter, change the sentence:

"A filter that allows textual representations of ..."

to:

"A writer that allows textual representations of ..."

Page 583, Section 18.5 Random Access for Files

Change the exception in the constructors:

RandomAccessFile(String name, String mode) throws IOException
RandomAccessFile(File file, String mode) throws IOException

to:

RandomAccessFile(String name, String mode) throws FileNotFoundException
RandomAccessFile(File file, String mode) throws FileNotFoundException

Changes added December 22, 2001.

Page 3, Declaring Members: Variables and Methods

In the middle of the page, replace the following:

"It also has a special method that has the same name as the class. Such methods are called constructors, ..."

with:

"It also has a special method-like declaration that has the same name as the class, (2). Such declarations are called constructors, ..."

Page 7, Section 1.5 Static Members

In the middle of the page, replace the sentence:

"Static members are distinguished from instance variables in a class definition by the keyword static in their declaration."

with:

"Static members are distinguished from instance members in a class definition by the keyword static in their declaration."

Page 24, Table 2.6 Examples of Octal and Hexadecimal Literals in Java

Replace the last row of the table:

-2147483648
-017777777777
-0x7fffffff

with:

-2147483648
-020000000000
-0x80000000

Page 48, Numeric Type Conversions on Assignment

The following paragraph is not correct any more:

"Narrowing conversions between char and byte (or short) values on assignment always require an explicit cast, even if the value is in the range of the destination datatype."

The new rules state that a narrowing primitive conversion is valid if the following conditions are fulfilled:

1. The right-hand side expression (i.e. source) is a constant expression of type byte, short, char or int.
2. The type of the left-hand variable (i.e. destination) is  byte, short, or char.
3. The value of the constant expression is in the range of the destination datatype.

Page 137, switch Statement

Replace the following sentence in the lower half of the page:

"The value LITTLE_ADVICE results in only one advice at (5) being given."

with:

"The value LITTLE_ADVICE results in only one advice at (4) being given."

Page 228, Figure 7.1 Top-level Nested Classes and Interfaces

To make the figure consistent with Example 7.2, do the following:

In the figure, add public accessibility, '+', to the class AccessInTopLevelClass.

In the figure, remove public accessibility, '+', from the interface NestedTopLevelInterface1.

Page 313, Searching for Characters and Substrings

On top of the page, replace the line:

String replace(char old, char new)

with:

String replace(char oldChar, char newChar)

Page 447, Review Question 14.18

Replace the question:

"What would be the effect of calling enableEvent(AWTEvent.KEY_EVENT_MASK) on a component?"

with:

"What would be the effect of calling enableEvents(AWTEvent.KEY_EVENT_MASK) on a component?"

Page 556, Section 18.3 Byte Streams: Input Streams and Output Streams

In the middle of the page, replace the sentence:

"Note that the first read() method read a byte, but returns an int value."

with:

"Note that the first read() method reads a byte, but returns an int value."

Page 558, Searching for Characters and Substrings

In the lower half of the page, replace the line:

FileOutputStream(File file) throws IOException

with:

FileOutputStream(File file) throws FileNotFoundException

Changes added June 29, 2001.

Page ix, Book web sites

Replace the following:

Information about the JDK and its documentation can be found at the following web site:

    <URL:http://java.sun.com/products/jdk/1.2/>

with:

Information about the Java 2 SDK Standard Edition (referred to as JDK in the book) and its documentation can be found at the following web site:

    <URL:http://java.sun.com/j2se/>

Page 40, Programming Exercise 2.1

A short note on creating and using packages.

A package statement can only occur as the first statement in a Java source file.
The statement

package com.acme;

instructs the compiler to place the Java byte code for all the classes (and interface) specified in the source file in the package com.acme.

Think of a package name as a path in the file system.
In this case the package name com.acme corresponds to the path name com/acme. So the Java byte code for all the classes (and interface) specified in the source file Exercise1.java will be placed under the catalog com/acme.

Question: where is com/acme?
You can choose the location of com/acme by using the -d option (d for destination) when compiling with javac. Assume that the current directory is called work, and the source code file Exercise1.java is to be found here. The command

javac -d . Exercise1.java

(note the dot after the -d option to indicate the current directory) will create com/acme under the current directory, and place the Java byte code for all the classes (and interface) in it.

                                  work
                                   |
                        ------------------------
                        |                      |
                  Exercise1.java              com
                                               |
                                              acme
                                               |
                                         Exercise1.class

How do we run the program? Since the current directory is work and we want to run Exercise1.class, the *full name* of the Exercise1 class must be specified in the java command:

java com.acme.Exercise1

This will now result in the main() method from the com.acme.Exercise1 class being executed.

Page 43, Casting

Replace the sentence in the lower part of the page:

"The same applies to the reference literal null, which is not of any type and therefore cannot be cast to any type."

with:

"Casting the reference literal null, which is not of any type, to a reference type results in a compile time warning."

Page 48, Numeric Type Conversions on Assignment

Replace the following line at the top of the page:

    float fast = (float) 100.5D; // Narrowing: double to float.

with (gives a better example of truncating):

    float fast = (float) 300.5D; // Narrowing: double to float.

Page 68, Examples of Bitwise Extended Assignment

Replace the line:

"At (1) in the examples above, both the byte value in v1 and the char value in v2 are first promoted to int."

with:

"At (1) in the examples above, both the char value in v1 and the byte value in v2 are first promoted to int."

Page 68, Shift Operators: <<, >>, >>>

Replace the sentences:

"The number of bits shifted is always in the range modulus 32 for an int value, and in the range modulus 64 for a long value."

with:

"The shift distance is calculated as the value of the expression (right operand value & (size-1)), where size is either 32 or 64 depending on whether the promoted type of the left operand is int or long. Thus the shift distance is always in the range 0 to 31 when the promoted type of left operand is int, and in the range 0 to 63 when the promoted type of left operand is long."

Page 70, The Shift-right-with-sign-fill Operator >>

Replace the following line in the middle of the page:

    = 0xfffffffa

with:

    = 0xfffffffd

Page 71, Shift Extended Assignment Operators: <<=, >>=, >>>=

Replace the following line in the middle of the page:

    = 0xc0

with:

    = 0x80

Page 88, Declaring Array Variables

At the top of the page, replace the following:

"..., and therefore does not apply to local arrays as well (Section 2.9, p. 34)."

with:

"..., and therefore does not apply to local array variables as well (Section 2.9, p. 34)."

Page 92, Figure 4.1 Arrays of Arrays

Extra horizontal line in the class diagram for matrix:double[][] should be deleted.

Page 163, throws Clause

The last sentence of this page:

"The method definition in the subclass can only specify all or none, or a subset of the exception classes (including their subclasses) specified in the throws clause of the overridden method in the superclass."

should be replaced with (insert checked ):

"The method definition in the subclass can only specify all or none, or a subset of the checked exception classes (including their subclasses) specified in the throws clause of the overridden method in the superclass."

Page 181, Variable Shadowing

In the last sentence of this section, replace the following:

"...: the variable accessed is from the class corresponding to the reference type, ..."

with:

"...: the variable accessed is declared in the class corresponding to the reference type, ..."

Page 212, Review Question 6.20

Replace the code lines:

    // Definitions: 
    interface A {}; 
    class B {};
    class C extends B implements A {};
    class D implements A {};

with (remove ;):

    // Definitions:
    interface A {}
    class B {}
    class C extends B implements A {}
    class D implements A {}

Page 254, Finalizer Chaining

In the last line, replace "massage" with "message". :-)

Page 255, Invoking Garbage Collection

Replace the sentence:

"The System.gc() method can be used to force garbage collection, and the System.run Finalization() method can be used to run the finalizers (which have not been executed before) for objects eligible for garbage collection."

with:

"The System.gc() method can be used to request garbage collection, and the System.run Finalization() method can be called to suggest that the finalizers (which have not been executed before) for objects eligible for garbage collection be run."

Page 284, Thread States

In the line that starts "Dead state: ...", replace  "Runnable" with "Running". 

Page 369,  List

Delete the following lines:

    void select(String str)

    Selects the item that matches the argument string in the list.

Page 453, Figure 15.1 Coordinates of a Component

Replace the following in the figure:

    (top, left)

with:

    (left, top)

Page 454, The Graphics Class

Replace the following sentence in the middle of the page:

"The origin of the drawing region in a component is given by (getInsets().top, getInsets().left)."

with:

"The origin of the drawing region in a component is given by (getInsets().left, getInsets().top)."

Page 517, Root Containers

Replace the sentence:

"Root components JComponent, JWindow, JFrame, JDialog and JApplet all extend their respective native AWT components, as shown in Figure 17.5."

with (delete JComponent):

"Root components JWindow, JFrame, JDialog and JApplet all extend their respective native AWT components, as shown in Figure 17.5."

Page 552, Querying the File System

Replace the sentence at the top of the page:

"Also platform-dependent, the canonical path usually specifies a pathname in which all relative references have been completely resolved."

with (insert "absolute"):

"Also platform-dependent, the canonical path usually specifies an absolute pathname in which all relative references have been completely resolved."

Page 558, Table 18.2 Output Streams

Add a horizontal line between DataOutputStream and ObjectOutputStream.

Page 579, Terminal I/O

In the upper half of the page, replace the sentence:

"The PrintStream class is now mostly deprecated, but its print() methods, which act as corresponding print() methods from the PrintWriter class, can still be used to write output to System.out and System.err."

with:

"The PrintStream class offers print() methods which act as corresponding print() methods from the PrintWriter class. These methods can be used to write output to System.out and System.err."

Page 598, Specifying Hyperlinks to Members

To the existing list, add the following:

@see <class-name>#<member-name> <label>
@see <class-name>#<method-signature> <label>
{@link <class-name>#<member-name> <label>}
{@link <class-name>#<method-signature> <label>}

Page 625, Answer to Review Question 2.11 

Additional explanation:

Strict adherence to the Java language specification requires the following declaration to start the execution of a Java program:

public static void main(String[] args)

This does not rule out any other legal non-accessibility modifiers like final. The Java compiler is however taking liberties with the specification allowing other declarations for starting the execution of a Java program.

Page 637, Answer to Review Question 6.2 

See "Clarification on Inheritance of Superclass Members".

Page 641, Answer to Review Question 6.27

Replace the line:

"... , but rather uses the public interface."

with:

"... , but rather uses the public method describe() in class Star to do that."

Page 662, Answer to Review Question 18.2

Replace the answer with:

18.2 (b)

The separator constant is of type String and contains the character used as path separator on the native platform. The most common platforms only use a single character as a path separator.

Page 668, Alternate solution to Programming Exercise 3.2

public class BinConversion {
    public static void main(String args[]) {
       System.out.println(convert(43));
    }
    public static String convert(int i) {
       String res = "";
       do {
           res = i % 2 + res;
           i /= 2;
       } while (i >= 1);
       return res;
    }
}

Page 699, Q2

Choice (d):

The value returned by >>> will never be negative as long as the value of the right operand is not divisible by 32.

should be replaced with:

The value returned by >>> will never be negative as long as the value of the right operand is not divisible by 32, and the left operand is non-negative.

Page 725, Answer to Q29

Replace the answer with:

Q29 (b), (c) and (e)

Unlike local variables, all member variables are initialized with default initial values. All numeric variables are initialized to zero, boolean values to false, char values to '\u0000' and all object reference values to null. (c) occurs when an un-initialized member variable is used in an initializer block before its declaration.

Changes added December 22, 2000.

Page 70, The Shift-right-with-sign-fill Operator >>

Replace the line:

"The value for i is shifted right with sign-fill 4 places:"

with (replace 4 with 2):

"The value for i is shifted right with sign-fill 2 places:"

Page 129, Review Question 4.25

Replace choice (d) with (delete the words "The constructor"):

            (d) MyClass() cannot be declared final.

Page 200, Review Question 6.13

Replace the question:

"Given the following variable declaration within the definition of an interface, which of these declarations are equivalent to it?"

with:

"Given the following variable declaration within the definition of an interface, which of these  declarations can be substituted for it?"

Page 230, Example 7.3 Defining Non-static Inner Classes 

Replace the code line:

private static String msg = "Shine the inner light.";     // (2)

with (delete the word static):

private String msg = "Shine the inner light.";            // (2)

Page 399, Review Question 13.11

Replace the question:

"Which of these are methods in the CardLayout class?"

with:

"Which of these method names are in the CardLayout class?"

Page 527, JTree 

Replace the first sentence of the last paragraph:

"A JTree uses an object implementing the TreeCellRenderer interface to render cells in each column of the table."

with:

"A JTree uses an object implementing the TreeCellRenderer interface to render the elements in the tree structure."

Page 632, Answer to Review Question 4.25 

Replace the sentence:

"Only methods can be declared synchronized."

with:

"Only methods and code blocks can be synchronized."

Page 716, Q49

Replace the question:

"Which modifiers and return types would be valid in the declaration of a working main() method for a Java standalone application?"

with:

"Which modifiers and return types would be valid in the declaration of a main() method which starts the execution of a Java standalone application?"

Changes added October 13, 2000.

Page 20, Exam Objectives

The last bullet (and its sub-bullet) should be deleted:

Page 39, Review Question 2.11

The question:

"Which of these are valid declarations of the main() method?"

should read:

"Which of these are valid declarations of the main() method in order to start the execution of a Java program?"

Page 106, Packages

Second paragraph, in the sentence:

"Subpackages do not afford anything extra when it come to accessibility of the members."

replace "come" with "comes":

"Subpackages do not afford anything extra when it comes to accessibility of the members."

Page 136, switch Statement

The sentence:

"The <statementi> associated with the first case label that is equal to the value of the integral expression is executed."

should be changed to (delete "first"):

"The <statementi> associated with the case label that is equal to the value of the integral expression is executed."

Page 149, return Statement

The sentence:

"The first form of the return statement can also be used in constructors and initializers, as these also do not return a value."

should be changed to:

"The first form of the return statement can also be used in constructors as these also do not return a value."

Page 179, Method Overriding

Change the bullet :

to (i.e. insert "or none,"):

Page 240, Access Rules for Local Classes

Replace these 2 lines of code:

	double zz = A.this.z;
	...
	double yy = A.this.y;

with

	double zz = TopLevelA.this.z;
	...
	double yy = TopLevelA.this.y;

Page 305, Pseudo Random Number Generator

The sentence:

"The method random() returns a random number greater or equal to 0.0 and less than 1.0, where the value is selected randomly with the range according to a uniform distribution."

should be (change "with" to "from"):

"The method random() returns a random number greater or equal to 0.0 and less than 1.0, where the value is selected randomly from the range according to a uniform distribution."

Page 347, Collection Adapters

Change the code line:

	String[] uniqueJiveArray = (String[])jiveSet.toArray();

to:

	String[] uniqueJiveArray = (String[])jiveSet.toArray(new String[0]);

Page 464, Drawing Rectangles

The method prototypes:

void drawRoundRect (
    int x, int y,         // top left corner
    int width, int height // of rectangle
    int arcWidth, int arcHeight
)
void fillRoundRect (
    int x, int y,         // top left corner
    int width, int height // of rectangle
    int arcWidth, int arcHeight
)
void fill3DRect (
    int x, int y,         // top left corner
    int width, int height // of rectangle
    int arcWidth, int arcHeight,
    boolean raised
)
void draw3DRect (
    int x, int y,         // top left corner
    int width, int height // of rectangle
    int arcWidth, int arcHeight,
    boolean raised
)


void fill3DRect (
    int x, int y,         // top left corner
    int width, int height // of rectangle
    int arcWidth, int arcHeight,
    boolean raised
)

should be changed to (all of them are missing a comma, and in the last 2 prototypes a code line must be deleted):

void drawRoundRect (
    int x, int y,         // top left corner
    int width, int height, // of rectangle
    int arcWidth, int arcHeight
)
void fillRoundRect (
    int x, int y,         // top left corner
    int width, int height, // of rectangle
    int arcWidth, int arcHeight
)
void draw3DRect (
    int x, int y,         // top left corner
    int width, int height, // of rectangle
    boolean raised
)


void fill3DRect (
    int x, int y,         // top left corner
    int width, int height, // of rectangle
    boolean raised
)

Page 495 Applet Life Cycle

The paragraph:

"Although subclasses of the Applet class can provide a default constructor, it is seldom used to initialize the applet. This is instead done in the init() method of the applet."

should be changed to:

"Although subclasses of the Applet class can provide a default constructor for initialization purposes, this is usually done in the init() method of the applet.

Page 548, Chapter 18 Files and Streams

Replace the page with the following:

    Exam Objectives

    Supplementary Objectives

Page 552, Querying the File System

In the 2nd paragraph, at the end of last sentence, replace the text:

"... and "c:\documents\book\chapter1", respectively."

with (delete the text "\documents"):

"... and "c:\book\chapter1", respectively."

Page 594, Section 9.1 Javadoc Facility

Replace the bullet:

with:

Page 613, Forms of answers expected

In the 4th. paragraph of this section, replace the first sentence:

"For multiple choice questions, the program will present a list of answers with either radio buttons or checkboxes."

with:

"For multiple choice questions, the program will ask the candidate to select a specific number of answers from a list."

Page 616, Appendix B Objectives for the SCPJ2 Exam

Replace the URL

        <URL:http://suned.sun.com/usa/cert_test.html?content=scpj2_obj>

with the following:

    <URL:http://suned.sun.com/USA/certification/progobj.html#Java2>

Page 618, Section TitleLanguage Fundamentals (Chapter 2)

The last objective should be deleted and inserted on page 621 (see below).

Page 621, Section Title The java.awt package (Chapter 13)

The objective deleted from page 618 should be added to the objectives for this section:

Page 622,  Section Title The java.io package (Chapter 18)

Add the following study notes after the objectives (see previous corrections for this page):

Study notes

Navigation in the file system is done using the File class. The concept of a stream is central to dealing with input and output. Input and output streams are provided for reading and writing bytes and characters. Classes FileInputStream and FileOutputStream are streams for dealing with the file content. Class RandomAccessFile allows direct access to the file content as opposed to sequential access provided by FileInputStream and FileOutputStream. Readers and writer are provided for reading from and writing characters to streams. Classes InputStreamReader and OutputStreamWriter can be used to specify a character encoding when reading from and writing characters to a stream. Streams can be chained to filters (subclasses of FilterInputStream and FilterOutputStream) to provide additional functionality (for example buffering of data, reading and writing Java primitive values).

Page 646, Review Question 9.6

The sentence:

"For each invocation of check(), each variable pair is incremented and their values are always equal when the method returns."

should be changed to

"For each invocation of doit(), each variable pair is incremented and their values are always equal when the method returns."

Page 727, Q51

The sentence:

"Mouse-motion listeners can be registered on all objects that are instances of Container."

should be changed to:

"Mouse-motion listeners can be registered on all objects that are instances of Component."

Changes added September 22, 2000.

Page 7, Figure 1.4 Class Diagram showing Static Members of a Class

The method name:

    getCounter()

should be replaced by:

    getInstanceCount()

Page 10, Example 1.3 Defining a Subclass

Replace the code line:

    for (int i = 0; i < stackArray.length; i++)

with:

    for (int i = 0; i <= topOfStack; i++)

Page 73, Review Question 3.14

The question:

"Given a variable x of type int (which may contain a negative value), which are correct ways of doubling the value of x?"

should be rephrased:

 "Given a variable x of type int (which may contain a negative value), which are correct ways of doubling the value of x, barring any overflow?"

Page 95, Review Question 4.5

In choice (b), replace:

    IndexArrayOutOfBoundsException

with:

    ArrayIndexOutOfBoundsException

Page 111, Review Question 4.15

Replace the code line:

    abstract void haunt()

with (semi-colon missing):

    abstract void haunt();

Page 117, protected Members

Replace the code line:

    objRefA.superclassVarA;               // (4) Not OK.

with:

    objRefA.superclassVarA = 10;          // (4) Not OK.

Page 163, Section 5.8 throws Clause

Change the last sentence on the page:

"The method definition in the subclass can only specify all or a subset of the exception classes (including their subclasses) specified in the throws clause of the overridden method in the superclass."

to (i.e. insert "or none,"):

"The method definition in the subclass can only specify all or none, or a subset of the exception classes (including their subclasses) specified in the throws clause of the overridden method in the superclass."

Page 165, Review Question 5.16

In choice (c), replace:

    IndexOutOfBoundsException

with:

    ArrayIndexOutOfBoundsException

Page 616, Appendix B Objectives for the SCPJ2 Exam

Add the following exam objectives which are covered in Chapter 18:

    Section Title: The java.io package (Chapter 18)

Changes added August 21, 2000.

Page 88, Constructing an Array

In the 2nd paragraph from bottom, in the last sentence, replace "mediumPizza" with "mediumPizzas", i.e.

"For example, the element at index 2 in array anIntArray gets the value 0, and the element at index 3 in array mediumPizza gets the value null when the arrays are constructed."

should be:

"For example, the element at index 2 in array anIntArray gets the value 0, and the element at index 3 in array mediumPizzas gets the value null when the arrays are constructed."

Page 90, Example 4.1 Using Arrays

Replace the 0 with 1 in the following code:

    for (int i = 0; i < valArray.length; ++i)
        minValue = Math.min(minValue, valArray[i]);

The code should be:

    for (int i = 1; i < valArray.length; ++i)
        minValue = Math.min(minValue, valArray[i]);

Page 98, Statements

In the first paragraph, replace the text "(chapter 4)" with "(chapter 5)".

Page 101, Default Constructor

In the first sentence of the last paragraph, replace the text "it does nothing" with "the method body is empty".

Page 103, Overloaded Constructors

Add the following sentence at the end of the first paragraph: "See also Section 6.3."

Page 114, Figure 4.3 Block Scope

The first line of code :

    public static void main(String args[]{

should be replaced by (the closing bracket, ')', is missing):

    public static void main(String args[]) {

Page 124, abstract Methods

In the middle of the page, the sentences

"Subclasses of its class are then forced to provide the method implementation. Abstract classes are discussed in Section 4.7, where Example 4.6 also illustrates the usage of abstract methods."

should be replaced by:

"Subclasses of an abstract class must then provide the method implementation, otherwise they are also abstract. See Section 4.7, where Example 4.6 also illustrates the usage of abstract methods."

Page 202, Figure 6.4 Array Types in Inheritance Hierarchy

There should be an arrow from the <<interface>> IStack[] box pointing to the Object[] box.
This arrow should NOT be a "dotted" arrow.

Page 234, Compiling and Importing Non-static Inner Classes

In the last sentence before Example 7.5, replace "... appended to the class's name ..." by "... prepended to the class's name ..."

Page 242, Instantiating Local Classes

In the code snippet, in the 2nd line createCircle() should be createCircle(5), i.e.

    IDrawable[] drawables = {             // (10)
        new Painter().createCircle(),     // (11) Object of non-static local class
        Painter.createMap(),              // (12) Object of static local class
        new Painter().createMap()         // (13) Object of static local class
    };

should be:

    IDrawable[] drawables = {             // (10)
        new Painter().createCircle(5),    // (11) Object of non-static local class
        Painter.createMap(),              // (12) Object of static local class
        new Painter().createMap()         // (13) Object of static local class
    };

Page 253, Example 8.1 Using Finalizers

Change the order of the following code lines:

    super.finalize();
    --population;

to:

    --population;
    super.finalize();

Page 305, Pseudo Random Number Generator

In the code snippet, replace Pseudonumber by Pseudorandom number, i.e.

    // Example of Pseudonumber Generator

should be:

    // Example of Pseudorandom Number Generator

Page 319, Appending, Inserting and Deleting Characters in String Buffers

In the following code snippet, delete the four occurrences of "buffer =", i.e. the code

    // Examples of appending, inserting and deleting in string buffers
    StringBuffer buffer = new StringBuffer("banana split");   // "banana split"
    buffer = buffer.delete(4,12);                             // "bana"
    buffer = buffer.append(42);                               // "bana42"
    buffer = buffer.insert(4,"na");                           // "banana42"
    buffer.setCharAt(0,'s');                                  // "sanana42"
    buffer = buffer.reverse();                                // "24ananas"

should be:

    // Examples of appending, inserting and deleting in string buffers
    StringBuffer buffer = new StringBuffer("banana split");   // "banana split"
    buffer.delete(4,12);                                      // "bana"
    buffer.append(42);                                        // "bana42"
    buffer.insert(4,"na");                                    // "banana42"
    buffer.setCharAt(0,'s');                                  // "sanana42"
    buffer.reverse();                                         // "24ananas"

Page 337, Review Question 11.6

The first "are" should be deleted.

Page 347, Collection Adaptors

Change "Adaptors" to "Adapters" in the title.

Page 399, CardLayout Manager

In the sentence:

"Each consecutive card is shown by calling the next() method on the CardLayout object with the applet as the argument at (7)."

the text "(7)" should be "(8)":

"Each consecutive card is shown by calling the next() method on the CardLayout object with the applet as the argument at (8)."

Page 433, Example 14.4 Listeners as Anonymous Classes

The line

if (evt.getSource() == quitButton)

should be deleted from the following code:

    // Create and add the listener to the button
    quitButton.addActionListener(new ActionListener() {  // (1)
        // Invoked when the user clicks the quit button.
        public void actionPerformed(ActionEvent evt) {
            if (evt.getSource() == quitButton)
                terminate();                             // (2)
        }
    });

The code should be:

    // Create and add the listener to the button
    quitButton.addActionListener(new ActionListener() {  // (1)
        // Invoked when the user clicks the quit button.
        public void actionPerformed(ActionEvent evt) {
            terminate();                                 // (2)
        }
    });

Page 552, Querying the File System

In the 2nd paragraph, at the end of last sentence, replace the text:

"... and "c:\book\chapter1", respectively."

with (insert the text "\documents"):

"... and "c:\documents\book\chapter1", respectively."

Page 604, Review Question 19.3

Replace the code line

    /*

with (missing one *):

    /**

Page 641, Answer to Review Question 6.25

Replace the last word "overloaded" by "overridden".

Page 673 - 674, Answers to Programming Exercise 6.1 and 6.2

Replace all 7 occurrences of evaulate with evaluate.

Page 674 - 675, Answer to Programming Exercise 7.1

Replace all 8 occurrences of evaulate with evaluate.

The Mock Exam Engine

The on-line exam is missing the underscore in choice a) of question 41, page 714, in the book. It says "class" instead of "_class".

Changes added August 16, 2000.

Clarification on Inheritance of Superclass Members

On page 118 (subsection private Members) and on page 173 (section 6.1 Inheritance), it is stated that ALL members of a superclass are inherited by the subclasses. Accessibility modifiers can be used to control whether the inherited members are accessible in the subclasses or not.

The Java Language Specification (JLS) states in section 8.2 that
"Members of a class that are declared private are not inherited by subclasses of that class. Only members of a class that are declared protected or public are inherited by subclasses declared in a package other than the one in which the class is declared.
Constructors, static initializers, and instance initializers are not members and therefore are not inherited."

According to this view, inheritance is linked to DIRECT ACCESSIBILITY of superclass members. In this sense the private members of the superclass are NOT inherited by the subclasses, but these members do EXIST in a subclass OBJECT. Private members of the superclass may be indirectly accessible from a subclass object if the superclass provides the appropriate implementation. In the example below, the private variable i in superclass A exists in object b of subclass B, but this data member is not inherited by the subclass B.

class A {
    private int i = 10; // Not inheritable
    public void printI() { // Inheritable
    System.out.println("i " + i);
    }
}

class B extends A {}

public class Inheritance {
    public static void main(String[] args) {
    
         B b = new B();
    
         b.printI();
    }
}

Output from the program:
i 10

JLS further states (section 8.4.6):

"A class inherits from its direct superclass and direct superinterfaces all the non-private methods (whether abstract or not) of the superclass and superinterfaces that are accessible to code in the class and are neither overridden (§8.4.6.1) nor hidden (§8.4.6.2) by a declaration in the class."

We will make the appropriate changes in accordance with JLS in the next edition when the time comes.

Page 68, Shift Operators: <<, >>, >>>

In the last sentence at the bottom of the page:

"Since char, byte and short operands are promoted to either int or long, the result of applying these bitwise operators is always either an int or a long value."

Remove the first occurrence of "either" and "or long" so that the sentence reads:

"Since char, byte and short operands are promoted to int, the result of applying these bitwise operators is always either an int or a long value."

Page 88, Constructing an Array

In the middle of the page, the sentence:

"However, here <elementType2> must be assignable to <elementType1> (Section 6.5, p. 201)."

should be replaced with:

"However, here array type <elementType2>[] must be assignable to array type <elementType1>[] (Section 6.5, p. 201)."

Page 114, Figure 4.3, Block Scope

The third code line from the top:

char digit;

should be replaced with:

char digit = 'z';

Page 225, Table 7.1 Overview of Classes and Interfaces

Replace the last row of the table for interfaces with the following two rows:

Entity  Declaration Context Accessibility Modifiers Outer Instance Direct Access to Enclosing Context Defines Static or Non-static Members
Package level interface As package member public or default No N/A Static variables + non-static method prototypes
Top-level nested interface As static class member all No Static variables in enclosing context Static variables + non-static method prototypes

Page 307, Creating and Initializing Strings

In the last sentence at the bottom of the page

"Another common way of ..." delete the word "common".

Page 313, Extracting Substrings

In the middle of the page, the text

"(all characters with values less than the space character)"

should be replaced with:

"(in fact all characters with values less than or equal to the space character, '\u0020')"

Page 319, Appending, Inserting and Deleting Characters in String Buffers

At the bottom of the page, the code lines:

String strBuffer = 4 + "U" + "Only";                                     // (1) "4UOnly"

String str = new StringBuffer().
                 append(4).append("U").append("Only").toString();        // (2)

should be replaced with:

String str1 = 4 + "U" + "Only";                                          // (1) "4UOnly"

String str2 = new StringBuffer().
                  append(4).append("U").append("Only").toString();       // (2)

Page 320, Controlling String Buffer Capacity

The following text:

"One typical use of this method is to compact a string buffer to remove any superfluous capacity:

buffer.setLength(buffer.length()); // Compact the string buffer."

should be replaced with:

"This method does not affect the capacity of the string buffer. One use of this method is to reset the string buffer:

buffer.setLength(0);               // Empty the buffer."

Changes added June 2, 2000.

Page 235, Inheritance and Containment Hierarchy of Non-static Inner Classes

In the second paragraph, the sentence:

"The standard form of the this reference can be used to access the inherited member, as shown at (3)."

should read

"The standard form of the this reference can be used to access the inherited member, as shown at (4)."

Changes added May 23, 2000.

Page 77, Figure 3.3 Parameter Passing: Primitive Data Values

The last statement in the definition of the calcPrice() method should be "return numberOfPizzas * pizzaPrice;".

Page 91, Multidimensional Arrays

Change  the comment "// 4. row (No comma)" to "// 4. row" as any comma at the end of last initializer will be ignored.

Page 141, Review Question 5.4

Change choice (d)

(d) switch expression of type char and case label value of type byte.

to 

(d) switch expression of type char and case label value of type long.

Page 162, Section 5.8 throws Clause

In the first sentence, "... using the throw clause or ..." should read "... using the throw statement or ...".

Page 202, Figure 6.4 Array Types in Inheritance Hierarchy

The label "StackImp" shoud be "StackImpl".

Changes added Mar. 20, 2000.

Page 22, Table 2.1 Keywords in Java

Include the keyword strictfp.

Page 672, Solution to Programming Exercise 5.2

The four occurrences of the method name needAdjust should be replaced with  needAdjustment.

Changes added Mar. 10, 2000.

Page 127, Table 4.4 Summary of Other Modifiers for Members

In the entry for abstract, the sentence "Its class is then implicitly abstract." should be replaced with "Its class must be designated abstract."

Page 226, Section 7.2 Top-level Nested Classes and Interfaces

The sentence

"Nested interfaces can optionally be prefixed with the keyword static and have public accessibility."

should read

"Nested interfaces can optionally be prefixed with the keyword static and can have any accessibility."

Page 289, Waiting and Notifying

The sentence

"If there were several waiting threads, all synchronized on the same object, then the first thread that executed the wait() call is enabled for running."

should read

"If there were several waiting threads, all synchronized on the same object, then some arbitrary thread that executed the wait() call is enabled for running."

Chapter 11 Collections: Page 323, Page 325 (Table 11.2), Page 326 (Figure 11.2), Page 339, Page 345 and Page 349

Replace all eight occurrences of HashTable with Hashtable.

Page 718, Sample Exam Question 53

The three occurrences of the class name Extention should be replaced with Extension in the code.

Changes added Feb. 11, 2000.

Page 207, Reference casting and instanceof Operator

In the second paragraph:

"The result of the instanceof operator at (8) is true" should be "The result of the instanceof operator at (9) is true"

"By the same token, the cast at (9) is also valid." should be "By the same token, the cast at (10) is also valid."

Page 475, Example 15.11 Screen Updating

public class ComponentUpdating extends Applet {

should be 

public class AWTApplet extends Applet {

Page 490, HTML APPLET Element

In the syntax of the APPLET element:

[NAME= names of other applets on this HTML page ]

should read

[NAME= the name assigned to the applet for identification by other applets on this HTML page]

In the syntax of the APPLET element:

<APPLET
...
    [ALT = ...]
[<PARAM NAME ... > ]
>
[<PARAM NAME ... > ]
...

should be:

<APPLET
...
     [ALT = ...]
>
[<PARAM NAME ... > ]
[<PARAM NAME ... > ]
...

Page 491, HTML OBJECT Element

In the syntax of the OBJECT element:

[NAME= names of other applets on this HTML page ]

should read

[NAME= the name assigned to the applet for identification by other applets on this HTML page]

Page 602, Section 19.3 Running javadoc

The sentence

"One way to generate documentation for one or more classes is to issue the javadoc command directory containing the source files."

should read

"One way to generate documentation for one or more classes is to issue the javadoc command in the directory containing the source files."

Page 725 Answer to Sample Exam Question 28

The existing answer should also include (b):

Q 28 (b), (c) and (e)

and the following sentence should be added:

"Since a Foo has a Baz which has a Bar, a Foo has a Bar."

Changes added Feb. 4, 2000.

Page 77, Figure 3.3 Parameter Passing: Primitive Data Values

The labels "Formal Parameters" and "Actual Parameters" should be swapped.

Page 82, Section 3.22 final Parameters

In the second paragraph, "calcPrice" should be "calcPrice()".

In the third paragraph, "calcPrice" should be "calcPrice()".

In the fifth paragraph, "bake" should be "bake()".

Changes added Jan. 26, 2000.

Page 357, Dialog Class

The sentence "A Dialog box is modal by default."

should read    "A Dialog box is non-modal by default."

Page 479, Section 15.7 Organizing Painting and Event Handling

Second line from the top, the sentences:

     "The color of the string is only changed by an event listener at (1) when the user clicks the mouse (Figure 15.5).
      Every other mouse click will make the text visible, because the text color toggles between black and white.
      The latter is the foreground color of the applet."

should be replaced with:

       "The appearance of the string is controlled by an event listener at (1) when the user clicks the mouse (Figure 15.5 ).
         Every other mouse click will make the text visible, because the text is drawn only when the toggle is true."

Page 556, Section 18.3 Byte Streams: Input Streams and Output Streams

The sentence  "Note that the read() methods read a byte, but return an int value."

should read     "Note that the first read() method reads a byte, but returns an int value."

Page 568, Section 18.4 Character Streams: Readers and Writers

The paragraph:

 "Note that the read() methods read an int in the range 0 to 65535 (0x0000–0xFFFF), i.e. a Unicode character. The value –1 is returned if the end of file has been reached."

should read:

 "Note that the read() methods read Unicode characters which are  int values in the range 0 to 65535 (0x0000–0xFFFF). The first method returns the character read as an int. The last two methods return the number of characters read into the char array. The value –1 is returned by all methods if the end of file has been reached."

Changes added prior to Jan. 26, 2000.

Page 12, Review Question 1.4

The lines
    item = new Object();
    Thing entity = new Object();
should read
    item = new Thing();
    Thing entity = new Thing();

Page 40, Programming Exercise 2.2

The line
    RETURN (fahr - 32) * 9 / 5;
should read
    RETURN (fahr - 32) * 5 / 9;
Notice that the code listed in this programming exercise intentionally contains errors. However, this error was unintentional. This error is related to the error on page 667, Solution to Programming Exercise 2.2.

Page 48, Section 3.3 Simple Assignment Operator =, Numeric Type Conversions on Assignment

The line
    byte b = 32;            // int to char, constant in range. No cast required.
should read
    byte b = 32;            // int to byte, constant in range. No cast required.

Page 69, The Shift-left Operator <<

"The sign bit of a char, byte or short value is extended" should be "The sign bit of a byte or short value is extended"

Page 74, Review Question 3.16

"Raises ArrayIndexOutofBoundsException" should be "Raises ArrayIndexOutOfBoundsException" (notice case)

Page 77, Section 3.18 Passing Primitive Data Values

"called from the Customer.main() method" should be "called from the CustomerOne.main() method"

Page 82, Section 3.22 final Parameters

"method bake from Example 3.3" should be "method bake() from Example 3.3"

Page 98, Section 4.3 Defining Methods, Statements

Add the following in the section for statements: "Statements can also be labeled. For example see Section 5.4, p. 145."

Page 101, Section 4.4 Constructors

The following bullet is not true:

"Constructors cannot specify exceptions in the header."

and should be replaced with:

"Constructors can only be called using the new operator."

Page 114, Figure 4.3 Block Scope

The line
        for (int index = 0; index < 10; ++index)        // Block 2
should read
        for (int index = 0; index < 10; ++index) {      // Block 2
and the second block labeled "Block 3" should be labeled "Block 4".

Page 114, Section 4.8 Scope and Accessibility of Members, Block Scope for Local Variables

"at (4) in Block 5" should be "at (4) in Block 4"

Page 118, Section 4.9 Member Accessibility Modifiers, Default Accessibility for Members

"This situation in depicted in Figure 4.6." should be "This situation is depicted in Figure 4.6."

Page 126, Section 4.10 Other Modifiers for Members, transient Variables

"the transient modifier cannot be specified" should be "the transient modifier should not be specified".

Page 130, Review Question 4.28, answer (c)

"int a[] = new a[10]" should read "int a[] = new int[10]"

Page 137, Section 5.2 Selection Statements, switch Statement

Erroneous line-break / paragraph-separator. The text "and finally executing the
<paragraph-separator>
break statement at (5)" should simply be "and finally executing the break statement at (5)"

Page 145, Section 5.3 Iteration Statements, for Statement

"list of declaration statements only." should be "list of expression statements only."

Page 177, Section 6.1 Inheritance, Object-oriented Programming concepts, Upcasting

"length() at (4)" should be "length() at (5)"

Page 196, Example 6.9 Interfaces

The line
    public boolean isFull() { return tos >= stackArray.length; } // (8)
should read
    public boolean isFull() { return tos == stackArray.length-1; }// (8)

Page 200, Review Question 6.15

The lines
    void f() { };
    void g() { };
should read
    public void f() {}
    public void g() {}

Page 219, Example 6.15 Inheritance and Aggregation

In the output from the program, the line
    Stacks are fun to sit on!
should read
    Stacks are fun to sit on!!

Page 326, Figure 11.2 The Core Interfaces and their Implementations

The leftmost box in this figure should be labeled "HashSet", not "Set".

Page 329, Section 11.2 Collections, Iterators

The line
    Iterator iter = c.Iterator();
should read
    Iterator iter = c.iterator();

Page 341, Section 11.6 Sorted Sets and Sorted Maps

The sentence

"The compare() method returns a negative integer, zero or a positive integer if the current object is less than, equal to or greater than the specified object, according to the natural order."

should be

"The compare() method returns a negative integer, zero or a positive integer if the first object is less than, equal to or greater than the second object, according to the total order."

Page 352, Figure 12.1 Partial Inheritance Hierarchy of Components and Containers in AWT

Remove the label "{abstract}", and remove italics from font formatting of label "Container".

Page 355, Container Class

"The abstract class Container" should be "The class Container".

Page 355, Panel Class

The sentence:

"The Panel class is a concrete subclass of the Container class."

should read (the word "concrete" can be deleted):

"The Panel class is a subclass of the Container class."

The sentence:

"A panel is a recursively nested, concrete container that is not a top-level window."

should read (the comma and the word "concrete" can be deleted):

"A panel is a recursively nested container that is not a top-level window."

Page 401, Section 13.7 GridBagLayout Manager, Dimension

"in both directions is one pixel." should be "in both directions is one cell."

Page 415, Section 14.2 The Event Hierarchy, AWTEvent Classes

"mouse movements followed by" should be "mouse movements to position the cursor followed by"

Page 424, Section 14.3 The Event Delegation Model

The second bullet:

"Note that events generated by an event source component are also generated by subclasses of the source component."

should be changed to:

"Note that events generated by an event source component are also generated by subclasses of the source component, unless explicitly inhibited."

In the third bullet "represents different mouse events" should be "represents different key events".

Page 426, Figure 14.3 Event Delegation

There should be no association between the Button class and the QuitHandler class in the figure.

Page 428, Review Question 14.9

Change choice (c):

(c) InputEvent

to:

(c) FocusEvent

Page 442, Table 14.6 Event Masks and Event Processing Methods

All event mask names should be in UPPERCASE.

In addition, the following row:

AWTEvent.Mouse_EVENT_MASK processMouseMotionEvent()

should be changed to (i.e. the text "MOTION_" should be inserted):

AWTEvent.MOUSE_MOTION_EVENT_MASK processMouseMotionEvent()

Page 460, Section 15.3 Rendering Text and Working with Fonts

The following sentence and code:

The Toolkit class provides access to platform-specific information like fonts and screen size. The current toolkit can be used to get a list of names for the available fonts:

    Toolkit currentTK = Toolkit.getDefaultToolkit(); 
    String[] fontNames = currentTK.getFontList();
should be replaced by:

The GraphicsEnvironment class provides access to platform-specific information about fonts. The local GraphicsEnvironment can be used to get a list of names for the available fonts:

    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    String[] fontNames = ge.getAvailableFontFamilyNames();

Page 510, Figure 17, and Page 513, Figure 17.3, and Page 518, Figure 17.5

The label "Container" should be *not* be in italics. Container class is not abstract.

Page 522, JMenuBar

The sentence

"A JMenuBar component is usually attached to a root component using the setMenuBar() method in JRootPane."

should read (the J is missing in the setMenuBar)

"A JMenuBar component is usually attached to a root component using the setJMenuBar() method in JRootPane."

Page 553, Listing Directory Entries

The lines
    String[] list()
    String[] list(FileNameFilter filter)
    File[]   list(FileNameFilter filter)
    File[]   list(FileFilter filter)
should read
    String[] list()
    String[] list(FilenameFilter filter)
    File[]   listFiles()
    File[]   listFiles(FilenameFilter filter)
    File[]   listFiles(FileFilter filter)
The line
    interface FileNameFilter {
should read
    interface FilenameFilter {

Page 638, Solution to Review Question 6.7

The sentences

"The max() method in B will return 29 to the max() method in A. The max() method in A will return 29 to the main() method."

should be

"The max() method in B will return 29 to the max() method in C. The max() method in C will return 29 to the main() method."

Page 642, Solution to Review Question 7.5

"Inner classes cannot contain non-static members" should be "Inner classes can only contain non-static members"

Page 647, Solution to Review Question 9.13

The existing explanation should be changed to the following:

9.13 (a), (b), (c) and (d)

Note that only methods and code blocks can be specified as synchronized. Variables cannot be declared as synchronized. Code blocks can be synchronized on any object.

Page 657, Solution to Review Question 14.14

The sentence

"The actionPerformed() method is called after the button has been clicked."

should be

"The actionPerformed() method is never called: the MyListener object is not registered with the button as an ActionListener using the addActionListener() method."

Page 666, Solution to Programming Exercise 2.1

Remove the blank line after main() method header (line not in the exercise).

Page 667, Solution to Programming Exercise 2.2

The line
        return (fahr - 32) * 9 / 5;
should be
        return (fahr - 32) * 5 / 9;
This error is related to the error on page 40, Programming exercise 2.2.

Add the following comment to main() method header: "// correct method signature".

Add the following comment to f2c() method header: "// Note parameter type".

Page 699, Sample Exam Question 2, (d)

"right operand is equal or greater than 1." should be "right operand is not divisible by 32."

Page 728, Answer to Sample Exam Question 59

The answer "(d)" should be "(a) and (d)".

The sentence "Conversion from int to char requires a cast." should be "The compile-time narrowing of literal converts the int to a char."

Other non-essential changes

Chapter 5 Flow Control and Exception Handling

Replace all mentions of "state diagram" with the more accurate term "activity diagram".