();
By specifying the type stored in the collection, we gain two advantages: ■ ■
Only objects of the appropriate type can be added to the collection. When an object is removed from the collection, its type is already established, avoiding the need to cast it to an appropriate type.
The myStringList object can store only String objects, and the myBookList collection can store only Book objects. Keep in mind that these include objects related to the specified type by inheritance. For example, if a Dictionary class is derived from Book, then we could store a Dictionary object in the myBookList collection. After all, if we’re using inheritance correctly, a Dictionary is a Book.
KeY CONCept Generic classes ensure type compatibility among the objects stored by the collection.
If no specific type is specified when the collection object is created, the collection is defined as containing references of the Object class, which means they can store any type of object. This makes the use of the collections classes consistent with earlier versions of Java that did not include generic specifications. The details of the collection classes and the techniques for defining a generic class go beyond the scope of this book and so are not explored further here. s e L F - r e v iew QuestiONs (see answers in Appendix N)
SR 13.17 What is the Java Collections API? SR 13.18 What is a generic type, and how does it relate to the Java Collections API?
661
662
Chapter 13 Collections
summary of Key Concepts ■
■ ■
■
■
■
■
An object, with its well-defined interface, is a perfect mechanism for implementing a collection. The size of a dynamic data structure grows and shrinks as needed. A dynamically linked list is managed by storing and updating references to objects. Insert and delete operations can be implemented by carefully manipulating object references. Many variations on the implementation of dynamically linked lists can be defined. A queue is a linear data structure that manages data in a first-in, first-out manner. A stack is a linear data structure that manages data in a last-in, first-out manner.
■
A tree is a non-linear data structure that organizes data into a hierarchy.
■
A graph is a non-linear data structure that connects nodes using generic edges.
■
■ ■
The Java Collections API defines several collection classes implemented in various ways. The classes of the Java Collections API are implemented as generic types. Generic classes ensure type compatibility among the objects stored by the collection.
exercises EX 13.1
Suppose current is a reference to a Node object and that it currently refers to a specific node in a linked list. Show, in pseudocode, the steps that would delete the node following current from the list. Carefully consider the cases in which current is referring to the first and last nodes in the list.
EX 13.2
Modify your answer to Exercise 13.1 assuming that the list was set up as a doubly linked list, with both next and prev references.
EX 13.3
Suppose current and newNode are references to Node objects. Assume current currently refers to a specific node in a linked list and newNode refers to an unattached Node object. Show, in pseudocode, the steps that would insert newNode behind current in the list. Carefully consider the cases in which current is referring to the first and last nodes in the list.
Exercises
EX 13.4
Modify your answer to Exercise 13.3 assuming that the list was set up as a doubly linked list, with both next and prev references.
EX 13.5
Would the front and rear references in the header node of a linked list ever refer to the same node? Would they ever both be null? Would one ever be null if the other was not? Explain your answers using examples.
EX 13.6
Show the contents of a queue after the following operations are performed. Assume the queue is initially empty. enqueue(45); enqueue(12); enqueue(28); dequeue(); dequeue(); enqueue(69); enqueue(27); enqueue(99); dequeue(); enqueue(24); enqueue(85); enqueue(16); dequeue();
EX 13.7
In terms of the final state of a queue, does it matter how dequeue operations are intermixed with enqueue operations? Does it matter how the enqueue operations are intermixed among themselves? Explain using examples.
EX 13.8
Show the contents of a stack after the following operations are performed. Assume the stack is initially empty. push(45); push(12); push(28); pop(); pop(); push(69); push(27); push(99); pop(); push(24); push(85); push(16); pop();
663
664
Chapter 13 Collections
EX 13.9
In terms of the final state of a stack, does it matter how the pop operations are intermixed with the push operations? Does it matter how the push operations are intermixed among themselves? Explain using examples.
EX 13.10 Would a tree data structure be a good choice to represent a family tree that shows lineage? Why or why not? Would a binary tree be a better choice? Why or why not? EX 13.11 What data structure would be a good choice to represent the links between various Web sites? Give an example.
programming projects PP 13.1
Consistent with the example from Chapter 8, design and implement an application that maintains a collection of DVDs using a linked list. In the main method of the driver class, add various DVDs to the collection and print the list when complete.
PP 13.2
Modify the MagazineRack program presented in this chapter by adding delete and insert operations into the MagazineList class. Have the Magazine class implement the Comparable interface, and base the processing of the insert method on calls to the compareTo method in the Magazine class that determines whether one Magazine title comes before another alphabetically. In the driver, exercise various insertion and deletion operations. Print the list of magazines when complete.
PP 13.3
Design and implement a version of selection sort (from Chapter 10) that operates on a linked list of nodes that each contain an integer.
PP 13.4
Design and implement a version of insertion sort (from Chapter 10) that operates on a linked list of nodes that each contain an integer.
PP 13.5
Design and implement an application that simulates the customers waiting in line at a bank. Use a queue data structure to represent the line. As customers arrive at the bank, customer objects are put in the rear of the queue with an enqueue operation. When the teller is ready to service another customer, the customer object is removed from the front of the queue with a dequeue operation. Randomly determine when new customers arrive at the bank and when current customers are finished at the teller window. Print a message each time an operation occurs during the simulation.
VideoNote
Developing a solution of PP 13.3.
Programming Projects
PP 13.6
Modify the solution to the PP 13.5 so that it represents eight tellers and therefore eight customer queues. Have new customers go to the shortest queue. Determine which queue had the shortest waiting time per customer on average.
PP 13.7
Design and implement an application that evaluates a postfix expression that operates on integer operands using the arithmetic operators +, −, *, /, and %. We are already familiar with infix expressions, in which an operator is positioned between its two operands. A postfix expression puts the operators after its operands. Keep in mind that an operand could be the result of another operation. This eliminates the need for parentheses to force precedence. For example, the following infix expression: (5 + 2) * (8 − 5) is equivalent to the following postfix expression: 52+85−* The evaluation of a postfix expression is facilitated by using a stack. As you process a postfix expression from left to right, you encounter operands and operators. If you encounter an operand, push it on the stack. If you encounter an operator, pop two operands off the stack, perform the operation, and push the result back on the stack. When you have processed the entire expression, there will be one value on the stack, which is the result of the entire expression. You may want to use a StringTokenizer object to assist in the parsing of the expression. You can assume the expression will be in valid postfix form.
PP 13.8
Design and implement a program that prompts the user to enter a string and then performs two palindrome tests. The first should use a single stack to test whether the string is a palindrome. The second should use two stacks to test whether the string is a palindrome when capitalization, spaces, punctuation, and other non-alphanumeric characters are ignored. The program should print the results of both tests.
PP 13.9
Design and implement a class named StringTree, a binary tree for storing String objects in alphabetic order. Each node in the tree should be represented by a Node class, which stores the string value and pointers to the right and left child nodes. For any node value in the tree, the value of its left child should
665
666
Chapter 13 Collections
come before that value, and the value of its right child should come after that value. The StringTree class should contain both a method for adding strings to the tree and a method for printing the tree’s value in alphabetic order. Write a driver program that reads strings from a file (one per line) and adds them to the tree. After processing the input, print the tree values. PP 13.10
Design and implement an application to support a moderated question-and-answer session in which audience members submit questions to a queue. The question at the front of the queue may be answered by the speaker or panel, and a list of answered or unanswered questions may be retrieved at any time. The program should accept the following simple commands: ‘Q’ will allow an audience member to submit a question, along with their name; ‘A’ will allow the speaker to enter an answer to the question currently at the top of the queue; ‘P’ will allow the speaker to pass on a question, moving it from the front of the queue to the end of the queue; ‘R’ will allow the speaker to mark a question as rejected, removing it from the queue; ‘LA’ will print a numbered list of answered questions, along with the answers; ‘LU’ will print a numbered list of unanswered questions; finally, ‘X’ will print numbered lists of answered and unanswered questions, then exit the program. You should create a Question class to store each question, its answer, and any other question state information. The answered and unanswered queues should be implemented using the java.util.LinkedList class. You must use only the methods in the class that provide Queue functionality: remove the first element, append an element to the end, retrieve the queue size, and iterate over the list.
Glossary
A
abstract—A Java reserved word that serves as a modifier for classes, interfaces, and methods. An abstract class cannot be instantiated and is used to specify bodiless abstract methods that are given definitions by derived classes. Interfaces are inherently abstract.
adaptor class—See listener adaptor class.
abstract class—See abstract.
ADT—See abstract data type.
abstract data type (ADT)—A collection of data and the operations that are defined on that data. An abstract data type might be implemented in a variety of ways, but the interface operations are consistent.
aggregate object—An object that contains variables that are references to other objects. See also has-a relationship.
abstract method—See abstract. Abstract Windowing Toolkit (AWT)—The package in the Java API (java.awt) that contains classes related to graphics and graphical user interfaces. See also Swing. abstraction—The concept of hiding details. If the right details are hidden at the right times, abstraction can significantly help control complexity and focus attention on appropriate issues. access—The ability to reference a variable or invoke a method from outside the class in which it is declared. Controlled by the visibility modifier used to declare the variable or method. Also called the level of encapsulation. See also visibility modifier. access modifier—See visibility modifier. actual parameter—The value passed to a method as a parameter. See also formal parameter.
address—(1) A numeric value that uniquely identifies a particular memory location in a computer’s main memory. (2) A designation that uniquely identifies a computer among all others on a network.
aggregation—Something that is composed, at least in part, of other things. See also aggregate object. algorithm—A step-by-step process for solving a problem. A program is based on one or more algorithms. alias—A reference to an object that is currently also referred to by another reference. Each reference is an alias of the other. analog—A representation that is in direct proportion to the source of the information. See also digital. animation—A series of images or drawings that give the appearance of movement when displayed in order at a particular speed. API—See Application Programming Interface. applet—A Java program that is linked into an HTML document, then retrieved and executed using a Web browser, as opposed to a standalone Java application.
667
668
APPEndix A Glossary
appletviewer—A software tool that interprets and displays Java applets through links in HTML documents. Part of the Java Development Kit. application—(1) A generic term for any program. (2) A Java program that can be run without the use of a Web browser, as opposed to a Java applet. Application Programming Interface (API)—A set of classes that defines services for a programmer. Not part of the language itself, but often relied on to perform even basic tasks. See also class library. arc angle—When defining an arc, the radial distance that defines the arc’s length. See also start angle. architectural design—A high-level design that identifies the large portions of a software system and key data structures. See also detailed design. architecture—See computer architecture. architecture neutral—Not specific to any particular hardware platform. Java code is considered architecture neutral because it is compiled into bytecode and then interpreted on any machine with a Java interpreter. arithmetic operator—An operator that performs a basic arithmetic computation, such as addition or multiplication. arithmetic promotion—The act of promoting the type of a numeric operand to be consistent with the other operand. array—A programming language construct used to store an ordered list of primitive values or objects. Each element in the array is referenced using a numerical index from 0 to N−1, where N is the size of the array. array element—A value or object that is stored in an array.
array element type—The type of the values or objects that are stored in an array. ASCII—A popular character set used by many programming languages. ASCII stands for American Standard Code for Information Interchange. It is a subset of the Unicode character set, which is used by Java. assembly language—A low-level language that uses mnemonics to represent program commands. assignment conversion—Some data types can be converted to another in an assignment statement. See widening conversion. assignment operator—An operator that results in an assignment to a variable. The = operator performs basic assignment. Many other assignment operators perform additional operations prior to the assignment, such as the *= operator. association—A relationship between two classes in which one uses the other or relates to it in some way. See also operator association, use relationship. AWT—See Abstract Windowing Toolkit. background color—(1) The color of the background of a graphical user interface component. (2) The color of the background of an HTML page. See also foreground color. base—The numerical value on which a particular number system is based. It determines the number of digits available in that number system and the place value of each digit in a number. See also binary, decimal, hexadecimal, octal, place value. base 2—See binary. base 8—See octal. base 10—See decimal. base 16—See hexadecimal.
A P P E n d i x A Glossary
base case—The situation that terminates recursive processing, allowing the active recursive methods to begin returning to their point of invocation.
and boundary values of the input. See also white-box testing.
base class—See superclass.
boolean—A Java reserved word representing a logical primitive data type that can only take the values true or false.
behavior—The functional characteristics of an object, defined by its methods. See also identity, state. binary—The base-2 number system. Modern computer systems store information as strings of binary digits (bits). binary operator—An operator that uses two operands. binary search—A searching algorithm that requires that the list be sorted. It repetitively compares the “middle” element of the list to the target value, narrowing the scope of the search each time. See also linear search. binary string—A series of binary digits (bits). binary tree—A tree data structure in which each node can have no more than two child nodes. binding—The process of associating an identifier with the construct that it represents. For example, the process of binding a method name to the specific definition that it invokes. bit—A binary digit, either 0 or 1.
block—A group of programming statements and declarations delimited by braces ({}).
boolean expression—An expression that evaluates to a true or false result, primarily used as conditions in selection and repetition statements. boolean operator—Any of the bitwise operators AND (&), OR (|), or XOR (^) when applied to boolean operands. The results are equivalent to their logical counterparts, except that boolean operators are not short-circuited. border—A graphical edge around a graphical user interface component to enhance its appearance or to group components visually. An empty border creates a buffer of space around a component. bounding rectangle—A rectangle that delineates a region in which an oval or arc is defined. boundary values—The input values corresponding to the edges of equivalence categories. Used in black-box testing.
bit shifting—The act of shifting the bits of a data value to the left or right, losing bits on one end and inserting bits on the other.
bounds checking—The process of determining whether an array index is in bounds, given the size of the array. Java performs automatic bounds checking.
bits per second (bps)—A measurement rate for data transfer devices.
bps—See bits per second.
bitwise operator—An operator that manipulates individual bits of a value, either by calculation or by shifting. black-box testing—Producing and evaluating test cases based on the input and expected output of a software component. The test cases focus on covering the equivalence categories
break—A Java reserved word used to interrupt the flow of control by breaking out of the current loop or switch statement. browser—Software that retrieves HTML documents and other resources across a network and formats them for viewing. A browser is the primary vehicle for accessing the World Wide Web.
669
670
APPEndix A Glossary
bug—A slang term for a defect or error in a computer program.
convert and return a value of one data type into another.
build-and-fix approach—An approach to software development in which a program is created without any significant planning or design, then modified until it reaches some level of acceptance. It is a prevalent, but unwise, approach.
catch—A Java reserved word that is used to specify an exception handler, defined after a try block.
bus—A group of wires in the computer that carry data between components such as the CPU and main memory. button—A graphical user interface component that allows the user to initiate an action, set a condition, or choose an option with a mouse click. There are several kinds of GUI buttons. See also check box, push button, radio button. byte—(1) A unit of binary storage equal to eight bits. (2) A Java reserved word that represents a primitive integer type, stored using eight bits in two’s complement format. byte stream—An I/O stream that manages 8-bit bytes of raw binary data. See also character stream. bytecode—The low-level format into which the Java compiler translates Java source code. The bytecodes are interpreted and executed by the Java interpreter, perhaps after transportation over the Internet. capacity—See storage capacity. case—(1) A Java reserved word that is used to identify each unique option in a switch statement. (2) The orientation of an alphabetic character (uppercase or lowercase). case sensitive—Differentiating between the uppercase and lowercase versions of an alphabetic letter. Java is case sensitive; therefore the identifier total and the identifier Total are considered to be different identifiers. cast—A Java operation expressed using a type or class name in parentheses to explicitly
CD-Recordable (CD-R)—A compact disc on which information can be stored once using a home computer with an appropriate drive. See also CD-Rewritable, CD-ROM. CD-Rewritable (CD-RW)—A compact disc on which information can be stored and rewritten multiple times using a home computer with an appropriate drive. See also CD-Recordable, CD-ROM. CD-ROM—An optical secondary memory medium that stores binary information in a manner similar to a musical compact disc. central processing unit (CPU)—The hardware component that controls the main activity of a computer, including the flow of information and the execution of commands. char—A Java reserved word that represents the primitive character type. All Java characters are members of the Unicode character set and are stored using 16 bits. character font—A specification that defines the distinct look of a character when it is printed or drawn. character set—An ordered list of characters, such as the ASCII or Unicode character sets. Each character corresponds to a specific, unique numeric value within a given character set. A programming language adopts a particular character set to use for character representation and management. character stream—An I/O stream that manages 16-bit Unicode characters. See also byte stream. character string—A series of ordered characters. Represented in Java using the String class and string literals such as "hello".
A P P E n d i x A Glossary
check box—A graphical user interface component that allows the user to set a boolean condition with a mouse click. A check box can be used alone or independently among other check boxes. See also radio button.
coding guidelines—A series of conventions that describe how programs should be constructed. They make programs easier to read, exchange, and integrate. Sometimes referred to as coding standards, especially when they are enforced.
checked exception—A Java exception that must be either caught or explicitly thrown to the calling method. See also unchecked exception.
coding standard—See coding guidelines.
child class—See subclass. class—(1) A Java reserved word used to define a class. (2) The blueprint of an object—the model that defines the variables and methods an object will contain when instantiated. class diagram—A diagram that shows the relationships between classes, including inheritance and use relationships. See also Unified Modeling Language. class hierarchy—A tree-like structure created when classes are derived from other classes through inheritance. See also interface hierarchy. class library—A set of classes that define useful services for a programmer. See also Application Programming Interface. class method—A method that can be invoked using only the class name. An instantiated object is not required as it is with instance methods. Defined in a Java program by using the static reserved word. CLASSPATH—An operating system setting that determines where the Java interpreter searches for class files. class variable—A variable that is shared among all objects of a class. It can also be referenced through the class name, without instantiating any object of that class. Defined in a Java program by using the static reserved word. client-server model—A manner in which to construct a software design based on objects (clients) making use of the services provided by other objects (servers).
cohesion—The strength of the relationship among the parts within a software component. See also coupling. collision—The process of two hash values producing the same hash code. See also hash code, hashing. color chooser—A graphical user interface component, often displayed as a dialog box, that allows the user to select or specify a color. combo box—A graphical user interface component that allows the user to select one of several options. A combo box displays the most recent selection. See also list. command-line arguments—The values that follow the program name on the command line. Accessed within a Java program through the String array parameter to the main method. comment—A programming language construct that allows a programmer to embed humanreadable annotations into the source code. See also documentation. compiler—A program that translates code from one language to equivalent code in another language. The Java compiler translates Java source code into Java bytecode. See also interpreter. compile-time error—Any error that occurs during the compilation process, often indicating that a program does not conform to the language syntax or that an operation was attempted on an inappropriate data type. See also logical error, run-time error, syntax error. component—Any portion of a software system that performs a specific task, transforming input to output. See also GUI component.
671
672
APPEndix A Glossary
computer architecture—The structure and interaction of the hardware components of a computer. concatenation—See string concatenation. condition—A boolean expression used to determine whether the body of a selection or repetition statement should be executed. conditional coverage—A strategy used in white-box testing in which all conditions in a program are executed, producing both true and false results. See also statement coverage. conditional operator—A Java ternary operator that evaluates one of two expressions based on a condition. conditional statement—See selection statement.
CPU—See central processing unit. data stream—An I/O stream that represents a particular source or destination for data, such as a file. See also processing stream. data structure—Any programming construct, either defined in the language or by a programmer, used to organize data into a format to facilitate access and processing. Arrays, linked lists, and stacks can all be considered data structures. data type—A designation that specifies a set of values (which may be infinite). For example, each variable has a data type that specifies the kinds of values that can be stored in it.
const—A Java reserved word that is not currently used.
data transfer device—A hardware component that allows information to be sent between computers, such as a modem.
constant—An identifier that contains a value that cannot be modified. Used to make code more readable and to facilitate changes. Defined in Java using the final modifier.
debugger—A software tool that allows a programmer to step through an executing program and examine the value of variables at any point. See also jdb.
constructor—A special method in a class that is invoked when an object is instantiated from the class. Used to initialize the object.
decimal—The base-10 number system, which humans use in everyday life. See also binary.
container—A Java graphical user interface component that can hold other components. See also containment hierarchy. containment hierarchy—The relationships among graphical components of a user interface. See also container. content pane—The part of a top-level container to which components are added. control characters—See nonprintable characters. controller—Hardware devices that control the interaction between a computer system and a particular kind of peripheral. coupling—The strength of the relationship between two software components. See also cohesion.
default—A Java reserved word that is used to indicate the default case of a switch statement, used if no other cases match. default visibility—The level of access designated when no explicit visibility modifier is used to declare a class, interface, method, or variable. Sometimes referred to as package visibility. Anything declared with default visibility is visible only to classes in the same package. defect testing—Testing designed to uncover errors in a program. delimiter—Any symbol or word used to set the boundaries of a programming language construct, such as the braces ({}) used to define a Java block.
A P P E n d i x A Glossary
deprecated—Something, such as a particular method in the Java API, that is considered outof-favor and should not be used. derived class—See subclass. design—(1) The plan for implementing a program, which includes a specification of the classes and objects used and an expression of the important program algorithms. (2) The process of creating a program design. desk check—A type of review in which a developer carefully examines a design or program to find errors. detailed design—(1) The low-level algorithmic steps of a method. (2) The development stage at which low-level algorithmic steps are determined. development stage—The software life-cycle stage in which a software system is first created, preceding use, maintenance, and eventual retirement. dialog box—A graphical window that pops up to allow brief, specific user interaction. digital—A representation that breaks information down into pieces, which are in turn represented as numbers. All modern computer systems are digital. digitize—The act of converting an analog representation into a digital one by breaking it down into pieces. digraph—A graph data structure in which each edge has a specific direction. dimension—The number of index levels of a particular array. direct recursion—The process of a method invoking itself. See also indirect recursion. disable—Make a graphical user interface component inactive so that it cannot be used. A disabled component is grayed to indicate its disabled status. See also enable.
DNS—See Domain Name System. do—A Java reserved word that represents a repetition construct. A do statement is executed one or more times. See also for, while. documentation—Supplemental information about a program, including comments in a program’s source code and printed reports such as a user’s guide. domain name—The portion of an Internet address that specifies the organization to which the computer belongs. Domain Name System (DNS)—Software that translates an Internet address into an IP address using a domain server. domain server—A file server that maintains a list of Internet addresses and their corresponding IP addresses. double—A Java reserved word that represents a primitive floating point numeric type, stored using 64 bits in IEEE 754 format. doubly linked list—A linked list with two references in each node: one that refers to the next node in the list and one that refers to the previous node in the list. dynamic binding—The process of associating an identifier with its definition during run time. See also binding. dynamic data structure—A set of objects that are linked using references, which can be modified as needed during program execution. editor—A software tool that allows the user to enter and store a file of characters on a computer. Often used by programmers to enter the source code of a program. efficiency—The characteristic of an algorithm that specifies the required number of a particular operation in order to complete its task. For example, the efficiency of a sort can be measured by the number of comparisons required to sort a list. See also order.
673
674
APPEndix A Glossary
element—A value or object stored in another object such as an array. element type—See array element type. else—A Java reserved word that designates the portion of code in an if statement that will be executed if the condition is false. enable—Make a graphical user interface component active so that it can be used. See also disable. encapsulation—The characteristic of an object that limits access to the variables and methods contained in it. All interaction with an object occurs through a well-defined interface that supports a modular design. equality operator—One of two Java operators that returns a boolean result based on whether two values are equal (==) or not equal (!=). equivalence category—A range of functionally equivalent input values as specified by the requirements of the software component. Used when developing black-box test cases. error—(1) Any defect in a design or program. (2) An object that can be thrown and processed by special catch blocks, though usually errors should not be caught. See also compile-time error, exception, logical error, run-time error, syntax error. escape sequence—In Java, a sequence of characters beginning with the backslash character (\), used to indicate a special situation when printing values. For example, the escape sequence \t specifies that a horizontal tab should be printed. exception—(1) A situation that arises during program execution that is erroneous or out of the ordinary. (2) An object that can be thrown and processed by special catch blocks. See also error. exception handler—The code in a catch clause of a try statement, executed when a particular type of exception is thrown.
exception propagation—The process that occurs when an exception is thrown: control returns to each calling method in the stack trace until the exception is caught and handled or until the exception is thrown from the main method, terminating the program. exponent—The portion of a floating point value’s internal representation that specifies how far the decimal point is shifted. See also mantissa. expression—A combination of operators and operands that produce a result. extends—A Java reserved word used to specify the parent class in the definition of a child class. event—(1) A user action, such as a mouse click or key press. (2) An object that represents a user action, to which the program can respond. See also event-driven programming. event-driven programming—An approach to software development in which the program is designed to acknowledge that an event has occurred and to act accordingly. See also event. false—A Java reserved word that serves as one of the two boolean literals (true and false). fetch-decode-execute—The cycle through which the CPU continually obtains instructions from main memory and executes them. FIFO—See first-in, first-out. file—A named collection of data stored on a secondary storage device such as a disk. See also text file. file chooser—A graphical user interface component, usually displayed as a dialog box, that allows the user to select a file from a storage device. file server—A computer in a network, usually with a large secondary storage capacity, that is dedicated to storing software needed by many network users.
A P P E n d i x A Glossary
filtering stream—See processing stream. final—A Java reserved word that serves as a modifier for classes, methods, and variables. A final class cannot be used to derive a new class. A final method cannot be overridden. A final variable is a constant. finalize—A Java method defined in the Object class that can be overridden in any other class. It is called after the object becomes a candidate for garbage collection and before it is destroyed. It can be used to perform “clean-up” activity that is not performed automatically by the garbage collector. finalizer method—A Java method, called finalize, that is called before an object is destroyed. See also finalize. finally—A Java reserved word that designates a block of code to be executed when an exception is thrown, after any appropriate catch handler is processed. first-in, first-out (FIFO)—A data management technique in which the first value that is stored in a data structure is the first value that comes out. See also last-in, first-out; queue. float—A Java reserved word that represents a primitive floating point numeric type, stored using 32 bits in IEEE 754 format. flushing—The process of forcing the contents of the output buffer to be displayed on the output device. font—See character font. for—A Java reserved word that represents a repetition construct. A for statement is executed zero or more times and is usually used when a precise number of iterations is known. foreground color—The color in which any current drawing will be rendered. See also background color.
formal parameter—An identifier that serves as a parameter name in a method. It receives its initial value from the actual parameter passed to it. See also actual parameter. fourth-generation language—A high-level language that provides built-in functionality such as automatic report generation or database management, beyond that of traditional highlevel languages. function—A named group of declarations and programming statements that can be invoked (executed) when needed. A function that is part of a class is called a method. Java has no functions because all code is part of a class. garbage—(1) An unspecified or uninitialized value in a memory location. (2) An object that cannot be accessed anymore because all references to it have been lost. garbage collection—The process of reclaiming unneeded, dynamically allocated memory. Java performs automatic garbage collection of objects that no longer have any valid references to them. gigabyte (GB)—A unit of binary storage, equal to 230 (approximately 1 billion) bytes. goto—(1) A Java reserved word that is not currently used. (2) An unconditional branch. grammar—A representation of language syntax that specifies how reserved words, symbols, and identifiers can be combined into valid programs. graph—A nonlinear data structure made up of nodes and edges that connect the nodes. See also digraph. graphical user interface (GUI)—Software that provides the means to interact with a program or operating system by making use of graphical images and point-and-click mechanisms, such as buttons and text fields.
675
676
APPEndix A Glossary
graphics context—The drawing surface and related coordinate system on which a drawing is rendered or graphical user interface components are placed. GUI component—A visual element, such as a button or text field, that is used to make up a graphical user interface (GUI). hardware—The tangible components of a computer system, such as the keyboard, monitor, and circuit boards. has-a relationship—The relationship between two objects in which one is composed, at least in part, of one or more of the other. See also aggregate object, is-a relationship. hash code—An integer value calculated from any given data value or object, used to determine where a value should be stored in a hash table. Also called a hash value. See also hashing. hash method—A method that calculates a hash code from a data value or object. The same data value or object will always produce the same hash code. Also called a hash function. See also hashing. hash table—A data structure in which values are stored for efficient retrieval. See also hashing. hashing—A technique for storing items so that they can be found efficiently. Items are stored in a hash table at a position specified by a calculated hash code. See also hash method. hexadecimal—The base-16 number system, often used as an abbreviated representation of binary strings. hierarchy—An organizational technique in which items are layered or grouped to reduce complexity. high-level language—A programming language in which each statement represents many machine-level instructions.
HTML—See HyperText Markup Language. hybrid object-oriented language—A programming language that can be used to implement a program in a procedural manner or an objectoriented manner, at the programmer’s discretion. See also pure object-oriented language. hypermedia—The concept of hypertext extended to include other media types such as graphics, audio, video, and programs. hypertext—A document representation that allows a user to easily navigate through it in other than a linear fashion. Links to other parts of the document are embedded at the appropriate places to allow the user to jump from one part of the document to another. See also hypermedia. HyperText Markup Language (HTML)—The notation used to define Web pages. See also browser, World Wide Web. icon—A small, fixed-sized picture, often used to decorate a graphical interface. See also image. identifier—Any name that a programmer makes up to use in a program, such as a class name or variable name. identity—The designation of an object, which, in Java, is an object’s reference name. See also state, behavior. IEEE 754—A standard for representing floating point values. Used by Java to represent float and double data types. if—A Java reserved word that specifies a simple conditional construct. See also else. image—A picture, often specified using the GIF, JPEG, or PING formats. See also icon. immutable—The characteristic of something that does not change. For example, the contents of a Java character string are immutable once the string has been defined.
A P P E n d i x A Glossary
implementation—(1) The process of translating a design into source code. (2) The source code that defines a method, class, abstract data type, or other programming entity. implements—A Java reserved word that is used in a class declaration to specify that the class implements the methods specified in a particular interface. import—A Java reserved word that is used to specify the packages and classes that are used in a particular Java source code file. index—The integer value used to specify a particular element in an array. index operator—The brackets ([]) in which an array index is specified. indirect recursion—The process of a method invoking another method, which eventually results in the original method being invoked again. See also direct recursion. infinite loop—A loop that does not terminate because the condition controlling the loop never becomes false. infinite recursion—A recursive series of invocations that does not terminate because the base case is never reached. infix expression—An expression in which the operators are positioned between the operands on which they work. See also postfix expression. inheritance—The ability to derive a new class from an existing one. Inherited variables and methods of the original (parent) class are available in the new (child) class as if they were declared locally.
inner class—A nonstatic, nested class. input/output buffer—A storage location for data on its way from the user to the computer (input buffer) or from the computer to the user (output buffer). input/output devices—Hardware components that allow the human user to interact with the computer, such as a keyboard, mouse, and monitor. input/output stream—A sequence of bytes that represents a source of data (input stream) or a destination for data (output stream). insertion sort—A sorting algorithm in which each value, one at a time, is inserted into a sorted subset of the entire list. See also selection sort. inspection—See walkthrough. instance—An object created from a class. Multiple objects can be instantiated from a single class. instance method—A method that must be invoked through a particular instance of a class, as opposed to a class method. instance variable—A variable that must be referenced through a particular instance of a class, as opposed to a class variable. instanceof—A Java reserved word that is also an operator, used to determine the class or type of a variable. instantiation—The act of creating an object from a class.
initialize—To give an initial value to a variable.
int—A Java reserved word that represents a primitive integer type, stored using 32 bits in two’s complement format.
initializer list—A comma-separated list of values, delimited by braces ({}), used to initialize and specify the size of an array. inline documentation—Comments that are included in the source code of a program.
integration test—The process of testing software components that are made up of other interacting components. Stresses the communication between components rather than the functionality of individual components.
677
678
APPEndix A Glossary
interface—(1) A Java reserved word that is used to define a set of abstract methods that will be implemented by particular classes. (2) The set of messages to which an object responds, defined by the methods that can be invoked from outside of the object. (3) The techniques through which a human user interacts with a program, often graphically. See also graphical user interface. interface hierarchy—A tree-like structure created when interfaces are derived from other interfaces through inheritance. See also class hierarchy. interpreter—A program that translates and executes code on a particular machine. The Java interpreter translates and executes Java bytecode. See also compiler. Internet—The most pervasive wide-area network in the world; it has become the primary vehicle for computer-to-computer communication. Internet address—A designation that uniquely identifies a particular computer or device on the Internet. invisible component—A graphical user interface component that can be added to a container to provide buffering space between other components. invocation—See method invocation. I/O devices—See input/output devices. IP address—A series of several integer values, separated by periods (.), that uniquely identifies a particular computer or device on the Internet. Each Internet address has a corresponding IP address. is-a relationship—The relationship created through properly derived classes via inheritance. The subclass is-a more specific version of the superclass. See also has-a relationship. ISO-Latin-1—A 128-character extension to the ASCII character set defined by the International
Standards Organization (ISO). The characters correspond to the numeric values 128 through 255 in both ASCII and Unicode. iteration—(1) One execution of the body of a repetition statement. (2) One pass through a cyclic process, such as an iterative development process. iteration statement—See repetition statement. iterative development process—A step-by-step approach for creating software, which contains a series of stages that are performed repetitively. Java Virtual Machine (JVM)—The conceptual device, implemented in software, on which Java bytecode is executed. Bytecode, which is architecture neutral, does not run on a particular hardware platform; instead, it runs on the JVM. java—The Java command-line interpreter, which translates and executes Java bytecode. Part of the Java Development Kit. Java—The programming language used throughout this text to demonstrate software development concepts. Described by its developers as object oriented, robust, secure, architecture neutral, portable, high-performance, interpreted, threaded, and dynamic. Java API—See Interface.
Application
Programming
Java Development Kit (JDK)—A collection of basic software tools, including a compiler and interpreter, for developing Java software. See also Software Development Kit. javac—The Java command-line compiler, which translates Java source code into Java bytecode. Part of the Java Development Kit. javadoc—A software tool that creates external documentation in HTML format about the contents and structure of a Java software system. Part of the Java Development Kit.
A P P E n d i x A Glossary
javah—A software tool that generates C header and source files, used for implementing native methods. Part of the Java Development Kit. javap—A software tool that disassembles a Java class file, containing unreadable bytecode, into a human-readable version. Part of the Java Development Kit. jdb—The Java command-line debugger. Part of the Java Development Kit. JDK—See Java Development Kit. JVM—See Java Virtual Machine. kilobit (Kb)—A unit of binary storage, equal to 210, or 1024 bits. kilobyte (K or KB)—A unit of binary storage, equal to 210, or 1024 bytes. label—(1) A graphical user interface component that displays text, an image, or both. (2) An identifier in Java used to specify a particular line of code. The break and continue statements can jump to a specific, labeled line in the program. LAN—See local-area network. last-in, first-out (LIFO)—A data management technique in which the last value that is stored in a data structure is the first value that comes out. See also first-in, first-out; stack. layout manager—An object that specifies the presentation of graphical user interface components. Each container is governed by a particular layout manager. lexicographic ordering—The ordering of characters and strings based on a particular character set such as Unicode. life cycle—The stages through which a software product is developed and used. LIFO—See last-in, first-out. linear search—A search algorithm in which each item in the list is compared to the target
value until the target is found or the list is exhausted. See also binary search. link—(1) A designation in a hypertext document that “jumps” to a new document (or to a new part of the same document) when followed. (2) A connection between two items in a dynamically linked structure, represented as an object reference. linked list—A dynamic data structure in which objects are linked using references. list—A graphical user interface component that presents a list of items from which the user can choose. The current selection is highlighted in the list. See also combo box. listener—An object that is set up to respond to an event when it occurs. listener adaptor class—A class defined with empty methods corresponding to the methods invoked when particular events occur. A listener object can be derived from an adaptor class. See also listener interface. listener interface—A Java interface that defines the methods invoked when particular events occur. A listener object can be created by implementing a listener interface. See also listener adaptor class. literal—A primitive value used explicitly in a program, such as the numeric literal 147 or the string literal “hello”. local-area network (LAN)—A computer network designed to span short distances and connect a relatively small number of computers. See also wide-area network. local variable—A variable defined within a method, which does not exist except during the execution of the method. logical error—A problem stemming from inappropriate processing in the code. It does not cause an abnormal termination of the program,
679
680
APPEndix A Glossary
but it produces incorrect results. See also compile-time error, run-time error, syntax error. logical line of code—A logical programming statement in a source code program, which may extend over multiple physical lines. See also physical line of code. logical operator—One of the operators that perform a logical NOT (!), AND (&&), or OR (||), returning a boolean result. The logical operators are short-circuited, meaning that if their left operand is sufficient to determine the result, the right operand is not evaluated. long—A Java reserved word that represents a primitive integer type, stored using 64 bits in two’s complement format. loop—See repetition statement. loop control variable—A variable whose value specifically determines how many times a loop body is executed. low-level language—Either machine language or assembly language, which are not as convenient to construct software in as high-level languages are. machine language—The native language of a particular CPU. Any software that runs on a particular CPU must be translated into its machine language. main memory—The volatile hardware storage device where programs and data are held when they are actively needed by the CPU. See also secondary memory. maintenance—(1) The process of fixing errors in or making enhancements to a released software product. (2) The software life-cycle phase in which the software is in use and changes are made to it as needed. mantissa—The portion of a floating point value’s internal representation that specifies the magnitude of the number. See also exponent.
megabyte (MB)—A unit of binary storage, equal to 220 (approximately 1 million) bytes. member—A variable or method in an object or class. memory—Hardware devices that store programs and data. See also main memory, secondary memory. memory location—An individual, addressable cell inside main memory into which data can be stored. memory management—The process of controlling dynamically allocated portions of main memory, especially the act of returning allocated memory when it is no longer required. See also garbage collection. method—A named group of declarations and programming statements that can be invoked (executed) when needed. A method is part of a class. method call conversion—The automatic widening conversion that can occur when a value of one type is passed to a formal parameter of another type. method definition—The specification of the code that gets executed when the method is invoked. The definition includes declarations of local variables and formal parameters. method invocation—A line of code that causes a method to be executed. It specifies any values that are passed to the method as parameters. method overloading—See overloading. mnemonic—(1) A word or identifier that specifies a command or data value in an assembly language. (2) A keyboard character used as a alternative means to activate a graphical user interface component such as a button. modal—Having multiple modes (such as a dialog box). modem—A data transfer device that allows information to be sent along a telephone line.
A P P E n d i x A Glossary
modifier—A designation used in a Java declaration that specifies particular characteristics to the construct being declared.
new—A Java reserved word that is also an operator, used to instantiate an object from a class.
monitor—The screen in the computer system that serves as an output device.
newline character—A nonprintable character that indicates the end of a line.
multidimensional array—An array that uses more than one index to specify a value stored in it.
nonprintable characters—Any character, such as escape or newline, that does not have a symbolic representation that can be displayed on a monitor or printed by a printer. See also printable characters.
multiple inheritance—Deriving a class from more than one parent, inheriting methods and variables from each. Multiple inheritance is not supported in Java. multiplicity—The numeric relationship between two objects, often shown in class diagrams. NaN—An abbreviation that stands for “not a number,” which is the designation for an inappropriate or undefined numeric value. narrowing conversion—A conversion between two values of different but compatible data types. Narrowing conversions could lose information because the converted type usually has an internal representation smaller than the original storage space. See also widening conversion. native—A Java reserved word that serves as a modifier for methods. A native method is implemented in another programming language. natural language—A language that humans use to communicate, such as English or French. negative infinity—A special floating point value that represents the “lowest possible” value. See also positive infinity. nested class—A class declared within another class in order to facilitate implementation and restrict access. nested if statement—An if statement that has as its body another if statement. network—Two or more computers connected together so that they can exchange data and share resources. network address—See address.
nonvolatile—The characteristic of a memory device that retains its stored information even after the power supply is turned off. Secondary memory devices are nonvolatile. See also volatile. null—A Java reserved word that is a reference literal, used to indicate that a reference does not currently refer to any object. number system—A set of values and operations defined by a particular base value that determines the number of digits available and the place value of each digit. object—(1) The primary software construct in the object-oriented paradigm. (2) An encapsulated collection of data variables and methods. (3) An instance of a class. object diagram—A visual representation of the objects in a program at a given point in time, often showing the status of instance data. object-oriented programming—An approach to software design and implementation that is centered around objects and classes. See also procedural programming. octal—The base-8 number system, sometimes used to abbreviate binary strings. See also binary, hexadecimal. off-by-one error—An error caused by a calculation or condition being off by one, such as when a loop is set up to access one too many array elements.
681
682
APPEndix A Glossary
operand—A value on which an operator performs its function. For example, in the expression 5 + 2, the values 5 and 2 are operands.
panel—A graphical user interface (GUI) container that holds and organizes other GUI components.
operating system—The collection of programs that provide the primary user interface to a computer and manage its resources, such as memory and the CPU.
parameter—(1) A value passed from a method invocation to its definition. (2) The identifier in a method definition that accepts the value passed to it when the method is invoked. See also actual parameter, formal parameter.
operator—A symbol that represents a particular operation in a programming language, such as the addition operator (+). operator association—The order in which operators within the same precedence level are evaluated, either right to left or left to right. See also operator precedence.
parameter list—The list of actual or formal parameters to a method. parent class—See superclass.
operator precedence—The order in which operators are evaluated in an expression as specified by a well-defined hierarchy.
pass by reference—The process of passing a reference to a value into a method as the parameter. In Java, all objects are managed using references, so an object’s formal parameter is an alias to the original. See also pass by value. pass by value—The process of making a copy of a value and passing the copy into a method. Therefore, any change made to the value inside the method is not reflected in the original value. All Java primitive types are passed by value.
order—The dominant term in an equation that specifies the efficiency of an algorithm. For example, selection sort is of order n2.
PDL—See Program Design Language. peripheral—Any hardware device other than the CPU or main memory.
overflow—A problem that occurs when a data value grows too large for its storage size, which can result in inaccurate arithmetic processing. See also underflow.
persistence—The ability of an object to stay in existence after the executing program that creates it terminates. See also serialize.
operator overloading—Assigning additional meaning to an operator. Operator overloading is not supported in Java, though method overloading is.
overloading—Assigning additional meaning to a programming language construct, such as a method or operator. Method overloading is supported by Java, but operator overloading is not.
physical line of code—A line in a source code file, terminated by a newline or similar character. See also logical line of code. pixel—A picture element. A digitized picture is made up of many pixels.
overriding—The process of modifying the definition of an inherited method to suit the purposes of the subclass. See also shadowing variables.
place value—The value of each digit position in a number, which determines the overall contribution of that digit to the value. See also number system.
package—A Java reserved word that is used to specify a group of related classes.
pointer—A variable that can hold a memory address. Instead of pointers, Java uses references, which provide essentially the same
package visibility—See default visibility.
A P P E n d i x A Glossary
functionality as pointers but without the need for explicit dereferencing.
primitive data type—A data type that is predefined in a programming language.
point-to-point connection—The link between two networked devices that are connected directly by a wire. polyline—A shape made up of a series of connected line segments. A polyline is similar to a polygon, but the shape is not closed. polymorphism—An object-oriented technique by which a reference that is used to invoke a method can result in different methods being invoked at different times. All Java method invocations are potentially polymorphic in that they invoke the method of the object type, not the reference type. portability—The ability of a program to be moved from one hardware platform to another without having to change it. Because Java bytecode is not related to any particular hardware environment, Java programs are considered portable. See also architecture neutral. positive infinity—A special floating point value that represents the “highest possible” value. See also negative infinity. postfix expression—An expression in which an operator is positioned after the operands on which it works. See also infix expression. postfix operator—In Java, an operator that is positioned behind its single operand, whose evaluation yields the value prior to the operation being performed. Both the increment (++) and decrement (– –) operators can be applied postfix. See also prefix operator. precedence—See operator precedence.
printable characters—Any character that has a symbolic representation that can be displayed on a monitor or printed by a printer. See also nonprintable characters.
prefix operator—In Java, an operator that is positioned in front of its single operand, whose evaluation yields the value after the operation has been performed. Both the increment (++) and decrement (– –) operators can be applied prefix. See also postfix operator.
private—A Java reserved word that serves as a visibility modifier for inner classes as well as methods and variables. A private inner class is accessible only to members of the class in which it is declared. Private methods and variables are visible only in the class in which they are declared. procedural programming—An approach to software design and implementation that is centered around procedures (or functions) and their interaction. See also object-oriented programming. processing stream—An I/O stream that performs some type of manipulation on the data in the stream. Sometimes called a filtering stream. See also data stream. program—A series of instructions executed by hardware, one after another. Program Design Language (PDL)—A language in which a program’s design and algorithms are expressed. See also pseudocode. programming language—A specification of the syntax and semantics of the statements used to create a program. programming language statement—An individual instruction in a given programming language. prompt—A message or symbol used to request information from the user. propagation—See exception propagation. protected—A Java reserved word that serves as a visibility modifier for inner classes as well as methods and variables. A protected inner class
683
684
APPEndix A Glossary
is visible to classes in the same package and to all classes in other packages that extend the class in which it is declared. Protected methods and variables are visible to all classes in the same package and to classes outside the package that extend the class. prototype—A program used to explore an idea or prove the feasibility of a particular approach. pseudocode—Structured and abbreviated natural language used to express the algorithmic steps of a program. See also Program Design Language. pseudorandom number—A value generated by software that performs extensive calculations based on an initial seed value. The result is not truly random because it is based on a calculation, but it is usually random enough for most purposes. public—A Java reserved word that serves as a visibility modifier for classes, interfaces, methods, and variables. Anything declared public is visible to all classes. pure object-oriented language—A programming language that enforces, to some degree, software development using an object-oriented approach. See also hybrid object-oriented language. push button—A graphical user interface component that allows the user to initiate an action with a mouse click. See also check box, radio button. queue—An abstract data type that manages information in a first-in, first-out manner. radio button—A graphical user interface component that allows the user choose one of a set of options with a mouse click. A radio button is useful only as part of a group of other radio buttons. See also check box. RAM—See random access memory.
random access device—A memory device whose information can be directly accessed. See also random access memory, sequential access device. random access memory (RAM)—A term basically interchangeable with main memory. Should probably be called read-write memory, to distinguish it from read-only memory. random number generator—Software that produces a pseudorandom number, generated by calculations based on a seed value. read-only memory (ROM)—Any memory device whose stored information is stored permanently when the device is created. It can be read from, but not written to. recursion—The process of a method invoking itself, either directly or indirectly. Recursive algorithms sometimes provide elegant, though perhaps inefficient, solutions to a problem. reference—A variable that holds of an object. In Java, a reference to interact with an object, but address cannot be accessed, set, on directly.
the address can be used its numeric or operated
register—A small area of storage in the CPU of the computer. relational operator—One of several operators that determine the ordering relationship between two values: less than (<), less than or equal to (<=), greater than (>), and greater than or equal to (>=). See also equality operator. release—A version of a software product that is made available to the customer. repetition statement—A programming construct that allows a set of statements to be executed repetitively as long as a particular condition is true. The body of the repetition statement should eventually make the condition false. Also called an iteration statement or loop. See also do, for, while.
A P P E n d i x A Glossary
requirements—(1) The specification of what a program must and must not do. (2) An early phase of the software development process in which the program requirements are established. reserved word—A word that has special meaning in a programming language and cannot be used for any other purpose. retirement—The phase of a program’s life cycle in which the program is taken out of active use. return—A Java reserved word that causes the flow of program execution to return from a method to the point of invocation. return type—The type of value returned from a method, specified before the method name in the method declaration. Could be void, which indicates that no value is returned. reuse—Using existing software components to create new ones. review—The process of critically examining a design or program to discover errors. There are many types of review. See also desk check, walkthrough. RGB value—A collection of three values that define a color. Each value represents the contribution of the primary colors red, green, and blue. ROM—See read-only memory. run-time error—A problem that occurs during program execution that causes the program to terminate abnormally. See also compile-time error, logical error, syntax error. scope—The areas within a program in which an identifier, such as a variable, can be referenced. See also access. scroll pane—A graphical user interface container that offers a limited view of a component and provides horizontal and/or vertical scroll bars to change that view. SDK—See Software Development Kit.
searching—The process of determining the existence or location of a target value within a list of values. See also binary search, linear search. secondary memory—Hardware storage devices, such as magnetic disks or tapes, which store information in a relatively permanent manner. See also main memory. seed value—A value used by a random number generator as a base for the calculations that produce a pseudo-random number. selection sort—A sorting algorithm in which each value, one at a time, is placed in its final, sorted position. See also insertion sort. selection statement—A programming construct that allows a set of statements to be executed if a particular condition is true. See also if, switch. semantics—The interpretation of a program or programming construct. sentinel value—A specific value used to indicate a special condition, such as the end of input. serialize—The process of converting an object into a linear series of bytes so it can be saved to a file or sent across a network. See also persistence. service methods—Methods in an object that are declared with public visibility and define a service that the object’s client can invoke. shadowing variables—The process of defining a variable in a subclass that supersedes an inherited version. short—A Java reserved word that represents a primitive integer type, stored using 16 bits in two’s complement format. sibling—Two items in a tree or hierarchy, such as a class inheritance hierarchy, that have the same parent. sign bit—A bit in a numeric value that represents the sign (positive or negative) of that value.
685
686
APPEndix A Glossary
signed numeric value—A value that stores a sign (positive or negative). All Java numeric values are signed. A Java character is stored as an unsigned value.
the monitor screen), and standard error (also usually the monitor). See also stream.
signature—The number, types, and order of the parameters of a method. Overloaded methods must each have a unique signature.
state—The state of being of an object, defined by the values of its data. See also behavior, identity.
slider—A graphical user interface component that allows the user to specify a numeric value within a bounded range by moving a knob to the appropriate place in the range.
statement—See programming language statement.
software—(1) Programs and data. (2) The intangible components of a computer system. software component—See component. Software Development Kit (SDK)—A collection of software tools that assist in the development of software. The Java Software Development Kit is another name for the Java Development Kit. software engineering—The discipline within computer science that addresses the process of developing high-quality software within practical constraints. sorting—The process of putting a list of values into a well-defined order. See also insertion sort, selection sort. split pane—A graphical user interface container that displays two components, either side by side or one on top of the other, separated by a moveable divider bar. stack—An abstract data type that manages data in a last-in, first-out manner. stack trace—The series of methods called to reach a certain point in a program. The stack trace can be analyzed when an exception is thrown to assist the programmer in tracking down the problem. standard I/O stream—One of three common I/O streams representing standard input (usually the keyboard), standard output (usually
start angle—When defining an arc, the angle at which the arc begins. See also arc angle.
statement coverage—A strategy used in whitebox testing in which all statements in a program are executed. See also condition coverage. static—A Java reserved word that serves as a modifier for methods and variables. A static method is also called a class method and can be referenced without an instance of the class. A static variable is also called a class variable and is common to all instances of the class. static data structure—A data structure that has a fixed size and cannot grow and shrink as needed. See also dynamic data structure. storage capacity—The total number of bytes that can be stored in a particular memory device. stream—A source of input or a destination for output. strictfp—A Java reserved word that is used to control certain aspects of floating point arithmetic. string—See character string. string concatenation—The process of attaching the beginning of one character string to the end of another, resulting in one longer string. strongly typed language—A programming language in which each variable is associated with a particular data type for the duration of its existence. Variables are not allowed to take on values or be used in operations that are inconsistent with their type.
A P P E n d i x A Glossary
structured programming—An approach to program development in which each software component has one entry and exit point and in which the flow of control does not cross unnecessarily.
process can execute concurrently in a method, unless the method is synchronized, making it a mutually exclusive resource. Methods that access shared data should be synchronized.
stub—A method that simulates the functionality of a particular software component. Often used during unit testing.
syntax rules—The set of specifications that govern how the elements of a programming language can be put together to form valid statements.
subclass—A class derived from another class via inheritance. Also called a derived class or child class. See also superclass.
syntax error—An error produced by the compiler because a program did not conform to the syntax of the programming language. Syntax errors are a subset of compile-time errors. See also compile-time error, logical error, run-time error, syntax rules.
subscript—See index. super—A Java reserved word that is a reference to the parent class of the object making the reference. Often used to invoke a parent’s constructor. super reference—See super. superclass—The class from which another class is derived via inheritance. Also called a base class or parent class. See also subclass. support methods—Methods in an object that are not intended for use outside the class. They provide support functionality for service methods. As such, they are usually not declared with public visibility. swapping—The process of exchanging the values of two variables. swing—The package in the Java API (javax. swing) that contains classes related to graphical user interfaces. Swing provides alternative components than the Abstract Windowing Toolkit package, but does not replace it. switch—A Java reserved word that specifies a compound conditional construct. synchronization—The process of ensuring that data shared among multiple threads cannot be accessed by more than one thread at a time. See also synchronized. synchronized—A Java reserved word that serves as a modifier for methods. Separate threads of a
tabbed pane—A graphical user interface (GUI) container that presents a set of cards from which the user can choose. Each card contains its own GUI components. target value—The value that is sought when performing a search on a collection of data. TCP/IP—Software that controls the movement of messages across the Internet. The acronym stands for Transmission Control Protocol/ Internet Protocol. terabyte (TB)—A unit of binary storage, equal to 240 (approximately 1 trillion) bytes. termination—The point at which a program stops executing. ternary operator—An operator that uses three operands. test case—A set of input values and user actions, along with a specification of the expected output, used to find errors in a system. testing—(1) The process of running a program with various test cases in order to discover problems. (2) The process of critically evaluating a design or program. text area—A graphical user interface component that displays, or allows the user to enter, multiple lines of data.
687
688
APPEndix A Glossary
text field—A graphical user interface component that displays, or allows the user to enter, a single line of data.
try—A Java reserved word that is used to define the context in which certain exceptions will be handled if they are thrown.
text file—A file that contains data formatted as ASCII or Unicode characters. this—A Java reserved word that is a reference to the object executing the code making the reference.
two-dimensional array—An array that uses two indices to specify the location of an element. The two dimensions are often thought of as the rows and columns of a table. See also multidimensional array.
thread—An independent process executing within a program. A Java program can have multiple threads running in a program at one time.
two’s complement—A technique for representing numeric binary data. Used by all Java integer primitive types (byte, short, int, long).
throw—A Java reserved word that is used to start an exception propagation.
type—See data type.
throws—A Java reserved word that specifies that a method may throw a particular type of exception.
unary operator—An operator that uses only one operand.
timer—An object that generates an event at regular intervals. token—A portion of a string defined by a set of delimiters. tool tip—A short line of text that appears when the mouse pointer is allowed to rest on top of a particular component. Usually, tool tips are used to inform the user of the component’s purpose. top-level domain—The last part of a network domain name, such as edu or com. transient—A Java reserved word that serves as a modifier for variables. A transient variable does not contribute to the object’s persistent state and therefore does not need to be saved. See also serialize. tree—A nonlinear data structure that forms a hierarchy stemming from a single root node. true—A Java reserved word that serves as one of the two boolean literals (true and false). truth table—A complete enumeration of all permutations of values involved in a boolean expression, as well as the computed result.
UML—See Unified Modeling Language.
unchecked exception—A Java exception that does not need to be caught or dealt with if the programmer so chooses. underflow—A problem that occurs when a floating point value becomes too small for its storage size, which can result in inaccurate arithmetic processing. See also overflow. Unicode—The international character set used to define valid Java characters. Each character is represented using a 16-bit unsigned numeric value. Unified Modeling Language (UML)—A graphical notation for visualizing relationships among classes and objects. Abbreviated UML. There are many types of UML diagrams. See also class diagrams. uniform resource locator (URL)—A designation for a resource that can be located through a World Wide Web browser. unit test—The process of testing an individual software component. May require the creation of stub modules to simulate other system components.
A P P E n d i x A Glossary
unsigned numeric value—A value that does not store a sign (positive or negative). The bit usually reserved to represent the sign is included in the value, doubling the magnitude of the number that can be stored. Java characters are stored as unsigned numeric values, but there are no primitive numeric types that are unsigned. URL—See uniform resource locator. use relationship—A relationship between two classes, often shown in a class diagram, that establishes that one class uses another in some way, such as relying on its services. See also association. user interface—The manner in which the user interacts with a software system, which is often graphical. See also graphical user interface. variable—An identifier in a program that represents a memory location in which a data value is stored. visibility modifier—A Java modifier that defines the scope in which a construct can be accessed. The Java visibility modifiers are public, protected, private, and default (no modifier used).
walkthrough—A form of review in which a group of developers, managers, and quality assurance personnel examine a design or program in order to find errors. Sometimes referred to as an inspection. See also desk check. WAN—See wide-area network. waterfall model—One of the earliest software development process models. It defines a basically linear interaction between the requirements, design, implementation, and testing stages. Web—See World Wide Web. while—A Java reserved word that represents a repetition construct. A while statement is executed zero or more times. See also do, for. white-box testing—Producing and evaluating test cases based on the interior logic of a software component. The test cases focus on stressing decision points and ensuring coverage. See also black-box testing, condition coverage, statement coverage. white space—Spaces, tabs, and blank lines that are used to set off sections of source code to make programs more readable.
void—A Java reserved word that can be used as a return value for a method, indicating that no value is returned.
wide-area network (WAN)—A computer network that connects two or more local area networks, usually across long geographic distances. See also local-area network.
volatile—(1) A Java reserved word that serves as a modifier for variables. A volatile variable might be changed asynchronously and therefore indicates that the compiler should not attempt optimizations on it. (2) The characteristic of a memory device that loses stored information when the power supply is interrupted. Main memory is a volatile storage device. See also nonvolatile.
widening conversion—A conversion between two values of different but compatible data types. Widening conversions usually leave the data value intact because the converted type has an internal representation equal to or larger than the original storage space. See also narrowing conversion.
von Neumann architecture—The computer architecture named after John von Neumann, in which programs and data are stored together in the same memory devices.
word—A unit of binary storage. The size of a word varies by computer, and is usually two, four, or eight bytes. The word size indicates the amount of information that can be moved through the machine at one time.
689
690
APPEndix A Glossary
World Wide Web (WWW or Web)—Software that makes the exchange of information across a network easier by providing a common user interface for multiple types of information. Web browsers are used to retrieve and format HTML documents.
wrapper class—A class designed to store a primitive type in an object. Usually used when an object reference is needed and a primitive type would not suffice. WWW—See World Wide Web.
Number Systems
B
This appendix contains a detailed introduction to number systems and their underlying characteristics. The particular focus is on the binary number system, its use with computers, and its similarities to other number systems. This introduction also covers conversions between bases. In our everyday lives, we use the decimal number system to represent values, to count, and to perform arithmetic. The decimal system is also referred to as the base-10 number system. We use 10 digits (0 through 9) to represent values in the decimal system. Computers use the binary number system to store and manage information. The binary system, also called the base-2 number system, has only two digits (0 and 1). Each 0 and 1 is called a bit, short for binary digit. A series of bits is called a binary string. There is nothing particularly special about either the binary or decimal systems. Long ago, humans adopted the decimal number system probably because we have 10 fingers on our hands. If humans had 12 fingers, we would probably be using a base-12 number system regularly and find it as easy to deal with as we do the decimal system now. It all depends on what you get used to. As you explore the binary system, it will become more familiar and natural. Binary is used for computer processing because the devices used to manage and store information are less expensive and more reliable if they have to represent only two possible values. Computers have been made that use the decimal system, but they are not as convenient. There are an infinite number of number systems, and they all follow the same basic rules. You already know how the binary number system works, but you just might not be aware that you do. It all goes back to the basic rules of arithmetic.
Place Value In decimal, we represent the values of 0 through 9 using only one digit. To represent any value higher than 9, we must use more than one digit. The position of each digit has a place value that indicates the amount it contributes to the overall value. In decimal, we refer to the one’s column, the ten’s column, the hundred’s column, and so on forever. 691
692
APPendix b Number Systems
Place value:
103
Decimal number: Decimal number:
102
8
101
4
8 * 103
2 +
8 * 1000 +
100
7
4 * 102
+
4 * 100 +
2 * 101 + 7 * 100 = 2 * 10
+ 7 * 1
= 8427
Place values in the decimal system
Figure b . 1
Each place value is determined by the base of the number system, raised to increasing powers as we move from right to left. In the decimal number system, the place value of the digit furthest to the right is 100, or 1. The place value of the next digit is 101, or 10. The place value of the third digit from the right is 102, or 100, and so on. Figure B.1 shows how each digit in a decimal number contributes to the value. The binary system works the same way except that we exhaust the available digits much sooner. We can represent 0 and 1 with a single bit, but to represent any value higher than 1, we must use multiple bits. The place values in binary are determined by increasing powers of the base as we move right to left, just as they are in the decimal system. However, in binary, the base value is 2. Therefore the place value of the bit furthest to the right is 20, or 1. The place value of the next bit is 21, or 2. The place value of the third bit from the right is 22, or 4, and so on. Figure B.2 shows a binary number and its place values. The number 1101 is a valid binary number, but it is also a valid decimal number as well. Sometimes to make it clear which number system is being used, the Place value:
23
22
21
20
Binary number:
1
Decimal number:
1 * 23
+
1 * 22
+
0
* 21
+
1
* 20
=
1 * 8
+
1 * 4
+
0
* 2
+
1
* 1
=
Figure b . 2
1
0
1
Place values in the binary system
13
A P P e n d i x b Number Systems
base value is appended as a subscript to the end of a number. Therefore you can distinguish between 11012, which is equivalent to 13 in decimal, and 110110 (one thousand, one hundred and one), which in binary is represented as 100010011012. A number system with base N has N digits (0 through N−1). As we have seen, the decimal system has 10 digits (0 through 9), and the binary system has two digits (0 and 1). They all work the same way. For instance, the base-5 number system has five digits (0 to 4). Note that, in any number system, the place value of the digit furthest to the right is 1, since any base raised to the zero power is 1. Also notice that the value 10, which we refer to as “ten” in the decimal system, always represents the base value in any number system. In base 10, 10 is one 10 and zero 1’s. In base 2, 10 is one 2 and zero 1’s. In base 5, 10 is one 5 and zero 1’s.
bases Higher Than 10 Since all number systems with base N have N digits, then base 16 has 16 digits. But what are they? We are used to the digits 0 through 9, but in bases higher than 10, we need a single digit, a single symbol, that represents the decimal value 10. In fact, in base 16, which is also called hexadecimal, we need digits that represent the decimal values 10 through 15. For number systems higher than 10, we use alphabetic characters as single digits for values greater than 9. The hexadecimal digits are 0 through F, where 0 through 9 represent the first 10 digits, and A represents the decimal value 10, B represents 11, C represents 12, D represents 13, E represents 14, and F represents 15. Therefore the number 2A8E is a valid hexadecimal number. The place values are determined as they are for decimal and binary, using increasing powers of the base. So in hexadecimal, the place values are powers of 16. Figure B.3 shows how the place values of the hexadecimal number 2A8E contribute to the overall value.
Place value:
163
162
Hexadecimal number:
2
Decimal number:
2 * 163
A
161
8
160
E
+ 10 * 162 + 8 * 161 + 14 * 160 =
2 * 4096 + 10 * 256 + 8 * 16 + 14 * 1 Figure b.3
Place values in the hexadecimal system
= 10893
693
694
APPendix b Number Systems
All number systems with bases greater than 10 use letters as digits. For example, base 12 has the digits 0 through B and base 19 has the digits 0 through I. However, beyond having a different set of digits and a different base, the rules governing each number system are the same. Keep in mind that when we change number systems, we are simply changing the way we represent values, not the values themselves. If you have 1810 pencils, it may be written as 10010 in binary or as 12 in hexadecimal, but it is still the same number of pencils. Figure B.4 shows the representations of the decimal values 0 through 20 in several bases, including base 8, which is also called octal. Note that the larger the base, the higher the value that can be represented in a single digit. Binary (base 2)
Octal (base 8)
Decimal (base 10)
0
0
0
0
1
1
1
1
10
2
2
2
11
3
3
3
100
4
4
4
101
5
5
5
110
6
6
6
111
7
7
7
1000
10
8
8
1001
11
9
9
1010
12
10
A
1011
13
11
B
1100
14
12
C
1101
15
13
D
1110
16
14
E
1111
17
15
F
10000
20
16
10
10001
21
17
11
10010
22
18
12
10011
23
19
13
10100
24
20
14
Figure b . 4
Hexadecimal (base 16)
Counting in various number systems
A P P e n d i x b Number Systems
Conversions We’ve already seen how a number in another base is converted to decimal by determining the place value of each digit and computing the result. This process can be used to convert any number in any base to its equivalent value in base 10. Now let’s reverse the process, converting a base-10 value to another base. First, find the highest place value in the new number system that is less than or equal to the original value. Then divide the original number by that place value to determine the digit that belongs in that position. The remainder is the value that must be represented in the remaining digit positions. Continue this process, position by position, until the entire value is represented. For example, Figure B.5 shows the process of converting the decimal value 180 into binary. The highest place value in binary that is less than or equal to 180 is 128 (or 27), which is the eighth bit position from the right. Dividing 180 by 128 yields 1 with 52 remaining. Therefore the first bit is 1, and the decimal value 52 must be represented in the remaining seven bits. Dividing 52 by 64, which is the next place value (26), yields 0 with 52 remaining. So the second bit is 0. Dividing 52 by 32 yields 1 with 20 remaining. So the third bit is 1, and the remaining five bits must represent the value 20. Dividing 20 by 16 yields 1 with 4 remaining. Dividing 4 by 8 yields 0 with 4 remaining. Dividing 4 by 4 yields 1 with 0 remaining. Since the number has been completely represented, the rest of the bits are zero. Therefore 18010 is equivalent to 10110100 in binary. This can be confirmed by
Place value
Number
Digit
128
180
1
64
52
0
32
52
1
16
20
1
8
4
0
4
4
1
2
0
0
1
0
0
Figure b.5
18010 = 101101002
Converting a decimal value into binary
695
696
APPendix b Number Systems
Place value
Number
Digit
256
1967
7
16
175
A
1
15
F
Figure b.6
196710 = 7AF16
Converting a decimal value into hexadecimal
converting the new binary number back to decimal to make sure we get the original value. This process works to convert any decimal value to any target base. For each target base, the place values and possible digits change. If you start with the correct place value, each division operation will yield a valid digit in the new base. In the example in Figure B.5, the only digits that could have resulted from each division operation would have been 1 or 0, since we were converting to binary. However, when we are converting to other bases, any valid digit in the new base could result. For example, Figure B.6 shows the process of converting the decimal value 1967 into hexadecimal. The place value of 256, which is 162, is the highest place value less than or equal to the original number, since the next highest place value is 163 or 4096. Dividing 1967 by 256 yields 7 with 175 remaining. Dividing 175 by 16 yields 10 with 15 remaining. Remember that 10 in decimal can be represented as the single digit A in hexadecimal. The 15 remaining can be represented as the digit F. Therefore 196710 is equivalent to 7AF in hexadecimal.
Shortcut Conversions We have established techniques for converting any value in any base to its equivalent representation in base 10, and from base 10 to any other base. Therefore. you can now convert a number in any base to any other base by going through base 10. However, an interesting relationship exists between the bases that are powers of 2, such as binary, octal, and hexadecimal, which allows very quick conversions between them. To convert from binary to hexadecimal, for instance, you can simply group the bits of the original value into groups of four, starting from the right, then convert each group of four into a single hexadecimal digit. The example in Figure B.7 demonstrates this process.
A P P e n d i x b Number Systems
101111110110011
101
1111
1011
0011
5
F
B
3
1011111101100112 = 5FB316
5FB3 Figure b.7
Shortcut conversion from binary to hexadecimal 40C6
0100
0000
1100
0110 40C616 = 1000000110001102
100000011000110
Figure b.8
Shortcut conversion from hexadecimal to binary
To go from hexadecimal to binary, we reverse this process, expanding each hexadecimal digit into four binary digits. Note that you may have to add leading zeros to the binary version of each expanded hexadecimal digit if necessary to make four binary digits. Figure B.8 shows the conversion of the hexadecimal value 40C6 to binary. Why do we section the bits into groups of four when converting from binary to hexadecimal? The shortcut conversions work between binary and any base that is a power of 2. We section the bits into groups of that power. Since 24 = 16, we section the bits in groups of four. Converting from binary to octal is the same process except that the bits are sectioned into groups of three, since 23 = 8. Likewise, when converting from octal to binary, we expand each octal digit into three bits. To convert between, say, hexadecimal and octal is now a process of doing two shortcut conversions. First convert from hexadecimal to binary, then take that result and perform a shortcut conversion from binary to octal. By the way, these types of shortcut conversions can be performed between any base B and any base that is a power of B. For example, conversions between base 3 and base 9 can be accomplished using the shortcut grouping technique, sectioning or expanding digits into groups of two, since 32 = 9.
697
This page is intentionally left blank.
The Unicode Character Set
C
The Java programming language uses the Unicode character set for managing text. A character set is simply an ordered list of characters, each corresponding to a particular numeric value. Unicode is an international character set that contains letters, symbols, and ideograms for languages all over the world. Each character is represented as a 16-bit unsigned numeric value. Unicode, therefore, can support over 65,000 unique characters. Only about half of those values have characters assigned to them at this point. The Unicode character set continues to be refined as characters from various languages are included. Many programming languages still use the ASCII character set. ASCII stands for the American Standard Code for Information Interchange. The 8-bit extended ASCII set is quite small, so the developers of Java opted to use Unicode in order to support international users. However, ASCII is essentially a subset of Unicode, including corresponding numeric values, so programmers used to ASCII should have no problems with Unicode. Figure C.1 shows a list of commonly used characters and their Unicode numeric values. These characters also happen to be ASCII characters. All of the characters in Figure C.1 are called printable characters because they have a symbolic representation that can be displayed on a monitor or printed by a printer. Other characters are called nonprintable characters because they have no such symbolic representation. Note that the space character (numeric value 32) is considered a printable character, even though no symbol is printed when it is displayed. Nonprintable characters are sometimes called control characters because many of them can be generated by holding down the control key on a keyboard and pressing another key. The Unicode characters with numeric values 0 through 31 are nonprintable characters. Also, the delete character, with numeric value 127, is a nonprintable
699
700
APPendix C The Unicode Character Set
Value
Char
Value
Char
Value
Char
Value
Char
Value
Char
32
space
51
3
70
F
89
Y
108
l
33
!
52
4
71
G
90
Z
109
m
34
"
53
5
72
H
91
[
110
n
35
#
54
6
73
I
92
\
111
o
36
$
55
7
74
J
93
]
112
p
37
%
56
8
75
K
94
ˆ
113
q
38
&
57
9
76
L
95
–
114
r
39
'
58
:
77
M
96
'
115
s
40
(
59
;
78
N
97
a
116
t
41
)
60
<
79
O
98
b
117
u
42
*
61
=
80
P
99
c
118
v
43
+
62
>
81
Q
100
d
119
w
44
'
63
?
82
R
101
e
120
x
45
–
64
@
83
S
102
f
121
y
46
.
65
A
84
T
103
g
122
z
47
/
66
B
85
U
104
h
123
{
48
0
67
C
86
V
105
i
124
|
49
1
68
D
87
W
106
j
125
}
50
2
69
E
88
X
107
k
126
~
Figure C.1
A small portion of the Unicode character set
character. All of these characters are ASCII characters as well. Many of them have fairly common and well-defined uses, while others are more general. The table in Figure C.2 lists a small sample of the nonprintable characters. Nonprintable characters are used in many situations to represent special conditions. For example, certain nonprintable characters can be stored in a text document to indicate, among other things, the beginning of a new line. An editor will process these characters by starting the text that follows it on a new line, instead of printing a symbol to the screen. Various types of computer systems use different nonprintable characters to represent particular conditions. Except for having no visible representation, nonprintable characters are essentially equivalent to printable characters. They can be stored in a Java character variable and be part of a character string. They are stored using 16 bits, can be converted to their numeric value, and can be compared using relational operators.
A P P e n d i x C The Unicode Character Set
Value
Figure C.2
Character
0
null
7
bell
8
backspace
9
tab
10
line feed
12
form feed
13
carriage return
27
escape
127
delete
Some nonprintable characters in the Unicode character set
The first 128 characters of the Unicode character set correspond to the common ASCII character set. The first 256 characters correspond to the ISO-Latin-1 extended ASCII character set. Many operating systems and Web browsers will handle these characters, but they may not be able to print the other Unicode characters. The Unicode character set contains most alphabets in use today, including Greek, Hebrew, Cyrillic, and various Asian ideographs. It also includes Braille, and several sets of symbols used in mathematics and music. Figure C.3 shows a few characters from non-Western alphabets.
Value
Character
Source
1071
Russian (Cyrillic)
3593
Thai
5098
Cherokee
8478
Letterlike Symbols
8652
Arrows
10287
Braille
13407
Chinese/Japanese/Korean (Common)
Figure C.3
Some non-Western characters in the Unicode character set
701
This page is intentionally left blank.
Java Operators
D
Java operators are evaluated according to the precedence hierarchy shown in Figure D.1 Operators at low precedence levels are evaluated before operators at higher levels. Operators within the same precedence level are evaluated according to the specified association, either right to left (R to L) or left to right (L to R). Operators in the same precedence level are not listed in any particular order. The order of operator evaluation can always be forced by the use of parentheses. It is often a good idea to use parentheses even when they are not required, to make it explicitly clear to a human reader how an expression is evaluated. For some operators, the operand types determine which operation is carried out. For instance, if the + operator is used on two strings, string concatenation is performed, but if it is applied to two numeric types, they are added in the arithmetic sense. If only one of the operands is a string, the other is converted to a string, and string concatenation is performed. Similarly, the operators &, ^, and | perform bitwise operations on numeric operands but boolean operations on boolean operands. The boolean operators & and | differ from the logical operators && and || in a subtle way. The logical operators are “short-circuited” in that if the result of an expression can be determined by evaluating only the left operand, the right operand is not evaluated. The boolean versions always evaluate both sides of the expression. There is no logical operator that performs an exclusive OR (XOR) operation.
Java Bitwise Operators The Java bitwise operators operate on individual bits within a primitive value. They are defined only for integers and characters. They are unique among all Java operators, because they let us work at the lowest level of binary storage. Figure D.2 lists the Java bitwise operators. Three of the bitwise operators are similar to the logical operators !, &&, and ||. The bitwise NOT, AND, and OR operations work basically the same way as their logical counterparts, except they work on individual bits of a value. The 703
704
APPendix d Java Operators
Precedence Level
Operator
1
[]
. (parameters) ++ --
Operation
Associates
array indexing object member reference parameter evaluation and method invocation postfix increment postfix decrement
L to R
prefix increment prefix decrement unary plus unary minus bitwise NOT logical NOT
R to L
object instantiation cast
R to L
2
++ -+ ~ !
3
new (type)
4
* / %
multiplication division remainder
L to R
5
+ + -
addition string concatenation subtraction
L to R
6
<< >> >>>
left shift right shift with sign right shift with zero
L to R
less than less than or equal greater than greater than or equal type comparison
L to R
equal not equal
L to R
& &
bitwise AND boolean AND
L to R
10
ˆ ˆ
bitwise XOR boolean XOR
L to R
11
| |
bitwise OR boolean OR
L to R
12
&&
logical AND
L to R
13
||
logical OR
L to R
7
< <= > >= instanceof
8
== !=
9
Fig u r e d . 1
Java operator precedence
A P P e n d i x d Java Operators
Precedence Level
Operator
14
?:
15
= += += -= *= /= %= <<= >>= >>>= &= &= ˆ= ˆ= |= |=
Operation
Figure d.1
Associates
conditional operator
R to L
assignment addition, then assignment string concatenation, then assignment subtraction, then assignment multiplication, then assignment division, then assignment remainder, then assignment left shift, then assignment right shift (sign), then assignment right shift (zero), then assignment bitwise AND, then assignment boolean AND, then assignment bitwise XOR, then assignment boolean XOR, then assignment bitwise OR, then assignment boolean OR, then assignment
R to L
Java operator precedence, continued
rules are essentially the same. Figure D.3 shows the results of bitwise operators on all combinations of two bits. Compare this chart to the truth tables for the logical operators in Chapter 5 to see the similarities. The bitwise operators include the XOR operator, which stands for exclusive OR. The logical || operator is an inclusive OR operation, which means it returns true if both operands are true. The | bitwise operator is also inclusive and yields a
Operator
Description
~
bitwise NOT
&
bitwise AND
|
bitwise OR
ˆ
bitwise XOR
<<
left shift
>>
right shift with sign
>>>
Figure d.2
right shift with zero fill
Java bitwise operators
705
706
APPendix d Java Operators
b
~ a
a & b
a | b
0
0
1
0
0
0
0
1
1
0
1
1
1
0
0
0
1
1
1
1
0
1
1
0
Figure d . 3
a
ˆb
a
Bitwise operations on individual bits
1 if both corresponding bits are 1. However, the exclusive OR operator (^) yields a 0 if both operands are 1. There is no logical exclusive OR operator in Java. When the bitwise operators are applied to integer values, the operation is performed individually on each bit in the value. For example, suppose the integer variable number is declared to be of type byte and currently holds the value 45. Stored as an 8-bit byte, it is represented in binary as 00101101. When the bitwise complement operator (~) is applied to number, each bit in the value is inverted, yielding 11010010. Since integers are stored using two’s complement representation, the value represented is now negative, specifically −46. Similarly, for all bitwise operators, the operations are applied bit by bit, which is where the term “bitwise” comes from. For binary operators (with two operands), the operations are applied to corresponding bits in each operand. For example, assume num1 and num2 are byte integers, num1 holds the value 45, and num2 holds the value 14. Figure D.4 shows the results of several bitwise operations. The operators &, |, and ^ can also be applied to boolean values, and they have basically the same meaning as their logical counterparts. When used with boolean values, they are called boolean operators. However, unlike the operators && and ||, which are “short-circuited,” the boolean operators are not short-circuited. Both sides of the expression are evaluated every time.
num1 | num2
00101101
00101101
00101101
& 00001110
| 00001110
ˆ 00001110
= 00001100
= 00101111
= 00100011
Figu r e d . 4
num1
ˆ num2
num1 & num2
Bitwise operations on bytes
A P P e n d i x d Java Operators
Like the other bitwise operators, the three bitwise shift operators manipulate the individual bits of an integer value. They all take two operands. The left operand is the value whose bits are shifted; the right operand specifies how many positions they should move. Prior to performing a shift, byte and short values are promoted to int for all shift operators. Furthermore, if either of the operands is long, the other operand is promoted to long. For readability, we use only 16 bits in the examples in this section, but the concepts are the same when carried out to 32- or 64-bit strings. When bits are shifted, some bits are lost off one end, and others need to be filled in on the other. The left-shift operator (<<) shifts bits to the left, filling the right bits with zeros. For example, if the integer variable number currently has the value 13, then the statement number = number << 2;
stores the value 52 into number. Initially, number contains the bit string 0000000000001101. When shifted to the left, the value becomes 0000000000110100, or 52. Notice that for each position shifted to the left, the original value is multiplied by 2. The sign bit of a number is shifted along with all of the others. Therefore the sign of the value could change if enough bits are shifted to change the sign bit. For example, the value −8 is stored in binary two’s complement form as 1111111111111000. When shifted left two positions, it becomes 1111111111100000, which is −32. However, if enough positions are shifted, a negative number can become positive and vice versa. There are two forms of the right-shift operator: one that preserves the sign of the original value (>>) and one that fills the leftmost bits with zeros (>>>). Let’s examine two examples of the right-shift-with-sign-fill operator. If the int variable number currently has the value 39, the expression (number >> 2) results in the value 9. The original bit string stored in number is 0000000000100111, and the result of a right shift two positions is 0000000000001001. The leftmost sign bit, which in this case is a zero, is used to fill from the left. If number has an original value of −16, or 1111111111110000, the rightshift (with sign fill) expression (number >> 3) results in the binary string 1111111111111110, or −2. The leftmost sign bit is a 1 in this case and is used to fill in the new left bits, maintaining the sign. If maintaining the sign is not desirable, the right-shift-with-zero-fill operator (>>>) can be used. It operates similarly to the >> operator but fills with zero no matter what the sign of the original value is.
707
This page is intentionally left blank.
E
Java Modifiers
This appendix summarizes the modifiers that give particular characteristics to Java classes, interfaces, methods, and variables. For discussion purposes, the set of all Java modifiers is divided into two groups: visibility modifiers and all others.
Java Visibility Modifiers The table in Figure E.1 describes the effect of Java visibility modifiers on various constructs. Visibility modifiers operate in the same way on classes and interfaces and in the same way on methods and variables. Default visibility means that no visibility modifier was explicitly used. Default visibility is sometimes called package visibility, but you cannot use the reserved word package as a modifier. Note that only inner classes can have private or protected visibility.
Modifier default (no modifier)
Classes and interfaces
Methods and variables
Visible in its package.
Visible to any class in the same package as its class.
public
Visible anywhere.
Visible anywhere.
protected
Can only be applied to inner classes. Visible in its package and to classes that extend the class in which it is declared.
Visible to any class in the same package and to any derived classes.
private
Can only be applied to inner classes. Visible to the enclosing class only.
Not visible by any other class.
Figure e.1
Java visibility modifiers
709
710
APPendix e Java Modifiers
A Visibility example Consider the highly contrived situation depicted in the Figure E.2 Class P is the parent class that is used to derive child classes C1 and C2. Class C1 is in the same package as P, but C2 is not. Class P contains four methods, each with different visibility modifiers. One object has been instantiated from each of these classes. The public method a() has been inherited by C1 and C2, and any code with access to object x can invoke x.a(). The private method d() is not visible to C1 or C2, so objects y and z have no such method available to them. Furthermore, d() is fully encapsulated and can be invoked only from within object x. The protected method b() is visible in both C1 and C2. A method in y could invoke x.b(), but a method in z could not. Furthermore, an object of any class in package One could invoke x.b(), even those that are not related to class P by inheritance, such as an object created from class Another1. Method c() has default visibility, since no visibility modifier was used to declare it. Therefore object y can refer to the method c() as if it were declared locally, but object z cannot. Object y can invoke x.c(), as can an object instantiated from any class in package One, such as Another1. Object z cannot invoke x.c(). These rules generalize in the same way for variables. The visibility rules may appear complicated initially, but they can be mastered with a little effort.
package One class P P x = new P();
public a() protected b() c() private d()
C1 y = new C1(); C2 z = new C2();
class Another1 package Two class C1
class C2 class Another2
Figure e.2
A situation demonstrating Java visibility modifiers
A P P e n d i x e Java Modifiers
Other Java Modifiers Figure E.3 summarizes the rest of the Java modifiers, which address a variety of issues. Furthermore, a modifier has different effects on classes, interfaces, methods, and variables. Some modifiers cannot be used with certain constructs and therefore are listed as not applicable (N/A). The transient modifier is used to indicate data that need not be stored in a persistent (serialized) object. That is, when an object is written to a serialized stream, the object representation will include all data that is not specified as transient.
Modifier
Class
abstract The class may contain abstract methods. It cannot be instantiated.
Interface All interfaces are inherently abstract. The modifier is optional.
Method
Variable
No method body is defined. The method requires implementation when inherited.
N/A
The class cannot be N/A used to drive new classes.
The method cannot be overridden.
The variable is a constant, whose value cannot be changed once initially set.
native
N/A
N/A
No method body is necessary since implementation is in another language.
N/A
static
N/A
N/A
Defines a class method. It does not require an instantiated object to be invoked. It cannot reference nonstatic methods or variables. It is implicitly final.
Defines a class variable. It does not require an instantiated object to be referenced. It is shared (common memory space) among all instances of the class.
synchronized
N/A
N/A
The execution of the method is mutually exclusive among all threads.
N/A
transient N/A
N/A
N/A
The variable will not be serialized.
volatile
N/A
N/A
The variable is changed asynchronously. The compiler should not perform optimizations on it.
final
N/A
Figure e.3
The rest of the Java modifiers
711
This page is intentionally left blank.
Java Coding Guidelines
F
This appendix contains a series of guidelines that describe how to organize and format Java source code. They are designed to make programs easier to read and maintain. Some guidelines can be attributed to personal preferences and could be modified. However, it is important to have a standard set of practices that make sense and to follow them carefully. The guidelines presented here are followed in the example code throughout the text and are consistent with the Java naming conventions. Consistency is half the battle. If you follow the same rules throughout a program and follow them from one program to another, you make the effort of reading and understanding your code easier for yourself and others. It is not unusual for a programmer to develop software that seems straightforward at the time, only to revisit it months later and have difficulty remembering how it works. If you follow consistent development guidelines, you reduce this problem considerably. When an organization adopts a coding standard, it is easier for people to work together. A software product is often created by a team of cooperating developers, each responsible for a piece of the system. If they all follow the same development guidelines, they facilitate the process of integrating the separate pieces into one cohesive entity. You may have to make tradeoffs between some guidelines. For example, you may be asked to make all of your identifiers easy to read yet keep them to a reasonably short length. Use common sense on a case-by-case basis to embrace the spirit of all guidelines as much as possible. You may choose, or be asked, to follow this set of guidelines as presented. If changes or additions are made, make sure they are clear and that they represent a conscious effort to use good programming practices. Most of these issues are discussed further in appropriate areas of the text but are presented succinctly here, without elaboration.
713
714
APPendix F Java Coding Guidelines
design Guidelines A. Design Preparation 1. The ultimate guideline is to develop a clean design. Think before you start coding. A working program is not necessarily a good program. 2. Express and document your design with consistent, clear notation. B. Structured Programming 1. Do not use the continue statement. 2. Use the break statement only to terminate cases of a switch statement. 3. Have only one return statement in a method as the last line, unless it unnecessarily complicates the method. C. Classes and Packages 1. Do not have additional methods in the class that contains the main method. 2. Define the class that contains the main method at the top of the file it is in, followed by other classes if appropriate. 3. If only one class is used from an imported package, import that class by name. If two or more are imported, use the * symbol. D. Modifiers 1. Do not declare variables with public visibility. 2. Do not use modifiers inside an interface. 3. Always use the most appropriate modifiers for each situation. For example, if a variable is used as a constant, explicitly declare it as a constant using the final modifier. E. Exceptions 1. Use exception handling only for truly exceptional conditions, such as terminating errors, or for significantly unusual or important situations. 2. Do not use exceptions to disguise or hide inappropriate processing. 3. Handle each exception at the appropriate level of design. F. Miscellaneous 1. Use constants instead of literals in almost all situations. 2. Design methods so that they perform one logical function. As such, the length of a method will tend to be no longer than 50 lines of code, and usually much shorter. 3. Keep the physical lines of a source code file to less than 80 characters in length. 4. Extend a logical line of code over two or more physical lines only when necessary. Divide the line at a logical place.
A P P e n d i x F Java Coding Guidelines
Style Guidelines A. Identifier Naming 1. Give identifiers semantic meaning. For example, do not use single letter names such as a or i unless the single letter has semantic meaning. 2. Make identifiers easy to read. For example, use currentValue instead of curval. 3. Keep identifiers to a reasonably short length. 4. Use the underscore character to separate words of a constant. B. Identifier Case 1. Use UPPERCASE for constants. 2. Use Title Case for class, package, and interface names. 3. Use lowercase for variable and method names, except for the first letter of each word other than the first word. For example, minTaxRate. Note that all reserved words must be lowercase. C. Indentation 1. Indent the code in any block by three or four spaces (be consistent). 2. If the body of a loop, if statement, or else clause is a single statement (not a block), indent the statement three spaces on its own line. 3. Put the left brace ({) starting each new block on a new line. Line up the terminating right brace (}) with the opening left brace. For example: while (value < 25) { value += 5; System.out.println ("The value is " + value); }
4. In a switch statement, indent each case label three spaces. Indent all code associated with a case three additional spaces. D. Spacing 1. Carefully use white space to draw attention to appropriate features of a program. 2. Put one space after each comma in a parameter list. 3. Put one space on either side of a binary operator. 4. Do not put spaces immediately after a left parenthesis or before a right parenthesis. 5. Do not put spaces before a semicolon. 6. Put one space before a left parenthesis, except before an empty parameter list.
715
716
APPendix F Java Coding Guidelines
7. When declaring arrays, associate the brackets with the element type, as opposed to the array name, so that it applies to all variables on that line. For example: int[30] list1, list2;
8. When referring to the type of an array, do not put any spaces between the element type and the square brackets, such as int[]. E. Messages and Prompts 1. 2. 3. 4. 5.
Do not condescend. Do not attempt to be humorous. Be informative, but succinct. Define specific input options in prompts when appropriate. Specify default selections in prompts when appropriate.
F. Output 1. Label all output clearly. 2. Present information to the user in a consistent manner.
documentation Guidelines A. The Reader 1. Write all documentation as though the reader is computer literate and basically familiar with the Java language. 2. Assume the reader knows almost nothing about what the program is supposed to do. 3. Remember that a section of code that seems intuitive to you when you write it might not seem so to another reader or to yourself later. Document accordingly. B. Content 1. Make sure comments are accurate. 2. Keep comments updated as changes are made to the code. 3. Be concise but thorough. C. Header Blocks 1. Every source code file should contain a header block of documentation providing basic information about the contents and the author. 2. Each class and interface, and each method in a class, should have a small header block that describes its role. 3. Each header block of documentation should have a distinct delimiter on the top and bottom so that the reader can visually scan from one construct to the next easily. For example:
A P P e n d i x F Java Coding Guidelines
//***************************************** // header block //*****************************************
D. In-Line Comments 1. Use in-line documentation as appropriate to clearly describe interesting processing. 2. Put a comment on the same line with code only if the comment applies to one line of code and can fit conveniently on that line. Otherwise, put the comment on a separate line above the line or section of code to which it applies. E. Miscellaneous 1. Avoid the use of the /* */ style of comment except to conform to the javadoc (/** */) commenting convention. 2. Don’t wait until a program is finished to insert documentation. As pieces of your system are completed, comment them appropriately.
717
This page is intentionally left blank.
Java Applets
G
In Chapter 2 we presented the basic concept of an applet, including how an applet differs from an application and how an applet is referenced in an HTML page so that it can be executed in a browser. The applet examples in Chapter 2 present simple drawings. We revisited the concept of an applet in Chapter 9, exploring how applets are a good example of inheritance. This appendix fills in some other details about Java applets. The example applets in Chapter 2 override the paint method of the JApplet class. An applet has several other methods that perform specific duties. Because an applet is designed to work with Web pages, some applet methods are specifically designed with that concept in mind. Figure G.1 lists several applet methods.
public void init()
Initializes the applet. Called just af ter the applet is loaded. public void start()
Starts the applet. Called just af ter the applet is made active. public void stop()
Stops the applet. Called just af ter the applet is made inactiv e. public void destroy()
Destroys the applet. Called when the br owser is exited. public URL getCodeBase()
Returns the URL at which this applet's bytecode is located. public URL getDocumentBase()
Returns the URL at which the HTML document containing this applet is locat ed. public AudioClip getAudioClip(URL url, String name)
Retrieves an audio clip from the specified URL. public Image getImage(URL url, String name)
Retrieves an image from the specified URL.
Figure g.1
Some methods of the Applet class 719
720
APPendix g Java Applets
The init method is executed once when the applet is first loaded, such as when the browser or appletviewer initially views the applet. Therefore the init method is the place to initialize the applet’s environment and permanent data. The start and stop methods of an applet are called when the applet becomes active or inactive, respectively. For example, after we use a browser to initially load an applet, the applet’s start method is called. We may then leave that page to visit another one, at which point the applet becomes inactive and the stop method is called. If we return to the applet’s page, the applet becomes active again and the start method is called again. Note that the init method is called once when the applet is loaded, but start may be called several times as the page is revisited. It is good practice to implement start and stop for an applet if it actively uses CPU time, such as when it is showing an animation, so that CPU time is not wasted on an applet that is not visible. Also note that reloading the Web page in the browser does not necessarily reload the applet. To force the applet to reload, most browsers provide some key combination for that purpose. For example, in Netscape Navigator, holding down the Shift key while clicking the Reload button with the mouse not only reloads the Web page but also reloads (and reinitializes) all applets linked to that page. The getCodeBase and getDocumentBase methods are useful to determine where the applet’s bytecode or HTML document resides. An applet could use the appropriate URL to retrieve additional resources, such as an image or audio clip by using the applet methods getImage or getAudioClip, respectively. Security is an issue with applets. As you browse Web pages, you may open a page containing an applet, and suddenly an unknown program is executing on your machine. Because of the dangers inherent in that process, applets are restricted in the kinds of operations they can perform. For instance, an applet cannot write data to a local drive. In the Graphics Track sections throughout this book, we explore issues related to the development of programs that use graphical user interfaces (GUIs). The examples in those sections are presented as Java applications, using JFrame components as the primary heavyweight container. An applet can also be used to present GUI-based programs. Like a JFrame, a JApplet is a heavyweight container. Applets are useful for small, isolated programs, such as a game or calculator. Because of their security restrictions and processing overhead, they are not frequently used for larger systems. Generally, other technologies are used to support fully integrated, dynamic Web sites.
Regular Expressions
H
Throughout the book we’ve used the Scanner class to read interactive input from the user and parse strings into individual tokens such as words. In Chapter 5 we also used it to read input from a data file. Usually we used the default whitespace delimiters for tokens in the scanner input. The Scanner class can also be used to parse its input according to a regular expression, which is a character string that represents a pattern. A regular expression can be used to set the delimiters used when extracting tokens, or it can be used in methods like findInLine to match a particular string. Some of the general rules for constructing regular expressions include: ■ ■
■
■
■
The dot (.) character matches any single character. The * character, which is called the Kleene star, matches zero or more characters. A string of characters in square brackets ([ ]) matches any single character in the string. The \ character followed by a special character (such as the ones in this list) matches the character itself. The \ character followed by a character matches the pattern specified by that character (see the following table).
For example, the regular expression B.b* matches Bob, Bubba, and Baby. The regular expression T[aei]*ing matches Taking, Tickling, and Telling. These examples are just a few of many. Figure H.1 specifies some of the patterns that can be matched in a Java regular expression, although this list is not complete. See the online documentation for the Pattern class for a complete list.
721
722
appendix H Regular Expressions
Regular Expression
Matches
x
The character x
.
Any character
[ abc]
a, b, or c
[^abc]
Any character except a, b, or c (negation)
[a-z][A-Z]
a through z or A through Z, inclusive (range)
[a-d[m-p]]
a through d or m through p (union)
[a-z&&[ def]]
d, e, or f (intersection)
[a-z&&[ ^bc]]
a through z, except for b and c (subtraction)
[a-z&&[ ^m-p]]
a through z but not m through p (subtraction)
\d
A digit: [0–9]
\D
A non-digit: [^0–9]
\s
A whitespace character
\S
A non-whitespace character
^
The beginning of a line
$
The end of a line
Figure H.1
Some patterns that can be matched in a Java regular expression
Javadoc Documentation Generator
I
Javadoc is a tool for creating documentation in HTML format from Java source code. The utility examines the source code, extracts specially marked information in the documentation, and then produces Web pages that summarize the software. Documentation comments, also referred to as doc comments, specify the format for comments to be processed by the javadoc tool. Special labels called tags are also parsed by javadoc. Together, doc comments and tags can be used to construct a complete Java application programming interface (API) specification. A Java API is a specification of how to work with a class. Javadoc can be run on packages or individual files (or both). It produces a well-structured, single document each time. However, javadoc does not support incremental additions. Javadoc comes as a standard part of the Java Software Development Kit (SDK). The tool executable, javadoc.exe, resides in the bin folder of the installation directory along with the javac compiler and java execution tool. Therefore, if you are able to compile and execute your code using the command line, javadoc should also work. Using javadoc is simple in its plain form; it is very much like compiling a java source file. For example: javadoc myfile.java
The javadoc command may also specify options and package names. The source file name must contain the .java extension (similar to the javac compiler command).
723
724
appendix i Javadoc Documentation Generator
doc Comments The document comments are subdivided into descriptions and tags. Descriptions should provide an overview of the functionality of the explained code. Tags address the specifics of the functionality such as code version (for classes or interfaces) or return types (for methods). Javadoc processes code comments placed between /**, the beginning tag, and */, the end tag. The comments are allowed to span multiple lines where each line begins with a * character, which are, along with any white space before them, discarded by the tool. These comments are allowed to contain HTML tags. For example: /** * */
This is an example document comment.
Comment placement should be considered carefully. The javadoc tool automatically copies the first sentence from each doc to a summary at the top of the HTML document. The sentence begins after any white space following the * character and ends at the first period. The description that follows should be concise and complete. Document comments are recognized only if they are placed immediately before a class, constructor, method, interface, or field declaration. The use of HTML inside the description should be limited to proper comment separation and display rather than styling. Javadoc automatically structures the document using certain tags—for example, heading tags. Appropriate use of paragraph or list tags (ordered/unordered) should provide satisfactory formatting.
Tags Tags are included in a doc comment. Each tag must start on a separate line, hence it must be preceded by the * character. Tags are case sensitive and begin with the @ symbol. Certain tags are required in some situations. The @param tag must be supplied for every parameter and is used to describe the purpose of the parameter. The @return tag must be supplied for every method that returns anything other than void, to describe what the method returns. The @author class and the @version tags are required for classes and interfaces only. Figure I.1 lists the various tags used in javadoc comments. Note the two different types of tags listed in Figure I.1. The block tags, which begin with the @ symbol (e.g., @author), must be placed in the tag section
a p p e n d i x i Javadoc Documentation Generator
Tag Name
Description
@author
Inserts an “Author” entry with the specified text.
{ @code}
Same as {@literal}
.
@deprecated
Inserts a bold “Deprecated” entry with the specified text.
{ @docRoot}
Relative link to the root of the document.
@exception
See @throws.
{ @inheritDoc}
Copies documentation from the closest inherited class or implemented interface where used allowing for more general comments of hierarchically higher classes to be reused.
{ @link}
Inserts a hyperlink to an HTML document. Use: {@link name url}.
{ @linkPlain}
Same as {@link} but is displayed as plain text. Use: {@linkPlain link label}.
{ @literal}
Text enclosed in the tag is denoted literally, as containing any HTML. For example, {@literal TouchDown} would be displayed as TouchDown ( not interpreted as a table cell).
@param
Inserts a “Parameters” section, which lists and describes parameters for a particular constructor/method.
@return
Inserts a “Returns” section, which lists and describes any return values for a particular constructor/method. Use: @return description. An error will be thrown if included in a comment of a method with the void return type.
@see
Included a “See Also” comment with a link pointing to a document with more information. Use: @see link.
@serial
Used for a serializable field. Use: @serial text.
@serialData
Used to document used to describe data written by the writeObject, readObject, writeExternal, and readExternal methods. Use: @serialdata text.
@serialField
Used to comment on the ObjectStreamField. Use: @serialField name type description.
@since
Inserts a new “Since” heading that is used to denote when particular features were first introduced. Use: @since text.
@throws
Includes a “Throws” heading. Use: @throws name description.
{ @value}
@version
Returns the value of a code element it refers to. Use: @value code-
member label.
Add a “Version” heading when the –version command–line option is used. Use: @version text.
Figure i.1
Various tags used in javadoc comments
725
726
appendix i Javadoc Documentation Generator
following the main description. The inline tags, enclosed in the { and } delimiters, can be placed anywhere in the description section or in the comments for block tags. For example: /** * This is an example document comment. * The {@link Glossary} provides definitions of types used. * * @author Sebastian Niezgoda */
Files generated The javadoc tool analyzes a java source file or package and produces a threepart HTML document for each class. The HTML file is often referred to as a documentation file. It contains cleanly organized information about the class file derived from the doc comments included in the code. The first part of the document contains an overall description of the class. The class name appears first followed by a graphical representation of the inheritance relationships. A general description is displayed next, which is extracted from the first sentence of each doc comment entity (as discussed previously). Next, a list of constructors and methods is provided. The signatures of all the constructors and methods included in the source file are listed along with onesentence descriptions. The name of the constructor/method is a hyperlink to a more detailed description in the third part of the document. Finally, complete descriptions of the methods are provided. Again, the signature is provided first followed by an explanation of the entity, but this time without the one-sentence limit, which is obtained from the doc comments. If applicable, a list of parameters and return values, along with their descriptions, is provided in the respective sections. The HTML document makes extensive use of hyperlinks to provide necessary additional information, using the @see tag for example, and for navigational purposes. The header and the footer of the page are navigation bars, with the following links: ■
■
■
Package provides a list of classes included in the package along with a short purpose and description of each class. Tree presents a visual hierarchy of the classes within the package. Each class name is a link to the appropriate documentation HTML file. Deprecated lists functionality that is considered deprecated that is used in any of the class files contained in the package.
a p p e n d i x i Javadoc Documentation Generator
■
■
Index provides an alphabetical listing of classes, constructors, and methods in the package. The class name is also associated with a short purpose and description of the class. Each appearance of the class name is a link to the appropriate HTML documentation. The signature of every constructor and method is a link to the appropriate detailed description. A one-sentence description presented next to the signature listing associates the constructor/ method with the appropriate class. Help loads a help page with how-to instructions for using and navigating the HTML documentation.
All pages could be viewed with or without frames. Each class summary has links that can be used to quickly access any of the parts of the document (as described above). The output content could be somewhat generated by command-line options (see above) used when executing the javadoc tool. By default, if no options are specified, the output returned is equivalent to using the −protected option. The options include: ■
private shows all classes, methods, and variables.
■
public shows only public classes, methods, and variables.
■
protected shows only protected and public classes, methods, and
variables. ■
help presents the online help.
■
keywords includes HTML meta tags to the output file generated to assist
with searching.
727
This page is intentionally left blank.
The PaintBox Project
J
In this appendix we examine a software development project that is larger than any other described in this text. Our example program allows the user to create drawings with various shapes and colors. This type of project encompasses a variety of issues that are commonly found in large-scale software development and provides a good basis for exploring our development model. We call this example the PaintBox project.
PaintBox Requirements Suppose the client provides the following set of initial requirements. The program will: ■
Present a graphical user interface that is primarily mouse driven for all user actions.
■
Allow the user to draw lines, ovals, circles, rectangles, and squares.
■
Allow the user to change the drawing color.
■
Display the current drawing color.
■
Allow the user to fill a shape, except for a line, with a color.
■
■ ■
■
Allow the user to select a shape in order to move it, modify its color, or reshape it. Allow the user to cut, copy, and paste individual shapes in a drawing. Allow the user to save a drawing in a file and load a previously stored drawing from a file for further editing. Allow the user to begin a new drawing at any time.
After examining these general requirements, we might sit down with the client and discuss some of the details to ensure that there are no misunderstandings. We might create a new requirements document that is much more specific about the issues involved. During these interactions with the client, we might create a sketch, such as the one shown in Figure J.1, of a user interface for the system. This sketch serves as a basic prototype of the interface, and gives us something to refer to in our discussions
729
730
appendix J The PaintBox Project
File Edit Select
Line
Oval
Rect
Color
g Drawin Area
Figure J.1
A sketch of the user interface for the PaintBox program
with the client. For other systems, there may be many such sketches for each screen of the program. The interface sketch shows a main drawing area where the user will create a drawing. The top edge contains a set of buttons used to select various tools, such as the oval tool to draw an oval or circle, the color tool to change the current drawing color, and a select tool to select a previously drawn shape to modify or move it. Two menu headings are shown along the top edge. The File menu contains operations to begin a new drawing, save a drawing, and exit the program. The Edit menu contains editing operations such as cut, copy, and paste. As a result of the discussions with the client, several additional requirements issues are established: ■
There is no need to have separate user interactions for circles or squares because they are subsets of ovals and rectangles, respectively.
■
The user should also be able to create polyline shapes.
■
The buttons used to select drawing tools should have icons instead of words.
a p p e n d i x J The PaintBox Project
■
■
■
■
■
The system should make a distinction between the stroke color (the outline) and the fill color (the interior) of a shape. Therefore, each shape will have a separate stroke and fill color. Lines and polylines will have only a stroke color because they cannot be filled. An option to save a drawing under a particular name should be provided (the traditional “save as” operation). Traditional keyboard shortcuts for operations such as cut, copy, and paste should be included. The system should perform checks to ensure that the user does not lose unsaved changes to a drawing. The system should present an initial “splash screen” to introduce the program when it is executed.
These issues must be integrated into the formal description of the requirements document for the project. Several discussions with the client, with additional screen sketches, may be necessary before we have an accurate and solid set of program requirements.
PaintBox architectural design After we have clarified the requirements with the client, we can begin to think about some of the elements of the high-level architectural design of the system. For example, many of the classes needed for the user interface can come from the Java standard class library in the Swing package. It also seems reasonable that a separate class could be used to represent each shape type. Further, each individually drawn shape should be an instantiation of the appropriate shape class. For example, we could define an Oval class to represent an oval, a Line class to represent a line, and so on. Each class should be responsible for keeping track of the information it needs to define it, and it should provide methods to draw itself. A drawing may be composed of many shapes, so we need a way to keep track of all of them. An ArrayList might be a good choice for this. As each new shape is drawn, we can add the object that represents it to the list. The list will also inherently define the order in which shapes are drawn. Since some shapes will be drawn on top of others, the list will also keep track of the order in which shapes are “stacked.” The process of defining an architectural design could take a while. The key is to make the most important and fundamental decisions that will affect the entire system without skipping ahead to decisions that are better left to individual refinements of the system.
731
732
appendix J The PaintBox Project
PaintBox Refinements After some consideration, we might decide that the evolution of the PaintBox project could be broken down into the following refinement steps: ■
Establish the basic user interface.
■
Allow the user to draw basic shapes using different stroke colors.
■
Allow the user to cut, copy, and paste shapes.
■
Allow the user to select, move, and fill shapes.
■
Allow the user to modify the dimensions of shapes.
■
Allow the user to save and reload drawings.
■
Include final touches such as the splash screen.
Note, first of all, that these refinements focus on breaking down the functionality of the system. Additional refinements may be necessary as we get into the iterative process. For instance, we may decide that we need a refinement to address problems that were discovered in previous refinements. The listed refinements could have been broken down further. For example, one refinement could have been devoted to the ability to draw one particular type of shape. The level of refinement, just like many other decisions when developing a software system, is a judgment call. The developer must decide what is best in any particular situation. The order in which we tackle the refinements is also important. The user interface refinement seems to be a logical first step because all other activity relies on it. We may decide that the ability to save and reload a drawing would be nice to have early for testing purposes. We might also note that being able to select an object is fundamental to operations such as move and cut/copy/ paste. After further analysis, we end up with the set of refinements shown in Figure J.2.
PaintBox Refinement #1 Most of the classes used for the interface come from predefined libraries. We use Swing technology whenever reasonable. For example, we can use a JPanel for the overall interface space, as well as separate JPanel objects to organize the button tools and the drawing area. The JButton class will serve well for the buttons. Classes such as JMenuBar and JMenuItem will serve to implement the menus. Figure J.3 shows a class diagram that represents the classes that are important to the first refinement of the PaintBox project. Note that it does not include all classes that might be needed, nor does it address anything other than the needs
a p p e n d i x J The PaintBox Project
Refinement
Description
1
Present the basic graphical user interface, including the main frame, buttons, menus, menu items, and the drawing area. The select and shape buttons work together as a radio button set (only one can be chosen at a time). No functionality for these interface elements is included at this time. Exiting the program is provided only by the frame's window close button.
2
Add support for drawing the four basic shapes: lines, ovals, rectangles, and polylines. The chosen shape button determines what shape is drawn. The stroke color button can be used to set the stroke color for the next shape drawn. The color button causes a separate dialog box to appear to allow color selection.
3
Add support for saving and loading drawings. This includes the functionality of the open, save, and save as File menu items. When the open, new, or exit File menu options are chosen, check to see if the current drawing has been modified since last saved, and if so prompt to see if the user wants to save the drawing.
4
Provide the ability to select and move shapes on the drawing surface. Simple graphic selection blocks should be presented on the shape's outline to indicate the currently selected shape. Once selected, the mouse can be used to drag the shape to another location on the drawing surface.
5
Add the functionality for the cut, copy and paste Edit menu items. Once selected, a shape can be cut or copied. Once a shape has been cut or copied, it can be pasted (perhaps multiple times) onto the drawing surface at a fixed offset to the original position. Edit menu items that are not valid at any given time are disabled. For example, unless a shape is selected, the cut and copy menu items cannot be chosen.
6
Add support for filling and reshaping a shape. Once a shape has been selected, the fill color button can be used to determine its fill color. A menu item on the Edit menu can be used to remove the fill of any filled object (make it transparent). The currently selected shape will now have a reshape handle that can be used to change the dimensions of the shape.
7
Add some extra functionality to the program. These additions include a splash screen that appears when the system is initially executed, an about dialog box, keyboard shortcuts for all menu items, and packaging the application into an executable JAR file.
FiguRe J.2
Functional refinements for the PaintBox project
of this one refinement. We’ll create additional diagrams that augment our understanding of the system design as further refinements are developed. The detailed design and implementation for the interface refinement might develop similarly to other graphical projects we’ve developed in previous chapters.
733
734
appendix J The PaintBox Project
JFrame
PaintBox
+ main (args : String[]) : void
PaintFrame
JMenuBar
JToolBar DrawingPanel
ButtonBar 1 5 JRadioButton
FiguRe J.3
JButton
A class diagram for the interface refinement of the PaintBox project
We can create listener objects and methods as appropriate but not concern ourselves with their inner workings at this time. That is, our focus in this refinement is to present the user interface, not to create any of the functionality behind the interface. During the development of this refinement, we modify the details of the user interface until it appears just the way we’d like it. At the end of the first refinement, we are left with a completely implemented program that presents only the user interface. The buttons do nothing when pushed, and the menu items do nothing when selected. We have no way of creating a drawing yet. What we do have, however, is a complete entity that has been debugged and tested to the level of this refinement. We may show it to the client at this point and get further input. Any changes that result from these discussions can be incorporated into future refinements. Figure J.4 shows the PaintBox program after the first refinement has been completed.
a p p e n d i x J The PaintBox Project
FiguRe J.4
The PaintBox application after refinement #1
PaintBox Refinement #2 The next refinement to address is the ability to draw basic shapes, because all other operations use drawn shapes in one way or another. Therefore, in this refinement we focus on providing the processing power behind the buttons that draw shapes and specify color. Most of the objects and classes that we will use in this refinement are not predefined as they were in the interface refinement. We might consider using the
735
736
appendix J The PaintBox Project
Rectangle class from the Java standard class library, but on further investigation
we realize that its role is not really consistent with our goals. In addition, no other classes are defined for the other shapes we need. So, as we envisioned in our architectural design, we consider having one class per shape type: Line, Oval, Rect, and Poly. Remember that circles and squares will just be specific instances of the Oval and Rect classes, respectively. Each shape class will have a draw method that draws that kind of shape on the screen. Now let’s consider the kind of information that each shape needs to store to be able to draw itself. A line needs two points: a starting point and an ending point. Each polyline, on the other hand, needs a list of points to define the start and end points of each line segment. Both ovals and rectangles are defined by a bounded rectangle, storing an upper-left corner and the width and height of the shape. This analysis leads to the conclusion that Oval and Rect objects have some common characteristics that we could exploit using inheritance. They could both, for instance, be derived from a class called BoundedShape. Furthermore, because all shapes have to be stored in the ArrayList object that we’ll use to keep track of the entire drawing, it would simplify the refinement to have a generic Shape class from which all drawn shapes are derived. The Shape and BoundedShape classes are used for organizational purposes. We do not intend to instantiate them; therefore they probably should be abstract classes. In fact, if we define an abstract method called draw in the Shape class, we could capitalize on polymorphism to simplify the drawing of the shapes in the drawing area. A loop can move through the ArrayList, having each shape (whatever it may be) draw itself. After some consideration, we achieve the class diagram shown in Figure J.5. This diagram specifically represents the classes that are important to the second refinement of the PaintBox project. Selecting a current color can be relegated to the JColorChooser component provided by the Swing package. The color button will bring up the JColorChooser dialog box and respond accordingly to the user’s selection. Multiple shapes will accumulate on the drawing surface. We could define a class to serve as a collection of the drawn shape objects. It could use an ArrayList to keep track of the list of shapes. Whenever the drawing area needs to be refreshed, we can iterate through the list of shapes and draw each one in turn. Figure J.6 shows the PaintBox program after the first two refinements have been completed. Once again, we could visit with the client at this point to determine whether the evolution of the system meets with his or her satisfaction.
a p p e n d i x J The PaintBox Project
DrawingPanel *
Shape – strokeColor : Color
1 ArrayList
+ draw() : void
Line – firstPoint : Point – secondPoint : Point
BoundedShape – upperLeft : Point – width, height : int
Rect
FiguRe J.5
Poly – xList, yList : ArrayList
Oval
A class diagram for the second refinement of the PaintBox project
Remaining paintBox Refinements For space reasons, the code for the various PaintBox refinements is not presented in the text. The full implementation of the first two refinements can be downloaded with the rest of the book’s examples. The remaining refinements are left as projects. The refinements of the PaintBox program continue until all requirement issues and problems have been addressed. This type of evolutionary development is crucial for medium- and large-scale development efforts. Figure J.7 shows the PaintBox program after all of the seven refinements have been completed.
737
738
appendix J The PaintBox Project
FiguRe J.6
The PaintBox program after the interface and shapes refinements
a p p e n d i x J The PaintBox Project
FiguRe J.7
The completed PaintBox program
739
This page is intentionally left blank.
GUI Events
K
Throughout the Graphics Track sections of this book, we’ve discussed various events that components might generate. The goal of this appendix is to put the event/component relationship into context. The events listed in Figure K.1 are generated by every Swing component. That is, we can set up a listener for any of these events on any component. Some events are generated only by certain components. The table in Figure K.2 maps the components to the events that they can generate. Keep in mind that these events are in addition to the ones that all components generate. If a component does not generate a particular kind of event, a listener for that event cannot be added to that component. We have discussed some of the events in Figures K.1 and K.2 at appropriate points in this text; we have left others for your independent exploration. Applying the basic concept of component/event/listener interaction is often just a matter of knowing which components generate which events under which circumstances. Of course, many events occur in a GUI that have no bearing on the current program. For example, every time a mouse is moved across a component, many mouse motion events are generated. However, this doesn’t mean we must listen for them. A GUI is defined in part by the events to which we choose to respond. Despite our heavy coverage of GUI development in this book, we’ve still only scratched the surface. The following list describes a few other Java GUI containers and components that are not covered in depth in this text: Event
Represents
Component Event
Changing a component's size, position, or visibility.
Focus Event
Gaining or losing the keyboard focus.
Key Event
Pressing, releasing, and clicking keyboard keys.
Mouse Event
Clicking the mouse button and moving the mouse into and out of a component's drawing area.
Mouse Motion Event
Moving or dragging a mouse over a component.
Figure K.1
Events that are generated by every Swing component 741
742
APPeNDiX K GUI Events
Event Component
Action
Caret
Change Document Item
List Window Other Selection
JButton JCheckBox JColorChooser JComboBox JDialog JEditorPane JFileChooser JFrame JInternalFrame JList JMenu JMenuItem JOptionPane JPasswordField JPopupMenu JProgessBar JRadioButton JSlider JTabbedPane JTable JTextArea JTextField JTextPane JToggleButton JTree
Figure K.2
■
■
Specific events generated by specific components
A tool bar is a container that groups several components into a row or column. A tool bar usually contains buttons that correspond to tasks that can also be accomplished in other ways. Tool bars can be dragged away from the container in which they initially exist into their own window. An internal frame is a container that operates like a regular frame but only within another window. An internal frame can be moved around within the window and overlapped with other internal frames. Internal frames can be used to create the feel of a GUI desktop in which components can be arranged as the user chooses.
A P P e N D i X K GUI Events
■
■
■
■
■
A layered pane is a container that takes into account a third dimension, depth, for organizing the components it contains. When a component is added to a layered pane, its depth is specified. If components overlap, the depth value of each component determines which is on top. A progress bar can be used to indicate the progress of a particular activity. The user does not generally interact with a progress bar other than to view it to determine how far along a task, such as the loading of images, has progressed. A table is a Java GUI component that displays data in a table format. A Java table can be completely tailored to provide a precise organization and presentation. It can allow the user to edit the data as well. A Java table does not actually contain or store the data; it simply presents it to the user in an organized manner. A tree is a component that presents a hierarchical view of data. Like a table, it doesn’t actually store the data; it provides an organized view that allows the user to traverse the data from a high-level root node down through the various branches. Another area for which Java provides rich support is text processing. We’ve made use of basic text components such as text fields and text areas, but that’s only the beginning. The Java standard class library (and particularly the Swing API) has a huge number of classes that support the display, editing, and manipulation of text.
As with all topics introduced in this book, we encourage you to explore these issues in more detail. The world of Java GUIs, in particular, offers many opportunities for you to discover.
743
This page is intentionally left blank.
L
Java Syntax This appendix contains syntax diagrams that collectively describe the way in which Java language elements can be constructed. Rectangles indicate something that is further defined in another syntax diagram, and ovals indicate a literal word or character.
Compilation Unit
Package Declaration
Import Declaration
Type Declaration
Package Declaration package
Name
;
Import Declaration import
Name
.
Identifier
;
* Type Declaration Class Declaration Interface Declaration
745
746
APPENDIX L Java Syntax
Class Declaration class
Identifier
Class Associations
Class Body
Modifier Class Associations
extends
Name
implements
Name List
Class Body {
} Class Member
Class Member Field Declaration Constructor Declaration Method Declaration Class Declaration Interface Declaration static
Block
Interface Declaration interface
Identifier
Modifier
Interface Body extends
Interface Body {
} Interface Member
Interface Member Field Declaration Method Declaration Class Declaration Interface Declaration
Name List
A P P E N D I X L Java Syntax
Field Declaration Type
Variable Declarator
Modifier
;
,
Variable Declarator Identifier =
Expression Array Initializer
Type Primitive Type [
Name
Modifier
]
Primitive Type public
boolean
private
char
protected
byte
static
short
final
int
abstract
long
native
float
synchronized
double
transient volatile
Array Initializer {
} Expression Array Initializer ,
Name
Name List Identifier .
Name ,
747
748
APPENDIX L Java Syntax
Method Declaration Type Modifier
Identifier
Parameters
Throws Clause
Method Body
void
Parameters (
) Type
Identifier ,
Throws Clause
throws
Name List
Method Body Block ; Constructor Declaration Identifier
Parameters
Throws Clause
Constructor Body
Modifier
Constructor Body {
} Constructor Invocation
Block Statement
Constructor Invocation this
Arguments
; super
Expression
.
Arguments
A P P E N D I X L Java Syntax
Block {
} Block Statement
Block Statement Local Variable Declaration
;
Statement Class Declaration
Local Variable Declaration Type final
Variable Declarator ,
Statement Block Statement Expression Basic Assignment If Statement Switch Statement While Statement Do Statement For Statement Return Statement Throw Statement Try Statement Synchronized Statement Empty Statement Break Statement Continue Statement Labeled Statement
749
750
APPENDIX L Java Syntax
If Statement if
(
Expression
)
Statement else
Statement
Switch Statement switch
(
Expression
)
{
} Switch Case
Switch Case case
Expression default
: Block Statement
:
While Statement while
(
Expression
)
Statement
Do Statement do
Statement
while
(
Expression
)
;
For Statement for
(
; For Init
For Init
; Expression
)
Statement
For Update For Update
Local Variable Declaration Statement Expression ,
Statement Expression ,
A P P E N D I X L Java Syntax
Basic Assignment Identifier
=
Expression
;
Return Statement return
; Expression
Throw Statement throw
;
Expression
Try Statement try
Block
catch
(
Type finally
Identifier Block
Synchronized Statement synchronized
(
Expression
Empty Statement ; Break Statement break
; Identifier
Continue Statement continue
; Identifier
Labeled Statement Identifier
:
Statement
)
Block
)
Block
751
752
APPENDIX L Java Syntax
Expression Primary Expression Assignment Arithmetic Expression Equality Expression Relational Expression Logical Expression Bitwise Expression Conditional Expression Instance Expression Cast Expression Unary Expression
Primary Expression Literal Primary Suffix
Name this super (
. Expression
Identifier )
Allocation
Primary Suffix .
Identifier
.
this
.
class
.
Allocation
[
Expression
Arguments
]
A P P E N D I X L Java Syntax
Arguments (
) Expression ,
Allocation new
Primitive Type
Array Dimensions Array Initializer
Name
Arguments Class Body
Array Dimensions [
Expression
] [
]
Statement Expression Assignment
;
Prefix Expression Postfix Expression
Assignment Expression
= += -= *= /= %= <<= >>= >>>= &= ^= |=
Expression
753
754
APPENDIX L Java Syntax
Arithmetic Expression Expression
+
Expression
* / % Equality Expression Expression
==
Expression
!= Relational Expression Expression
<
Expression
> <= >= Logical Expression Expression
&&
Expression
|| Bitwise Expression Expression
&
Expression
| ^ << >> >>> Conditional Expression Expression
?
Expression
:
Instance Expression Expression
instanceOf
Type
Cast Expression (
Type
)
Expression
Expression
A P P E N D I X L Java Syntax
Unary Expression
Prefix Expression
Prefix Expression
++
Postfix Expression
--
+
Expression
Expression
Postfix Expression
!
Expression
~
--
Literal Integer Literal Floating Point Literal Character Literal String Literal Boolean Literal null Integer Literal Decimal Integer Literal Octal Integer Literal Hex Integer Literal Decimal Integer Literal 0 1-9
L
0-9
l Octal Integer Literal 0
Hex Digit
0-7
0-9 L
a-f
l
A-F
Hex Integer Literal 0
++
X x
Hex Digit
L l
755
756
APPENDIX L Java Syntax
Floating Point Literal 0-9
.
.
Exponent Part
0-9
Float Suffix
0-9
Exponent Part
Float Suffix
e
0-9
f
+
E
F
-
d D
Character Literal
Boolean Literal
'
any character
'
true false
Escape Sequence Unicode Escape
String Literal "
" any character Escape Sequence Unicode Escape
Escape Sequence \
n t b r f \ ' " 0-3
0-7
0-7
A P P E N D I X L Java Syntax
Identifier Java Letter Java Letter Java Digit
Java Letter a-z A-Z _ $ other Java letter
*
Unicode Escape * The "other Java letter" category includes letters from many languages other than English.
Java Digit 0-9 other Java digit
*
Unicode Escape * The "other Java digit" category includes additional digits defined in Unicode.
Unicode Escape* \
u
Hex Digit
Hex Digit
* In some contexts, the character represented by a Unicode Escape is restricted.
Hex Digit
Hex Digit
757
This page is intentionally left blank.
The Java Class Library
M
In previous editions of this book, this appendix included abbreviated reference material for the Java API. This appendix is still available at ftp://ftp.aw.com/cseng/ authors/lewis/jss7/ for anyone who would like to download and make use of it. A better solution, however, is to become familiar with the official and complete online API documentation, as shown in Figure M.1. It contains a description of every class, interface, and method available to every Java development environment. We encourage you to spend some time becoming familiar with the organization and layout of that documentation. It is a valuable tool to rely on during program development.
Figure M.1
The online Java API documentation 759
This page is intentionally left blank.
Answers to SelfReview Questions Chapter 1
N
Introduction
1.1 Computer Processing SR 1.1
The hardware of a computer system consists of its physical components such as a circuit board, monitor, or keyboard. Computer software consists of the programs that are executed by the hardware and the data that those programs use. Hardware is tangible, whereas software is intangible. In order to be useful, hardware requires software and software requires hardware.
SR 1.2
The operating system provides a user interface and efficiently coordinates the use of resources such as main memory and the CPU.
SR 1.3
It takes 7,200,000 numbers for a three-minute song (40,000 3 60 3 3) and 144,000,000 numbers for one hour of music (40,000 3 60 3 60).
SR 1.4
The information is broken into pieces, and those pieces are represented as numbers.
SR 1.5
In general, N bits can represent 2N unique items. Therefore: a. b. c. d.
SR 1.6
2 4 5 7
bits bits bits bits
can can can can
represent represent represent represent
4 items because 22 5 4. 16 items because 24 5 16. 32 items because 25 5 32. 128 items because 27 5 128.
It would take 6 bits to represent each of the 50 states. Five bits is not enough because 25 5 32 but six bits would be enough because 26 5 64.
1.2 Hardware Components SR 1.7
A kilobyte (KB) is 210 = 1,024 bytes, a megabyte (MB) is 220 5 1,048,576 bytes, and a gigabyte (GB) is 230 5 1,073,741,824 bytes. Therefore: 761
762
aPPendIx n Answers to Self-Review Questions
a. 3 KB 5 3 * 1,024 bytes 5 3,072 bytes = approximately 3 thousand bytes b. 2 MB 5 2 * 1,048,576 bytes 5 2,097,152 bytes = approximately 2.1 million bytes c. 4 GB 5 4 * 1,073,741,824 bytes 5 4,294,967,296 bytes = approximately 4.3 billion bytes SR 1.8
There are eight bits in a byte. Therefore: a. 8 bytes 5 8 * 8 bits 5 64 bits b. 2 KB 5 2 * 1,024 bytes 5 2,048 bytes 5 2,048 * 8 bits = 16,384 bits c. 4 MB 5 4 * 1,048,576 bytes 5 4,194,304 bytes 5 4,194,304 * 8 bits 5 33,554,432 bits
SR 1.9
Under the stated conditions, one hour of music would require 288,000,000 bytes (40,000 3 60 3 60 3 2). Dividing this number by the number of bytes in a megabyte (1,048,576 bytes) gives approximately 275 MB. Note that a typical audio CD has a capacity of about 650 MB and can store about 70 minutes of music. This coincides with an actual sampling rate of 41,000 measurements per second, two bytes of storage space per measurement, and the need to store two streams of music to produce a stereo effect.
SR 1.10 The two primary hardware components are main memory and the CPU. Main memory holds the currently active programs and data. The CPU retrieves individual program instructions from main memory, one at a time, and executes them. SR 1.11 A memory address is a number that uniquely identifies a particular memory location in which a value is stored. SR 1.12 Main memory is volatile, which means the information that is stored in it will be lost if the power supply to the computer is turned off. Secondary memory devices are nonvolatile; therefore, the information that is stored on them is retained even if the power goes off. SR 1.13 The word that best matches is a. peripheral b. controller c. modem d. main or RAM e. secondary or ROM f. RAM g. CPU
1.3 networks SR 1.14 A file server is a network computer that is dedicated to storing and providing programs and data that are needed by many network users.
a P P e n d I x n Answers to Self-Review Questions
SR 1.15 Counting the number of unique connections in Figure 1.16, there are 10 communication lines needed to fully connect a point-to-point network of five computers. Adding a sixth computer to the network will require that it be connected to the original five, bringing the total to 15 communication lines. SR 1.16 Having computers on a network share a communication line is cost effective because it cuts down on the number of connections needed and it also makes it easier to add a new computer to the network. Sharing lines, however, can mean delays in communication if the network is busy. SR 1.17 The word Internet comes from the word internetworking, a concept related to wide-area networks (WANs). An internetwork connects one network to another. The Internet is a WAN. SR 1.18 TCP stands for Transmission Control Protocol. IP stands for Internet Protocol. A protocol is a set of rules that govern how two things communicate. SR 1.19 Breaking down the parts of each URL: a. duke is the name of a computer within the csc subdomain (the Department of Computing Sciences) of the villanova.edu domain, which represents Villanova University. The edu top-level domain indicates that it is an educational organization. This URL is requesting a file called examples.html from within a subdirectory called jss. b. java is the name of a computer (Web server) at the sun.com domain, which represents Sun Microsystems, Inc. The com toplevel domain indicates that it is a commercial business. This URL is requesting a file called index.html from within a subdirectory called products.
1.4 The Java Programming Language SR 1.20 The Java programming language was developed in the early 1990s by James Gosling at Sun Microsystems. It was introduced to the public in 1995. SR 1.21 The processing of a Java application begins with the main method. SR 1.22 The characters “Hello” will be printed on the computer screen. SR 1.23 The entire line of code is a comment, so there is no result. SR 1.24 All of the identifiers shown are valid except 12345 (since an identifier cannot begin with a digit) and black&white (since an identifier cannot
763
764
aPPendIx n Answers to Self-Review Questions
contain the character &). The identifiers RESULT and result are both valid, but should not be used together in a program because they differ only by case. The underscore character (as in answer_7) is a valid part of an identifier. SR 1.25 Although any of the listed names could be used as the required identifier, the only “good” choice is scoreSum. The identifier x is not descriptive and is meaningless, the identifier sumOfTheTestScoresOfTheStudents is unnecessarily long, and the identifier smTstScr is unclear. SR 1.26 White space is a term that refers to the spaces, tabs, and newline characters that separate words and symbols in a program. The compiler ignores extra white space; therefore, it doesn’t affect execution. However, it is crucial to use white space appropriately to make a program readable to humans.
1.5 Program development SR 1.27 At the lowest level, a computer’s instructions perform only simple tasks, such as copying a value or comparing two numbers. However, by putting together millions of these simple instructions every second, a computer can perform complex tasks. SR 1.28 High-level languages allow a programmer to express a series of program instructions in English-like terms that are relatively easy to read and use. However, in order to execute, a program must be expressed in a particular computer’s machine language, which consists of a series of bits that are basically unreadable by humans. A high-level language program must be translated into machine language before it can be run. SR 1.29 Java bytecode is a low-level representation of a Java source code program. The Java compiler translates the source code into bytecode, which can then be executed using the Java interpreter. The bytecode might be transported across the Web before being executed by a Java interpreter that is part of a Web browser. SR 1.30 The word that best matches is a. machine e. compiler
b. assembly f. interpreter
c. high-level
d. high-level
SR 1.31 Syntax rules define how the symbols and words of a programming language can be put together. The semantics of a programming language instruction determine what will happen when that instruction is executed. SR 1.32 a. Compile-time error b. Run-time error (you cannot divide by zero) c. Logical error
a P P e n d I x n Answers to Self-Review Questions
1.6 Object-Oriented Programming SR 1.33 1. 2. 3. 4. 5.
Understand the problem. Design a solution. Consider alternatives and refinements to the solution. Implement the solution. Test the solution.
SR 1.34 The first solution to a problem that we think of may not be a good one. By considering alternative solutions before expending too much energy implementing our first idea, we can often save overall time and effort. SR 1.35 The primary elements that support object-oriented programming are objects, classes, encapsulation, and inheritance. An object is defined by a class, which contains methods that define the operations on those objects (the services that they perform). Objects are encapsulated such that they store and manage their own data. Inheritance is a reuse technique in which one class can be derived from another.
Chapter 2
data and expressions
2.1 Character Strings SR 2.1
A string literal is a sequence of characters delimited by double quotes.
SR 2.2
Both the print and println methods of the System.out object write a string of characters to the monitor screen. The difference is that, after printing the characters, the println performs a carriage return so that whatever’s printed next appears on the next line. The print method allows subsequent output to appear on the same line.
SR 2.3
A parameter is data that is passed into a method when it is invoked. The method usually uses that data to accomplish the service that it provides. For example, the parameter to the println method indicates what characters should be printed.
SR 2.4
The output produced by the code fragment is One Two Three
SR 2.5
The output produced by the code fragment is Ready Set Go
765
766
aPPendIx n Answers to Self-Review Questions
SR 2.6
The output produced by the statement is It is good to be 10
The + operator in the sub-expression (5 + 5) represents integer addition, since both of its operands are integers. If the inner parentheses are removed, the + operators represent string concatenation and the output produced is It is good to be 55
SR 2.7
An escape sequence is a series of characters that begins with the backslash (\) and that implies that the following characters should be treated in some special way. Examples: \n represents the newline character, \t represents the tab character, and \" represents the quotation character (as opposed to using it to terminate a string).
SR 2.8
System.out.println("\"I made this letter longer than " + "usual because I lack the time to\nmake it short.\"" + "\n\tBlaise Pascal");
2.2 Variables and assignment SR 2.9
A variable declaration establishes the name of a variable and the type of data that it can contain. A declaration may also have an optional initialization, which gives the variable an initial value.
SR 2.10 Given those variable declarations, the answers are: a. Five variables are declared: count, value, total, MAX_VALUE, and myValue. b. They are all of type int. c. count, MAX_VALUE, and myValue are each given an initial value. d. Yes, it is legal. myValue is a variable of type int and 100 is an int literal. e. No, it is not legal. MAX_VALUE is declared as a final variable and therefore it cannot be assigned a value other than its initial value. SR 2.11 The variable name you choose should reflect the purpose of the variable. For example: int numCDs = 0;
SR 2.12 The variable name you choose should reflect the purpose of the variable. Since the number of feet in a mile will not change, it is a good idea to declare a constant. For example: final int FT_PER_MILE = 5280;
a P P e n d I x n Answers to Self-Review Questions
SR 2.13 First, by carefully choosing the name of the constant, you can make your program more understandable than if you just use the literal value. Second, using a constant ensures that the literal value represented by the variable will not be inadvertently changed somewhere in the program. Third, if you ever do have to rewrite the program using a different literal value, you will only need to change that value once, as the initial value of the constant, rather than many places throughout the program.
2.3 Primitive data Types SR 2.14 Primitive data are basic values such as numbers or characters. Objects are more complex entities that usually contain primitive data that help define them. SR 2.15 An integer variable can store only one value at a time. When a new value is assigned to it, the old one is overwritten and lost. SR 2.16 The four integer data types in Java are byte, short, int, and long. They differ in how much memory space is allocated for each and therefore how large a number they can hold. SR 2.17 Java automatically assigns an integer literal the data type int. If you append an L or an l on the end of an integer literal, for example 1234L, Java will assign it the type long. SR 2.18 Java automatically assigns a floating point literal the data type double. If you append an F or an f on the end of a floating point literal, for example 12.34f, Java will assign it the type float. SR 2.19 A character set is a list of characters in a particular order. A character set defines the valid characters that a particular type of computer or programming language will support. Java uses the Unicode character set. SR 2.20 The original ASCII character set supports 27 5 128 characters, the extended ASCII character set supports 28 5 256 characters, and the UNICODE character set supports 216 5 65,536 characters.
2.4 expressions SR 2.21 The result of 19%5 in a Java expression is 4. The remainder operator % returns the remainder after dividing the second operand into the first. The remainder when dividing 19 by 5 is 4. SR 2.22 The result of 13/4 in a Java expression is 3 (not 3.25). The result is an integer because both operands are integers. Therefore, the / operator performs integer division, and the fractional part of the result is truncated.
767
768
aPPendIx n Answers to Self-Review Questions
SR 2.23 After executing the statement, diameter holds the value 20. First, the current value of diameter (5) is multiplied by 4, and then the result is stored back in diameter. SR 2.24 Operator precedence is the set of rules that dictates the order in which operators are evaluated in an expression. SR 2.25 The evaluations of the expressions are 5 15 + 21 a. 15 + 7 * 3 b. (15 + 7) * 3 5 22 * 3 c. 3 * 6 + 10 / 5 + 5 5 18 + 2 + 5 d. 27 % 5 + 7 % 3 5 2 + 1 e. 100 / 2 / 2 / 2 5 50 / 2 / 2 f. 100 / ( 2 / 2) / 2 5 100 / 1 / 2
5 5 5 5 5 5
36 66 25 3 25 / 2 = 12 100 / 2 = 50
SR 2.26 Expression a is valid. Expression b is invalid because there are two open parentheses but only one close parenthesis. Similarly with expression c, where there are two open parentheses but no close parenthesis. Expression d might be a valid algebraic expression in an algebra book, but it is not a valid expression in Java. There is no operator between the operands 2 and ( 4 ). SR 2.27 After the sequence of statements, the value in result is 8. SR 2.28 After the sequence of statements, the value in result is 8. Note that even though result was set to base + 3, changing the value of base to 7 does not retroactively change the value of result. SR 2.29 An assignment operator combines an operation with assignment. For example, the += operator performs an addition, then stores the value back into the variable on the left-hand side. SR 2.30 After executing the statement, weight holds the value 83. The assignment operator −= modifies weight by first subtracting 17 from the current value (100), then storing the result back into weight.
2.5 data Conversion SR 2.31 A widening conversion tends to go from a small data value, in terms of the amount of space used to store it, to a larger one. A narrowing conversion does the opposite. Information is more likely to be lost in a narrowing conversion, which is why narrowing conversions are considered to be less safe than widening ones. SR 2.32 The conversions are: a. widening, b. narrowing, c. widening, d. widening, e. widening.
a P P e n d I x n Answers to Self-Review Questions
SR 2.33 During the execution of the statement, the value stored in value is read and transformed into a float as it is being copied into the memory location represented by result. But the value variable itself is not changed, so value will remain an int variable after the assignment statement. SR 2.34 During the execution of the statement, the value stored in result is read and then transformed into an int as it is being copied into the memory location represented by value. But the result variable itself is not changed, so it remains equal to 27.32, whereas value becomes 27. SR 2.35 The results stored are a. 3 b. 3.0
c. 2.4 d. 3.4 e. 2
integer division is used since both operands are integers. integer division is used since both operands are integers, but then assignment conversion converts the result of 3 to 3.0. floating point division is used since one of the operands is a floating point. num1 is first cast as a double; therefore, floating point division is used since one of the operands is a floating point. val1 is first cast as an int; therefore, integer division is used since both operands are integers.
2.6 Interactive Programs SR 2.36 The corresponding lines of the GasMileage program are a. b. c. d.
import java.util.Scanner; Scanner scan = new Scanner(System.in); Scanner scan = new Scanner(System.in); miles = scan.nextInt();
SR 2.37 Under the stated assumptions, the following code will ask users to enter their age and store their response in value. System.out.print("Enter your age in years: "); value = myScanner.nextInt();
2.7 Graphics SR 2.38 A black and white picture can be drawn using a series of dots, called pixels. Pixels that correspond to a value of 0 are displayed in white, and pixels that correspond to a value of 1 are displayed in black. By using
769
770
aPPendIx n Answers to Self-Review Questions
thousands of pixels, a realistic black and white photo can be produced on a computer screen. SR 2.39 The coordinates of the fourth corner are (3, 7), which is the top-right corner. SR 2.40 We can tell from the given information that the side of the square has length 3. Therefore, the other two corners are (5, 13) and (8, 13). SR 2.41 Eight bits per number, three numbers per pixel, and 300 by 200 pixels gives 8 3 3 3 300 3 200 5 1,440,000 bits
2.8 applets SR 2.42 A Java applet is a Java program that can be executed using a Web browser. Usually, the bytecode form of the Java applet is pulled across the Internet from another computer and executed locally. A Java application is a Java program that can stand on its own. It does not require a Web browser in order to execute. SR 2.43 An applet’s paint method is invoked by the system whenever the applet’s graphic element needs to be displayed (or “painted”) on the screen. Examples include when the applet first runs or when a window that was covering the applet’s window is removed. SR 2.44 The code tag should indicate a bytecode file, such as DrawHouse.class, and not a source code file. The file indicated by the tag is supposed to be “ready to run” on a Java interpreter.
2.9 drawing Shapes SR 2.45 A bounding rectangle is an imaginary rectangle that surrounds a curved shape, such as an oval, in order to define the shape’s width, height, and upper left corner. SR 2.46 page.drawRect(16, 12, 50, 50); SR 2.47 page.setColor(Color.blue); page.fillRect(30, 35, 40, 20);
SR 2.48 The results of the changes are a. Since the value of MID is added to all the horizontal components of the snowman figure, the snowman shifts a little bit to the left. b. Since the value of TOP is added to all the vertical components of the snowman figure, the snowman shifts upwards a little bit. c. The hat is now blue.
a P P e n d I x n Answers to Self-Review Questions
d. By changing the start angle of the smile arc to 10, the starting point is now on the right side of the snowman’s face instead of the left. The “direction” of the arc is still counterclockwise. Thus, the arc curves downward instead of upward and the happy snowman is now sad. e. The upper torso “disappears” since it merges with the background.
Chapter 3
Using Classes and Objects
3.1 Creating Objects SR 3.1
A null reference is a reference that does not refer to any object. The reserved word null can be used to check for null references before following them.
SR 3.2
The new operator creates a new instance (an object) of the specified class. The constructor of the class is then invoked to help set up the newly created object.
SR 3.3
The following declaration creates a String variable called author and initializes it: String author = new String("Fred Brooks");
For strings, this declaration could have been abbreviated as follows: String author = "Fred Brooks";
This object reference variable and its value can be depicted as follows:
author
SR 3.4
"Fred Brooks"
To set an integer variable size to the length of a String object called name, you code: size = name.length();
SR 3.5
Two references are aliases of each other if they refer to the same object. Changing the state of the object through one reference changes it for the other because there is actually only one object. An object is marked for garbage collection only when there are no valid references to it.
3.2 The String Class SR 3.6
Strings are immutable. The only way to change the value of a String variable is to reassign it a new object. Therefore, the variables changed by the statements are: a. none, b. s1, c. none, d. s3.
771
772
aPPendIx n Answers to Self-Review Questions
SR 3.7
The output produced is: o Found 11 5
SR 3.8
The following statement prints the value of a String object in all uppercase letters: System.out.println(title.toUpperCase());
SR 3.9
The following declaration creates a String object and sets it equal to the first 10 characters of the String description; String front = description.substring(0, 10);
3.3 Packages SR 3.10 A Java package is a collection of related classes. The Java standard class library is a group of packages that support common programming tasks. SR 3.11 Each package contains a set of classes that support particular programming activities. The classes in the java.net package support network communication and the classes in the javax.swing class support the development of graphical user interfaces. SR 3.12 The Scanner class and the Random class are part of the java.util package. The String and Math classes are part of the java.lang package. SR 3.13 The Point class, according to the online Java API documentation, represents a location with coordinates (x, y) in two-dimensional space. SR 3.14 An import statement establishes the fact that a program uses a particular class, specifying what package that class is a part of. This allows the programmer to use the class name (such as Random) without having to fully qualify the reference (such as java.util.Random) every time. SR 3.15 The String class is part of the java.lang package, which is automatically imported into any Java program. Therefore, no separate import declaration is needed.
3.4 The Random Class SR 3.16 A call to the nextInt method of a Random object returns a random integer in the range of all possible int values, both positive and negative.
a P P e n d I x n Answers to Self-Review Questions
SR 3.17 Passing a positive integer parameter x to the nextInt method of a Random object returns a random number in the range of 0 to x−1. So a call to nextInt(20) will return a random number in the range 0 to 19, inclusive. SR 3.18 The ranges of the expressions are: a. From 0 to 49 d. From -25 to 24
b. From 10 to 14
c. From 5 to 14
SR 3.19 The expressions to generate the given ranges are: a. generator.nextInt(31); b. generator.nextInt(10) + 10; c. generator.nextInt(11) - 5;
// range is 0 to 30 // range is 10 to 19 // range is -5 to 5
3.5 The Math Class SR 3.20 A class or static method can be invoked through the name of the class that contains it, such as Math.abs. If a method is not static, it can be executed only through an instance (an object) of the class. SR 3.21 The values of the expressions are: a. 20
b. 16.0
c. 16.0
d. 243.0
e. 125.0
f. 4.0
SR 3.22 The following statement prints the sine of an angle measuring 1.23 radians: System.out.println(Math.sin(1.23));
SR 3.23 The following declaration creates a double variable and initializes it to 5 raised to the power 2.5: double result = Math.pow(5, 2.5);
SR 3.24 Examples of methods that are not listed in Figure 3.5 include: static int min(int a, int b) static float max(long a, long b) static long round(double a)
3.6 Formatting Output SR 3.25 To obtain a NumberFormat object for use within a program, you request an object using one of the static methods provided by the NumberFormat class. The method you invoke depends upon your intended use of the
773
774
aPPendIx n Answers to Self-Review Questions
object. For example, if you intend to use it for formatting percentages, you might code: NumberFormat fmt = NumberFormat.getPercentInstance();
SR 3.26 a. The statement is: NumberFormat moneyFormat = NumberFormat.getCurrencyInstance();
Do not forget, you also must import java.text.NumberFormat into your program. b. The statement is: System.out.println(moneyFormat.format(cost));
c. If the locale is the United States, the output will be $54.89. If the locale is the United Kingdom, the output will be £54.89. SR 3.27 To output a floating point value as a percentage, you first obtain a NumberFormat object using a call to the static method getPercentageInstance of the NumberFormat class. Then, you pass the value to be formatted to the format method of the formatter object, which returns a properly formatted string. For example: NumberFormat fmt = NumberFormat.getPercentageInstance(); System.out.println(fmt.format(value));
SR 3.28 The following code will prompt for and read in a double value from the user and then print the result of taking the square root of the absolute value of the input value to two decimal places: Scanner scan = new Scanner(System.in); DecimalFormat fmt = new DecimalFormat("0.00"); double value, result; System.out.print("Enter a double value: "); value = scan.nextDouble(); result = Math.sqrt(Math.abs(value)); System.out.println(fmt.format(result));
3.7 enumerated Types SR 3.29 The following is a declaration of an enumerated type for movie ratings: enum Ratings {G, PG, PG13, R, NC17}
SR 3.30 Under the listed assumptions, the output is: clubs hearts 0 2
a P P e n d I x n Answers to Self-Review Questions
SR 3.31 By using an enumerated type, you guarantee that variables of that type will only take on the enumerated values.
3.8 Wrapper Classes SR 3.32 A wrapper class is defined in the Java standard class library for each primitive type. In situations where objects are called for, an object created from a wrapper class may suffice. SR 3.33 The corresponding wrapper classes are Byte, Integer, Double, Character, and Boolean. SR 3.34 One approach is to use the constructor of Integer, as follows: holdNumber = new Integer(number);
Another approach is to take advantage of autoboxing, as follows: holdNumber = number;
SR 3.35 The following statement uses the MAX_VALUE constant of the Integer class to print the largest possible int value: System.out.println(Integer.MAX_VALUE);
3.9 Components and Containers SR 3.36 Both a frame and a panel are containers that can hold GUI elements. However, a frame is displayed as a separate window with a title bar, whereas a panel cannot be displayed on its own. A panel is often displayed inside a frame. SR 3.37 The term that best matches is a. container e. lightweight
b. frame c. panel d. heavyweight f. content pane g. label h. layout manager
SR 3.38 If you resize the frame by dragging the bottom right corner toward the right, the saying changes from being spread across two lines to being on one line. This happens because no special instructions were included to describe the layout of the container, in which case components of a panel arrange themselves next to each other if the size of the panel allows. SR 3.39 The best description is “Labels are added to a panel, which is added to a content pane of a frame.” SR 3.40 The results of the changes are a. Due to the new dimensions the panel is larger and square.
775
776
aPPendIx n Answers to Self-Review Questions
b. The saying is not visible. You just see a black panel because the saying, which is written in black, blends in with the background. c. There is no change. d. Since the labels are added in the opposite order, the saying is “backwards”—that is, it reads “but raise your hand first.” followed by “Question authority.”
3.10 nested Panels SR 3.41 The containment hierarchy of a graphical user interface identifies the nesting of elements within the GUI. For example, in a particular GUI, suppose some labels and buttons are contained within a panel that is contained within another panel that is contained within a frame. The containment hierarchy can be represented as a tree that indicates how all the elements of a GUI are nested within each other. SR 3.42 In the NestedPanels program, there are three panels created: subPanel1, subPanel2, and primary. SR 3.43 In the NestedPanels program, subPanel1 and subPanel2 are added to the primary panel. The primary panel is explicitly added to the content pane of the frame.
3.11 Images SR 3.44 One frame, one panel, one image icon, and three labels are declared in the LabelDemo program. SR 3.45 In the label instantiation statement from the LabelDemo program: label2 = new JLabel("Devil Right", icon, SwingConstants.CENTER);
the first parameter defines the text, the second parameter provides the image, and the third parameter indicates the horizontal alignment of the label. SR 3.46 The results of the changes are: a. Changing the horizontal alignment of the labels has no visual effect. The horizontal alignment describes only how text and icons are aligned within a label. Since a label’s area is typically exactly the size needed to display the label, label alignment within that area is irrelevant. b. The change in the text position results in the text “Devil Right” appearing to the right of the second image, instead of to its left.
a P P e n d I x n Answers to Self-Review Questions
c. The change in the text position results in a run-time error— “Bottom” is not a valid argument for the setHorizontalTextPosition method. d. Since you changed the vertical position of the text within the label, the text “Devil Above” appears directly on the third image.
Chapter 4
Writing Classes
4.1 Classes and Objects Revisited SR 4.1
An attribute is a data value stored in an object and defines a particular characteristic of that object. For example, one attribute of a Student object might be that student’s current grade point average. Collectively, the values of an object’s attributes determine that object’s current state.
SR 4.2
An operation is a function that can be done to or done by an object. For example, one operation of a Student object might be to compute that student’s current grade point average. Collectively, an object’s operations are referred to as the object’s behaviors.
SR 4.3
Some attributes and operations that might be defined for a class called Book that represents a book in a library are:
SR 4.4
Attributes
Operations
idNumber onShelfStatus readingLevel dueDate
checkOut checkIn isAvailable placeOnHold setStatus
The answers are: a. False – Identifying classes to help us solve a problem is a key step in object-oriented programming. In addition to identifying classes that already exist, we also identify, design, and implement new classes, as needed. b. True – We call such operations mutators. c. True – The result of many operations depends on the current state of the object on which they are operating. d. False – In Java, the state of an object is represented by its instance data.
777
778
aPPendIx n Answers to Self-Review Questions
4.2 anatomy of a Class SR 4.5
A class is the blueprint of an object. It defines the variables and methods that will be a part of every object that is instantiated from it. But a class reserves no memory space for variables. Each object has its own data space and, therefore, its own state.
SR 4.6
The instance data of the Die class are MAX, an integer constant equal to 6 that represents the number of faces on the die and therefore the maximum value of the die, and faceValue, an integer variable that represents the current “up” or face value of the die.
SR 4.7
The methods defined for the Die class that can change the state of a Die object are roll and setFaceValue.
SR 4.8
When you pass an object to a print or println method, the toString method of the object is called automatically to obtain a string description of the object. If no toString method is defined for the object, then a default string is used. Therefore, it is usually a good idea to define a toString method when defining classes.
SR 4.9
The scope of a variable is the area within a program in which the variable can be referenced. An instance variable, declared at the class level, can be referenced in any method of the class. Local variables, including the formal parameters, declared within a particular method, can be referenced only in that method.
SR 4.10 A UML diagram helps us visualize the entities (classes and objects) in a program as well as the relationships among them. UML diagrams are tools that help us capture the design of a program prior to writing it.
4.3 encapsulation SR 4.11 A self-governing object is one that controls the values of its own data. Encapsulated objects, which don’t allow an external client to reach in and change its data, are self-governing. SR 4.12 An object’s interface is the set of public operations (methods) defined on it. That is, the interface establishes the set of services the object will perform for the rest of the system. SR 4.13 A modifier is a Java reserved word that can be used in the definition of a variable or method and that specifically defines certain characteristics of its use. For example, by declaring a variable with private visibility, the variable cannot be directly accessed outside of the object in which it is defined.
a P P e n d I x n Answers to Self-Review Questions
SR 4.14 A constant might be declared with public visibility, because that would not violate encapsulation. Because the value of a constant cannot be changed, it is not generally a problem for another object to access it directly. SR 4.15 The modifiers affect the methods and variables in the following ways: a. A public method is called a service method for an object because it defines a service that the object provides. b. A private method is called a support method because it cannot be invoked from outside the object and is used to support the activities of other methods in the class. c. A public variable is a variable that can be directly accessed and modified by a client. This explicitly violates the principle of encapsulation and therefore should be avoided. d. A private variable is a variable that can be accessed and modified only from within the class. Variables almost always are declared with private visibility.
4.4 anatomy of a Method SR 4.16 Although a method is defined in a class, it is invoked through a particular object to indicate which object of that class is being affected. For example, the Student class may define the operation that computes the grade point average (GPA) of a student, but the operation is invoked through a particular Student object to compute the GPA for that student. The exception to this rule is the invocation of a static method (see Chapter 3), which is executed through the class name and does not affect any particular object. SR 4.17 An invoked method may return a value, which means it computes a value and provides that value to the calling method. The calling method usually uses the invocation and thus its return value, as part of a larger expression. SR 4.18 An explicit return statement is used to specify the value that is returned from a method. The type of the return value must match the return type specified in the method definition. SR 4.19 A return statement is required in methods that have a return type other than void. A method that does not return a value could use a return statement without an expression, but it is not necessary. Only one return statement should be used in a method. SR 4.20 An actual parameter is a value sent to a method when it is invoked. A formal parameter is the corresponding variable in the header of the
779
780
aPPendIx n Answers to Self-Review Questions
method declaration; it takes on the value of the actual parameter so that it can be used inside the method. SR 4.21 The following code implements the requested getFaceDown method.: //--------------------------------------------------// Face down value accessor. //--------------------------------------------------public int getFaceDown() { return (MAX + 1) - faceValue; }
SR 4.22 In the Transactions program a. Three Account objects are created. b. Two arguments (actual parameters) are passed to the withdraw method when it is invoked on the acct2 object. c. No arguments (actual parameters) are passed to the addInterest method when it is invoked on the acct3 object. SR 4.23 The method getBalance is a classic accessor method. One can also classify the toString method as an accessor, since it returns information about the object. The deposit, withdraw, and addInterest methods all provide both mutator and accessor capabilities, because they can be used to change the account balance and also return the value of the balance after the change is made. All of the methods mentioned above are service methods––they all have public visibility and provide a service to the client.
4.5 Constructors Revisited SR 4.24 Constructors are special methods in an object that are used to initialize the object when it is instantiated. SR 4.25 A constructor has the same name as its class, and it does not return a value.
4.6 Graphical Objects SR 4.26 The “content” of the panel created in the SmilingFace program is defined in the SmilingFacePanel class. SR 4.27 In the SmilingFace program, the paintComponent method of the panel object is invoked automatically when the panel object SmilingFacePanel is instantiated.
a P P e n d I x n Answers to Self-Review Questions
SR 4.28 There are many ways to add a pair of eyeglasses to the smiling face. The following code, inserted after the code that draws the nose and mouth, is one approach. page.drawOval(BASEX+17, page.drawOval(BASEX+42, page.drawLine(BASEX+3, page.drawLine(BASEX+62, page.drawLine(BASEX+39,
BASEY+23, BASEY+23, BASEY+27, BASEY+27, BASEY+29,
21, 21); 21, 21); BASEX+17, BASEX+76, BASEX+42,
// glasses BASEY+27); BASEY+27); BASEY+29);
SR 4.29 The following code implements the requested constructor: //--------------------------------------------------// Constructor: Sets up this circle with the // specified values. //--------------------------------------------------public Circle(Color shade, int upperX, int upperY) { diameter = (int) (Math.random() * 180) + 20; color = shade; x = upperX; y = upperY; }
It might be better to define and use constants of 180 and 20 in the Circle class, or perhaps pass those values to the constructor from the client as arguments.
4.7 Graphical User Interfaces SR 4.30 Events usually represent user actions. A listener object is set up to listen for a certain event to be generated from a particular component. SR 4.31 No, we cannot add any listener to any component. Each component generates a certain set of events, and only listeners of those types can be added to the component.
4.8 Buttons SR 4.32 A JButton object generates an action event when the button is pushed. When that occurs, the actionPerformed method of the action listener associated with that button is invoked. SR 4.33 To change the PushCounterPanel class so that instead of displaying a count of how many times the button was pushed it displays a count
781
782
aPPendIx n Answers to Self-Review Questions
“trail,” you can define a new instance variable of the PushCounterPanel class as follows: private String display = "0";
Then change the code in the actionPerformed method to be: count++; display = display + count; label.setText("Pushes: " + display);
4.9 Text Fields SR 4.34 In the Fahrenheit program, when a user types a number into the text box of the interface and presses the Enter (or Return) key, the text field component generates an action event. The TempListener class that is listening for that event reacts by getting the text from the text box, transforming the text into an integer that represents the given Fahrenheit temperature, calculating the corresponding Celsius temperature and saving it to the resultLabel. The contents of the resultLabel then appear on the screen. SR 4.35 To make the change to the FahrenheitPanel class, first remove the outputLabel from the class since it is no longer needed. Then, change the code that sets the result label to: String hold = text + " degrees Fahrenheit = "; hold += celsiusTemp + " degrees Celsius"; resultLabel.setText(hold);
Chapter 5
Conditionals and Loops
5.1 Boolean expressions SR 5.1
The flow of control through a program determines the program statements that will be executed on a given run of the program.
SR 5.2
Each conditional and loop is based on a boolean condition that evaluates to either true or false.
SR 5.3
The equality operators are equal (==) and not equal (!=). The relational operators are less than (<), less than or equal to (<=), greater than (>), and greater than or equal to (>=). The logical operators are not (!), and (&&), and or (||).
a P P e n d I x n Answers to Self-Review Questions
SR 5.4
Assuming the given declarations, the values are: a. true, b. true, c. false, d. true, e. true, f. true, g. true, h. false, i. true, j. true
SR 5.5
A truth table is a table that shows all possible results of a boolean expression, given all possible combinations of variables and conditions.
SR 5.6
The truth table is:
done
!done
(value > 0) || !done
true
true
false
true
true
false
true
true
false
true
false
false
false
false
true
true
value > 0
783
SR 5.7 The truth table is:
c1
c2
!c1
!c2
c1 && !c2
!c1 && c2
c1 && !c2 || !c1 && c2
true
true
false
false
false
false
false
true
false
false
true
true
false
true
false
true
true
false
false
true
true
false
false
true
true
false
false
false
5.2 The if Statement SR 5.8
Based on the given assumptions, the output would be: a. red white yellow b. blue yellow c. blue yellow
SR 5.9
A block statement groups several statements together. We use them to define the body of an if statement or loop when we want to do multiple things based on the boolean condition.
SR 5.10 A nested if occurs when the statement inside an if or else clause is an if statement. A nested if lets the programmer make a series of decisions. Similarly, a nested loop is a loop within a loop.
784
aPPendIx n Answers to Self-Review Questions
SR 5.11 Based on the given assumptions, the output would be: a. red orange white b. black blue green c. yellow green
yellow
SR 5.12 if (temperature <= 50) { System.out.println("It is cool."); System.out.println("Dress warmly."); } else if (temperature > 80) { System.out.println("It is System.out.println("Dress } else { System.out.println("It is System.out.println("Dress }
warm."); cooly.");
pleasant."); pleasantly.");
5.3 Comparing data SR 5.13 Because they are stored internally as binary numbers, comparing floating point values for exact equality will be true only if they are the same bit-by-bit. It’s better to use a reasonable tolerance value and consider the difference between the two values. SR 5.14 We compare strings for equality using the equals method of the String class, which returns a boolean result. The compareTo method of the String class can also be used to compare strings. It returns a positive, 0, or negative integer result depending on the relationship between the two strings. SR 5.15 //-----------------------------------------------------// Returns true if this Die equals die, otherwise // returns false. //-----------------------------------------------------public boolean equals(Die die) { return (this.faceValue == die.faceValue); }
SR 5.16 if (s1.compareTo(s2) < 0) System.out.println(s1 + "\n" + s2); else System.out.println(s2 + "\n" + s1);
a P P e n d I x n Answers to Self-Review Questions
5.4 The while Statement SR 5.17 An infinite loop is a repetition statement that never terminates. Specifically, the body of the loop never causes the condition to become false. SR 5.18 The output is the integers 0 through 9, printed one integer per line. SR 5.19 The loop is not entered, so there is no output. SR 5.20 Since the value of high always remains larger than the value of low, the code loops continuously, producing many lines of zeros, until the program is terminated. SR 5.21 The output is: 0 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9
2 3 4 5 6 7 8 9
3 4 5 6 7 8 9 10 4 5 6 7 8 9 10 5 6 7 8 9 10 6 7 8 9 10 7 8 9 10 8 9 10 9 10 10
10 10
SR 5.22 int count = 1; System.out.print("divisors of " + value + ":"); while (count <= value) { if ((value % count) == 0) System.out.print(" " + count); count++; }
SR 5.23 int count1 = 1, count2; while (count1 <= value) { System.out.print("divisors of " + count1 + ":"); count2 = 1; while (count2 <= count1) { if ((count1 % count2) == 0) System.out.print(" " + count2); count2++; } System.out.println(); count1++; }
785
786
aPPendIx n Answers to Self-Review Questions
5.5 Iterators SR 5.24 a. Scanner user = new Scanner(System.in); b. Scanner infoFileScan = new Scanner(new File("info.dat"));
c. Scanner infoStringScan = new Scanner(infoString); SR 5.25 The following code prints out the average number of characters per line: int numChars = 0; int numLines = 0;
String holdLine; // Read and process each line of the file while (fileScan.hasNext())
{ numLines++; holdLine = fileScan.nextLine(); numChars += holdLine.length(); } System.out.println ((double)numChars/numLines);
5.6 The ArrayList Class SR 5.26 An ArrayList stores and manages multiple objects at one time. It allows you to access the objects by a numeric index and keeps the indexes of its objects continuous as they are added and removed. An ArrayList dynamically increases its capacity as needed. SR 5.27 An ArrayList generally holds references to the Object class, which means that it can hold any type of object at all (this is discussed further in Chapter 8). A specific type of element can and should be specified in the ArrayList declaration to restrict the type of objects that can be added and eliminate the need to cast the type when extracted. SR 5.28 ArrayList dice = new ArrayList(); SR 5.29 [Andy, Don, Betty]
a P P e n d I x n Answers to Self-Review Questions
Chapter 6
More Conditionals and Loops
6.1 The switch Statement SR 6.1
When a Java program is running, if the expression evaluated for a switch statement does not match any of the case values associated with the statement, execution continues with the default case. If no default case exists, processing continues with the statement following the switch statement.
SR 6.2
If a case does not end with a break statement, processing continues into the statements of the next case. We usually want to use break statements in order to jump to the end of the switch.
SR 6.3
If the user enters 72, the output is: That grade is average. If the user enters 46, the output is: That grade is not passing. If the user enters 123, the output is: That grade is not passing.
SR 6.4
An equivalent switch statement is: switch (num1) { case 5: myChar = break; case 6: myChar = break; case 7: myChar = break; default: myChar =
'W'; 'X'; 'Y'; 'Z';
}
6.2 The Conditional Operator SR 6.5
The conditional operator is a trinary operator that evaluates a condition and produces one of two possible results. A conditional statement, such as the if and switch statements, is a category of statements that allow conditions to be evaluated and the appropriate statements executed as a result.
787
788
aPPendIx n Answers to Self-Review Questions
SR 6.6
char id = (first) ? 'A' : 'B';
SR 6.7
System.out.println("The value is " + ((val <= 10) ? "not" : "") + "greater than 10.");
6.3 The do Statement SR 6.8
A while loop evaluates the condition first. If it is true, it executes the loop body. The do loop executes the body first and then evaluates the condition. Therefore, the body of a while loop is executed zero or more times, and the body of a do loop is executed one or more times.
SR 6.9
The output is the integers 0 through 9, printed one integer per line.
SR 6.10 The code contains an infinite loop. The numbers 10, 11, 12, and so on will be printed until the program is terminated or until the number gets too large to be held by the int variable low. SR 6.11 Scanner scan = new Scanner(System.in); int num, sum = 0; do { System.out.print("enter next number (0 to quit) > "); num = scan.nextInt(); sum += num; } while (num != 0); System.out.println(sum);
6.4 The for Statement SR 6.12 A for loop is usually used when we know, or can calculate, how many times we want to iterate through the loop body. A while loop handles a more generic situation. SR 6.13 The output is:
100
SR 6.14 The output is:
60
SR 6.15 The output is: * *** ***** ******* ********* ***********
a P P e n d I x n Answers to Self-Review Questions
SR 6.16 final int NUMROLLS = 100; int sum = 0; for (int i = 1; i <= NUMROLLS; i++) { sum += die.roll(); } System.out.println((double)sum/NUMROLLS);
Chapter 7
Object-Oriented design
7.1 Software development activities SR 7.1
The four basic activities in software development are requirements analysis (deciding what the program should do), design (deciding how to do it), implementation (writing the solution in source code), and testing (validating the implementation).
SR 7.2
Typically the client provides an initial set of requirements or a description of a problem they would like to have solved. It is the responsibility of the software developer to work with the client to make sure the requirements or problem statement is correct and unambiguous.
SR 7.3
Software development is a problem-solving activity. Therefore, it is not surprising that the four basic development activities presented in this section are essentially the same as the five general problem-solving steps presented in Section 1.6. “Establishing the requirements” directly corresponds to “understanding the problem.” “Designing a solution” and “considering alternative designs” taken together correspond to “creating a design”––in the case of software, the design is the solution. Finally, in both approaches we include “implementation” and “testing” stages.
7.2 Identifying Classes and Objects SR 7.4
Identifying the nouns in a problem specification can help you identify potential classes to use when developing an object-oriented solution to a problem. The nouns in the specification often correspond to objects that should be represented in the solution.
SR 7.5
It is not crucial to identify and define all the methods that a class will contain during the early stages of problem solution design. It is often sufficient to just identify those methods that provide the primary responsibilities of the class. Additional methods can be added to a class as needed, when you evolve and add detail to your design.
789
790
aPPendIx n Answers to Self-Review Questions
7.3 Static Class Members SR 7.6
Memory space for an instance variable is created for each object that is instantiated from a class. A static variable is shared among all objects of a class.
SR 7.7
Assuming you decide to use the identifier totalBalance, the declaration is: private static int totalBalance = 0;
SR 7.8
Assuming that the minimum required is 100 and you decide to use the identifier MIN_BALANCE, the declaration is: public static final int MIN_BALANCE = 100;
SR 7.9
The main method of any program is static, and can refer only to static or local variables. Therefore, a main method could not refer to instance variables declared at the class level.
7.4 Class Relationships SR 7.10 A dependency relationship between two classes occurs when one class relies on the functionality of the other. It is often referred to as a “uses” relationship. SR 7.11 A method executed through an object might take as a parameter another object created from the same class. For example, the concat method of the String class is executed through one String object and takes another String object as a parameter. SR 7.12 An aggregate object is an object that has other objects as instance data. That is, an aggregate object is one that is made up of other objects. SR 7.13 The this reference always refers to the currently executing object. A non-static method of a class is written generically for all objects of the class, but it is invoked through a particular object. The this reference, therefore, refers to the object through which that method is currently being executed.
7.5 Interfaces SR 7.14 A class can be instantiated; an interface cannot. An interface contains a set of abstract methods for which a class provides the implementation. SR 7.15 public interface Nameable { public void setName(String name); public String getName(); }
a P P e n d I x n Answers to Self-Review Questions
SR 7.16 a. False – An interface can also include constants. b. True – There is no body of code defined for an abstract method. c. True – An interface is a collection of constants and abstract methods. d. False – Although the class must define the methods that are included in the interface, the class can also define additional methods. e. True – As long as each of the implementing classes provides the required methods. f. True – As long as the class provides the required methods for each interface it implements. g. False – Although the signatures of the methods must be the same, the implementations of the methods can be different.
7.6 enumerated Types Revisited SR 7.17 Using the enumerated type Season as defined in this section, the output is winter summer 0 June through August
7.7 Method design SR 7.18 Method decomposition is the process of dividing a complex method into several support methods to get the job done. This simplifies and facilitates the design of the program. SR 7.19 Based on the PigLatinTranslator class: a. The service provided by the class, namely to translate a string into Pig Latin, is accessed through a static method. Therefore, there is no need to create an object of the class. It follows that there is no need for a constructor. b. The methods defined as private methods do not provide services directly to clients of the class. Instead, they are used to support the public method translate. c. The Scanner object declared in the translate method is used to scan the string sentence, which is passed to the method by the client. SR 7.20 The sequence of calls is: a. translate – translateWord - beginsWithVowel b. translate – translateWord - beginsWithVowel beginsWithBlend
791
792
aPPendIx n Answers to Self-Review Questions
c. translate – translateWord – beginsWithVowel–beginsWithBl end – translateWord – beginsWithVowel – translateWord – beginsWithVowel – beginsWithBlend – translateWord – beginsWithVowel - beginsWithBlend
SR 7.21 Objects are passed to methods by copying the reference to the object (its address). Therefore, the actual and formal parameters of a method become aliases of each other.
7.8 Method Overloading SR 7.22 Overloaded methods are distinguished by having a unique signature, which includes the number, order, and type of the parameters. The return type is not part of the signature. SR 7.23 a. They are distinct. b. They are not distinct. The return type of a method is not part of its signature. c. They are not distinct. The names of a method’s parameters are not part of its signature. d. They are distinct. SR 7.24 //-----------------------------------------------------// Sets up the new Num object, storing a default value // of 0. //-----------------------------------------------------public Num() { value = 0;
}
7.9 Testing SR 7.25 The word that best matches is a. regression e. test case
b. review f. test suite
c. walkthrough d. defects g. black-box h. white-box
7.10 GUI design SR 7.26 The general guidelines for GUI design include: know the needs and characteristics of the user, prevent user errors when possible, optimize user abilities by providing shortcuts and other redundant means
a P P e n d I x n Answers to Self-Review Questions
to accomplish a task, and be consistent in GUI layout and coloring schemes. SR 7.27 A good user interface design is very important because to the user, the interface is the program. Since it is the only way the user interacts with the program, in the user’s mind the interface represents the entire program.
7.11 Layout Managers SR 7.28 A layout manager is consulted whenever the visual appearance of its components might be affected, such as when the container is resized or when a new component is added to the container. SR 7.29 Flow layout attempts to put as many components on a row as possible. Multiple rows are created as needed. SR 7.30 Border layout is divided into five areas: North, South, East, West, and Center. The North and South areas are at the top and bottom of the container, respectively, and span the entire width of the container. Sandwiched between them, from left to right, are the West, Center, and East areas. Any unused area takes up no space, and the others fill in as needed. SR 7.31 A glue component in a box layout dictates where any extra space in the layout should go. It expands as necessary, but takes up no space if there is no extra space to distribute.
7.12 Borders SR 7.32 The BorderFactory class contains several methods used to create borders that can be applied to components. SR 7.33 The border types presented in this section include: empty—buffering space only, line—a simple line, etched—etched groove, bevel—component appears raised or sunken, titled—text title, matte—edges may have separate sizes, and compound—a combination of two borders.
7.13 Containment Hierarchies SR 7.34 The containment hierarchy for a GUI is the set of nested containers and the other components they contain. The containment hierarchy can be described as a tree.
793
794
aPPendIx n Answers to Self-Review Questions
SR 7.35 The containment hierarchy tree for the LeftRight application GUI presented in Chapter 5 is:
JFrame JPanel JPanel
JPanel JButton
Chapter 8
JButton
arrays
8.1 array elements SR 8.1
An array is an object that stores a list of values. The entire list can be referenced by its name, and each element in the list can be referenced individually based on its position in the array.
SR 8.2
Each element in an array can be referenced by its numeric position, called an index, in the array. In Java, all array indexes begin at zero. Square brackets are used to specify the index. For example, nums[5] refers to the sixth element in the array called nums.
SR 8.3
a. 61, b. 139, c. 73, d. 79, e. 74, f. 11
8.2 declaring and Using arrays SR 8.4
An array’s element type is the type of values that the array can hold. All values in a particular array have the same type, or are at least of compatible types. So we might have an array of integers, or an array of boolean values, or an array of Dog objects, etc.
SR 8.5
Arrays are objects. Therefore, as with all objects, to create an array we first create a reference to the array (its name). We then instantiate the array itself, which reserves memory space to store the array elements. The only difference between a regular object instantiation and an array instantiation is the bracket syntax.
SR 8.6
int[] ages = new int[100];
SR 8.7
int[] faceCounts = new int[6];
a P P e n d I x n Answers to Self-Review Questions
SR 8.8
Whenever a reference is made to a particular array element, the index operator (the brackets that enclose the subscript) ensures that the value of the index is greater than or equal to zero and less than the size of the array. If it is not within the valid range, an ArrayIndexOutOfBoundsException is thrown.
SR 8.9
An off-by-one error occurs when a program’s logic exceeds the boundary of an array (or similar structure) by one. These errors include forgetting to process a boundary element as well as attempting to process a nonexistent element. Array processing is susceptible to off-by-one errors because their indexes begin at zero and run to one less than the size of the array.
SR 8.10 for (int index = 0; index < values.length; index++) { values[index]++; }
SR 8.11 int sum = 0; for (int index = 0; index < values.length; index++) { sum += values[index]; } System.out.println(sum);
SR 8.12 An array initializer list is used in the declaration of an array to set up the initial values of its elements. An initializer list instantiates the array object, so the new operator is not needed. SR 8.13 An entire array can be passed as a parameter. Specifically, because an array is an object, a reference to the array is passed to the method. Any changes made to the array elements will be reflected outside of the method.
8.3 arrays of Objects SR 8.14 An array of objects is really an array of object references. The array itself must be instantiated, and the objects that are stored in the array must be created separately. SR 8.15 a. String[] team = new String[6]; b. String[] team = {"Amanda", "Clare", "Emily", "Julie", "Katie", "Maria"}; SR 8.16 a. Book[] library = new Book[10]; b. library[0] = new Book("Starship Troopers", 208);
795
796
aPPendIx n Answers to Self-Review Questions
8.4 Command-Line arguments SR 8.17 A command-line argument is data that is included on the command line when the interpreter is invoked to execute the program. Command-line arguments are another way to provide input to a program. They are accessed using the array of strings that is passed into the main method as a parameter. SR 8.18 //-----------------------------------------------------// Prints the sum of the string lengths of the first // two command line arguments. //-----------------------------------------------------public static void main(String[] args) { System.out.println(args[0].length() + args[1].length()); }
SR 8.19 //-----------------------------------------------------// Prints the sum of the first two command line // arguments, assuming they are integers. //-----------------------------------------------------public static void main(String[] args) { System.out.println(Integer.parseInt(args[0]) + Integer.parseInt(args[1])); }
8.5 Variable Length Parameter Lists SR 8.20 A Java method can be defined to accept a variable number of parameters by using ellipses (...) in the formal parameter list. When a set of values is passed to the method, they are automatically converted to an array. This allows the method to be written in terms of array processing without forcing the calling method to create the array. SR 8.21 public int distance(int ... legs) { int sum = 0; for (int leg : legs) { sum += leg; } return sum; }
SR 8.22 double travelTime(int speed, int ... legs) { int sum = 0;
a P P e n d I x n Answers to Self-Review Questions
for (int leg : legs) { sum += leg; } return (double)sum/speed; }
8.6 Two-dimensional arrays SR 8.23 A multidimensional array is implemented in Java as an array of array objects. The arrays that are elements of the outer array could also contain arrays as elements. This nesting process could continue for as many levels as needed. SR 8.24 int high = scores[0][0]; int low = high; for (int row = 0; row < scores.length; row++) for (int col = 0; col < scores[row].length; col++) { if (scores[row][col] < low) low = scores[row][col]; if (scores[row][col] > high) high = scores[row][col]; } System.out.println(high − low);
8.7 Polygons and Polylines SR 8.25 A polyline is defined by a series of points that represent its vertices. The drawPolyline method takes three parameters to specify its shape. The first is an array of integers that represent the x coordinates of the points. The second is an array of integers that represent the y coordinates of the points. The third parameter is a single integer that indicates the number of points to be used from the arrays. SR 8.26 A polygon is always closed, whereas a polyline may be open. The first and last coordinates of a polygon are automatically connected; that is not the case for polylines. SR 8.27 The results of the changes are: a. The flame below the rocket is now solid red, because a polygon is always closed and we specified it to be filled in. b. The rocket ship’s window disappears, because only the first two points are used to draw the polygon, which results in an “invisible” line being drawn instead of the window.
797
798
aPPendIx n Answers to Self-Review Questions
c. The rocket ship and flames now appear sideways (i.e., horizontal), because exchanging the x and y coordinates of all of the points reflects the drawing across the line x = y. d. The rocket ship and flames are framed by a yellow diamond; because the yellow polygon is drawn first, everything else is visible on top of it. e. Almost all of the picture is hidden by the yellow polygon; because the yellow polygon is drawn last, it hides the other components of the drawing that fall within its coordinates.
8.8 Mouse events SR 8.28 A mouse event is an event generated when the user manipulates the mouse in various ways. There are several types of mouse events that may be of interest in a particular situation, including the mouse being moved, a mouse button being pressed, the mouse entering a particular component, and the mouse being dragged. SR 8.29 The sequence of events is mouse pressed, mouse released, and mouse clicked. SR 8.30 The sequence of events is mouse pressed, mouse exited, and mouse clicked. There are also a series of mouse motion events generated. SR 8.31 The mouse event responded to in the Dots program is mouse pressed. The mouse events responded to in the RubberLines program are mouse pressed and mouse dragged. SR 8.32 Some possible responses include: highlight a game square when a mouse enters its space if it represents a legal move; place an X (or an O) in a game square if the user clicks on it at the appropriate time; allow the user to drag an X (or an O) to a square.
8.9 Key events SR 8.33 A key event is generated when a keyboard key is pressed, which allows a listening program to respond immediately to the user input. The object representing the event holds a code that specifies which key was pressed. SR 8.34 a. keyPressed b. keyTyped, keyReleased c. VK_UP d. arrowLeft.gif e. arrowRight.gif
a P P e n d I x n Answers to Self-Review Questions
Chapter 9
Inheritance
9.1 Creating Subclasses SR 9.1
A child class is derived from a parent class using inheritance. The methods and variables of the parent class automatically become a part of the child class, subject to the rules of the visibility modifiers used to declare them.
SR 9.2
Because a new class can be derived from an existing class, the characteristics of the parent class can be reused without the error-prone process of copying and modifying code.
SR 9.3
Each inheritance derivation should represent an is-a relationship: the child is-a more specific version of the parent. If this relationship does not hold, then inheritance is being used improperly.
SR 9.4
The protected modifier establishes a visibility level (like public and private) that takes inheritance into account. A variable or method declared with protected visibility can be referenced by name in the derived class, while retaining some level of encapsulation. Protected visibility allows access from any class in the same package.
SR 9.5
The super reference can be used to call the parent’s constructor, which cannot be invoked directly by name. It can also be used to invoke the parent’s version of an overridden method.
SR 9.6
public class SchoolBook2 extends Book2 { private int ageLevel; //--------------------------------------------------// Constructor: Sets up the schoolbook with the // specified number of pages and age level (assumed // to be between 4 and 16 inclusive). //--------------------------------------------------public SchoolBook2(int numPages, int age) { super(numPages); ageLevel = age; } //--------------------------------------------------// Returns a string that describes the age level. //--------------------------------------------------public String level() { if (ageLevel <= 6) return "Pre-school";
799
800
aPPendIx n Answers to Self-Review Questions
else if (ageLevel <= 9) return "Early"; else if (ageLevel <= 12) return "Middle"; else return "Upper";
} }
SR 9.7
With single inheritance, a class is derived from only one parent, whereas with multiple inheritance, a class can be derived from multiple parents, inheriting the properties of each. The problem with multiple inheritance is that collisions must be resolved in the cases when two or more parents contribute an attribute or method with the same name. Java supports only single inheritance.
9.2 Overriding Methods SR 9.8
A child class may prefer its own definition of a method in favor of the definition provided for it by its parent. In this case, the child overrides (redefines) the parent’s definition with its own.
SR 9.9
The answers are: a. True – The child “overrides” the parent’s definition of the method if both methods have the same signature. b. False – A constructor is a special method with no return type which has the same name as its class. If you tried to override the parent’s constructor, you would create a syntax error since all methods except constructors must have a return type. c. False – A final method cannot be overridden (that’s why it is “final”). d. False – On the contrary, the need to override methods of a parent class occurs often when using inheritance. e. True – Such a variable is called a shadow variable. You can do this, but it may lead to confusing situations and its use is discouraged.
9.3 Class Hierarchies SR 9.10 There are many potential answers to this problem. SR 9.11 All classes in Java are derived, directly or indirectly, from the Object class. Therefore, all public methods of the Object class, such as equals and toString, are available to every object.
a P P e n d I x n Answers to Self-Review Questions
SR 9.12 The only Java class that does not have a parent class is the Object class. As mentioned in the previous answer, all other classes are derived from Object either directly or indirectly. Object is the root of the Java inheritance tree. SR 9.13 An abstract class is a representation of a general concept. Common characteristics and method signatures can be defined in an abstract class so that they are inherited by child classes derived from it. SR 9.14 It is a contradiction to define an abstract class as final. An abstract class is “incomplete” because it contains abstract methods. Typically the definitions of these methods are completed by one or more classes that extend the abstract class. But a final class cannot be extended, so there would be no way to complete its definition. SR 9.15 A new interface can be derived from an existing interface using inheritance, just as a new class can be derived from an existing class.
9.4 Visibility SR 9.16 A class member is not inherited if it has private visibility, meaning that it cannot be referenced by name in the child class. However, such members do exist for the child and can be referenced indirectly. SR 9.17 The Pizza class can refer to the variable servings explicitly, because it is declared with protected visibility. It cannot, however, refer to the calories method explicitly, because the calories method is declared as private.
9.5 designing for Inheritance SR 9.18 An inheritance derivation represents an “is-a” relationship when the child class represents a more specific version of the parent class. For example, a dictionary is a type of book, so if a Dictionary class extends a Book class, the inheritance represents an “is-a” relationship. SR 9.19 Common features of classes should appear as high as possible in a class hierarchy, as long as it is appropriate for the features to be at the level where they are defined. This approach supports understandability, consistency, and reuse. SR 9.20 You can define a class with multiple roles by having the class implement more than one interface. SR 9.21 You should override the toString method of a parent in its child class, even when the method is not invoked through the child by your current
801
802
aPPendIx n Answers to Self-Review Questions
applications, to avoid problems at a later time. Someone who later uses the class directly or extends the class may assume the existence of a valid toString method. SR 9.22 The final modifier can be applied to a particular method, which keeps that method from being overridden in a child class. It can also be applied to an entire class, which keeps that class from being extended at all.
9.6 The Component Class Hierarchy SR 9.23 a. True, b. True, c. False, d. False, e. False, f. True SR 9.24 The benefits include not having to worry about the details of applet creation and execution, or how the applet interacts with the browser, or security concerns. Essentially, you do not have to worry about anything that would be a common concern across all applets; such concerns have already been handled. You just have to worry about what makes your applet different from other applets.
9.7 extending adapter Classes SR 9.25 An adapter class is a class that implements a listener interface, providing empty definitions for all of its methods. A listener class can be created by extending the appropriate adapter class and overriding the methods of interest. SR 9.26 The OffCenterPanel class extends the JPanel class. The JPanel class inherits from all of the other classes mentioned. Therefore, an OffCenterPanel object “is” a JPanel, and a JComponent, and a Container, and an Object. SR 9.27 The OffCenterListener class extends the MouseAdapter class. Since the MouseAdapter class includes methods for each of the mouse events, the OffCenterListener class inherits those methods and does not need to define them directly.
9.8 The Timer Class SR 9.28 An object created from the Timer class produces an action event at regular intervals. It can be used to control the speed of an animation. SR 9.29 The Timer constructor is called in the ReboundPanel constructor to set the initial delay and to associate a listener with the timer. The start
a P P e n d I x n Answers to Self-Review Questions
method is also called in the ReboundPanel constructor to begin the timer countdown initially. The timer is never stopped in the Rebound program. SR 9.30 a. The smiling face would move faster if the timer delay were decreased. b. The smiling face would move slower if the timer delay were increased. c. The image could be changed by specifying a new file in the call to the ImageIcon constructor. d. The smiling face would make larger jumps if the values of moveX and moveY were increased. e. The smiling face would move faster when it hits the edge if, in the actionPerformed method, the timer delay were decreased in both of the if statements.
Chapter 10
Polymorphism
10.1 Late Binding SR 10.1 Polymorphism is the ability of a reference variable to refer to objects of various types at different times. A method invoked through such a reference is bound to different method definitions at different times, depending on the type of the object referenced. SR 10.2 Compile time binding is considered more efficient than dynamic binding. Compile time binding occurs before the program is executed and therefore does not delay the execution progress of the program. Dynamic binding occurs while the program is running and therefore does affect the runtime efficiency of the program.
10.2 Polymorphism via Inheritance SR 10.3 In Java, a reference variable declared using a parent class can be used to refer to an object of the child class. If both classes contain a method with the same signature, the parent reference can be polymorphic. SR 10.4 Yes, the statements are legal. Since a CDPlayer is a MusicPlayer, it is legal to assign an object of class CDPlayer to a variable of class MusicPlayer. SR 10.5 No, the third statement is not legal. A MusicPlayer is not necessarily a CDPlayer. It is not legal to perform cdplayer = mplayer without using an explicit cast operation. Consider that the mplayer variable could potentially represent many different kinds of music players: CD players, record players, mp3 players, etc. Suppose at the time of the assignment statement, it represents an mp3 player. Then, you would
803
804
aPPendIx n Answers to Self-Review Questions
be assigning an mp3 player object to a CDPlayer variable. That, most likely, doesn’t make sense and would cause problems if it was allowed to happen. SR 10.6 When a child class overrides the definition of a parent’s method, two versions of that method exist. If a polymorphic reference is used to invoke the method, the version of the method that is invoked is determined by the type of the object being referred to, not by the type of the reference variable. SR 10.7 The StaffMember class is abstract because it is not intended to be instantiated. It serves as a placeholder in the inheritance hierarchy to help organize and manage the objects polymorphically. SR 10.8 The pay method has no meaning at the StaffMember level, so is declared as abstract. But by declaring it there we guarantee that every object of its children will have a pay method. This allows us to create an array of StaffMember objects, which is actually filled with various types of staff members, and pay each one. The details of being paid are determined by each class as appropriate. SR 10.9 It depends. The pay method invocation is polymorphic. The actual method that is invoked is determined at run time and is based on the class of the object referenced by the current (according to the value of count) element of the staff list.
10.3 Polymorphism via Interfaces SR 10.10
An interface name can be used as the type of a reference. Such a reference variable can refer to any object of any class that implements that interface. Because all classes implement the same interface, they have methods with common signatures, which can be dynamically bound.
SR 10.11
a. b. c. d.
illegal – Speaker is an interface and interfaces do not have constructors. legal – the Dog class implements Speaker. legal – note that all the classes involved implement Speaker. legal – Philosopher implements Speaker, so it is legal to assign a philosopher object to a speaker variable. e. illegal – first is declared to be a Speaker, so we cannot invoke the Philosopher method pontificate through first.
10.4 Sorting SR 10.12
The Comparable interface contains a single method called compareTo, which should return an integer that is less than zero, equal to zero,
a P P e n d I x n Answers to Self-Review Questions
or greater than zero if the executing object is less than, equal to, or greater than the object to which it is being compared, respectively. SR 10.13
SR 10.14
The sequence of changes the selection sort algorithm makes to the list of numbers is: 5
7
1
8
2
4
3
1
7
5
8
2
4
3
1
2
5
8
7
4
3
1
2
3
8
7
4
5
1
2
3
4
7
8
5
1
2
3
4
5
8
7
1
2
3
4
5
7
8
The sequence of changes the insertion sort algorithm makes to the list of numbers is: 5
7
1
8
2
4
3
5
7
1
8
2
4
3
1
5
7
8
2
4
3
1
5
7
8
2
4
3
1
2
5
7
8
4
3
1
2
4
5
7
8
3
1
2
3
4
5
7
8
SR 10.15
The sorting methods in this chapter all operate on an array of Comparable objects. So the sorting method doesn’t really “know” what the objects are, other than that they are comparable and therefore have a compareTo method that can be invoked.
SR 10.16
Selection sort and insertion sort are generally equivalent in efficiency, because they both take about n2 number of comparisons to sort a list of n numbers. Selection sort, though, generally makes fewer swaps. Several sorting algorithms are more efficient than either of these.
10.5 Searching SR 10.17
a. 4, b. 1, c. 15, d. 15
SR 10.18
A binary search assumes that the search pool is already sorted and begins by examining the middle element. Assuming the target is not found, approximately half of the data is eliminated as viable candidates. Then, the middle element of the remaining candidates is examined, eliminating another quarter of the data. This process continues until the element is found or all viable data has been examined.
SR 10.19
a. 1, b. 3, c. 4, d. 4
805
806
aPPendIx n Answers to Self-Review Questions
10.6 designing for Polymorphism SR 10.20–SR 10.22 For the questions in this section, reasonable arguments can be made for using either inheritance or interfaces in each of the situations described. The point of the questions is to have students think about choices, consider alternative approaches, and practice making technical arguments to support their decisions.
Chapter 11
exceptions
11.1 exception Handling SR 11.1 An exception is an object that defines an unusual or erroneous situation. An error is similar, except that an error generally represents an unrecoverable situation and should not be caught. SR 11.2 A thrown exception can be handled in one of three ways: it can be ignored, which will cause a program to terminate; it can be handled where it occurs using a try statement; or it can be caught and handled higher in the method calling hierarchy.
11.2 Uncaught exceptions SR 11.3 a. False – Exceptions and errors are related but are not always the same thing. b. True – Division by zero is invalid, so an exception is thrown. c. False – An exception must be either handled or thrown. d. True – If the exception is not handled, the program will terminate and display a message. e. True – That is the purpose of the call stack trace.
11.3 The try-catch Statement SR 11.4 A catch phrase of a try statement defines the code that will handle a particular type of exception. SR 11.5 The finally clause of a try statement is executed no matter how the try block is exited. If no exception is thrown, the finally clause is executed after the try block is complete. If an exception is thrown, the appropriate catch clause is executed; then the finally clause is executed.
a P P e n d I x n Answers to Self-Review Questions
SR 11.6 The output produced is: a. finally the end
b. one caught finally the end c. two caught finally the end d. finally
11.4 exception Propagation SR 11.7 If an exception is not caught immediately when thrown, it begins to propagate up through the methods that were called to get to the point where it was generated. The exception can be caught and handled at any point during that propagation. If it propagates out of the main method, the program terminates. SR 11.8 If the exception generating code was added to the level2 method, just before the call to the level3 method, then the output would not include any mention of “Level 3” – this is because the call to level 3 does not occur since the exception is raised before the call is made. SR 11.9 There is no change. The exception is still raised in level 3. The new code in level 2 does not get executed.
11.5 The exception Class Hierarchy SR 11.10
A checked exception is an exception that must be either (1) caught and handled or (2) listed in the throws clause of any method that may throw or propagate it. This establishes a set of exceptions that must be formally acknowledged in the program one way or another. Unchecked exceptions can be ignored completely in the code if desired.
SR 11.11
a. True – It inherits from RunTimeException which inherits from Exception. b. True – It inherits from Throwable through RunTimeException and Exception. c. False – It inherits from RunTimeException so it is unchecked. d. True – It does not inherit from RunTimeException. e. True – See, for example, the OutOfRangeException defined in this section. f. False – The ArithmeticException is unchecked.
807
808
aPPendIx n Answers to Self-Review Questions
SR 11.12
If the input is 42, the program defined OutOfRangeException is thrown in main, the message “Input value is out of range.” is printed along with the stack trace that consists of just information about CreatingExceptions. main, and the program terminates. If the input is -3, the same thing happens. If the input is the string “thirty,” then a library defined InputMismatchException is thrown, a stack trace that consists of information about five methods is printed, and the program terminates. I/O exceptions are the topic of the next section of this textbook.
11.6 I/O exceptions SR 11.13
A stream is a sequential series of bytes that serves as a source of input or a destination for output.
SR 11.14
The standard I/O streams in Java are System.in, the standard input stream; System.out, the standard output stream; and System.err, the standard error stream. Usually, standard input comes from the keyboard and standard output and error go to a default window on the monitor screen.
SR 11.15
The Stream object we have been using explicitly throughout this book is the System.out object. We have used it when printing output from our programs. Sometimes we have also used the System.in object, to create Scanner objects for reading input from the user.
SR 11.16
The main method definition of the CreatingExceptions program does not include a throws InputMismatchException clause, because the Scanner class takes care of that—there is no need to repeat code in the main method when it is already included in a helper class.
SR 11.17
The main method definition of the TestData program does not include a throws FileNotFoundException clause, because the FileWriter class takes care of that—there is no need to repeat code in the main method when it is already included in a helper class.
SR 11.18
If the PrintWriter constructor of the TestDate class is passed the fw object instead of the bw object, the program still works. The only difference is that the program does not use the buffering capabilities of the BufferedWriter class and therefore the processing may not be as efficient.
11.7 Tool Tips and Mnemonics SR 11.19
A tool tip is a small amount of text that can be set up to appear when the cursor comes to rest on a component. It usually gives information about that component.
a P P e n d I x n Answers to Self-Review Questions
SR 11.20
A mnemonic is a character that can be used to activate a control, such as a button, as if the user had used a mouse to do so. The user activates a mnemonic by holding down the ALT key and pressing the appropriate character.
SR 11.21
A component should be disabled if it is not a viable option for the user at a given time. Not only does this prevent user error, but also it helps clarify what the current valid actions are.
SR 11.22
The class(es), and the line(s) of code from the class(es), that provide the listed functionality are a. LightBulb − panel.setBackground(Color.black) b. LightBulbControls - offButton.setToolTipText("Turn it off!") c. LightBulbControls - onButton.setMnemonic(‘n’) OffListener - onButton.setEnabled(true)
d. OnListener - onButton.setEnabled(false) e. LightBulbPanel − on = true
11.8 Combo Boxes SR 11.23
A combo box is a component that allows the user to choose from a set of options in a pull-down list. An editable combo box also allows the user to enter a specific value.
SR 11.24
The JukeBox program ensures that it doesn’t try to play a song associated with the "Make a Selection. . ." combo box option by setting the corresponding entry in the music array to null.
SR 11.25
There are two action listeners defined in the JukeBox program. The ComboListener listens for a mouseclick on the combo box selection list. The ButtonListener listens for a mouseclick on one of the two buttons (play and stop).
SR 11.26
The JukeBox program associates the combo box selection made by the user with a specific audio clip by storing the audio clips in an array music; storing the descriptions of the music, in the same order, in an array musicNames; generating the combo box used to make music selections based on the array musicNames; and using the index returned from a combo box selection to set the current audio clip from the music array.
11.9 Scroll Panes SR 11.27
A scroll pane can have a vertical scroll bar on the right side and/or a horizontal scroll bar along the bottom. The programmer can determine, in
809
810
aPPendIx n Answers to Self-Review Questions
either case, whether the scroll bar should always appear, never appear, or appear as needed to be able to view the underlying component. SR 11.28
If you change the first parameter passed to the Dimension constructor within the TransitMap program to 1000, when the map appears, it is in a wider container—there is no horizontal scroll bar at the bottom of the map, because the entire width of the map already fits in the container.
11.10 Split Panes SR 11.29
Divider bars separate split panes into distinct right/left or top/bottom sections. The bars can be dragged to make one section larger and the other section smaller so that users can control what they see.
SR 11.30
In general, all of the options of a JList object are visible to the user, whereas with a combo box the user must “open” the box to see the options.
Chapter 12
Recursion
12.1 Recursive Thinking SR 12.1
Recursion is a programming technique in which a method calls itself, solving a smaller version of the problem each time, until the terminating condition is reached.
SR 12.2
The recursive part of the definition of a List is used nine times to define a list of 10 numbers. The base case is used once.
SR 12.3
Infinite recursion occurs when there is no base case that serves as a terminating condition or when the base case is improperly specified. The recursive path is followed forever. In a recursive program, infinite recursion will often result in an error that indicates that available memory has been exhausted.
SR 12.4
A base case is always required to terminate recursion and begin the process of returning through the calling hierarchy. Without the base case, infinite recursion results.
SR 12.5
5 * n = 5 if n = 1, 5 * n = 5 + (5 * (n − 1)) if n > 1
12.2 Recursive Programming SR 12.6
Recursion is not necessary. Every recursive algorithm can be written in an iterative manner. However, some problem solutions are much more elegant and straightforward when written recursively.
a P P e n d I x n Answers to Self-Review Questions
SR 12.7
Avoid recursion when the iterative solution is simpler and more easily understood and programmed. Recursion has the overhead of multiple method calls and is not always intuitive.
SR 12.8
If n < 0 a −1 is returned; otherwise the number of digits in the integer n is returned.
SR 12.9
The recursive solution below is more complicated than the iterative version, so it normally would not be done in this way. // Returns 5 * num, assumes num > 0 private static int multByFive(int num) { int result = 5; // when num == 1 if (num > 1) result = 5 + multByFive(num - 1); return result; }
SR 12.10
Indirect recursion occurs when a method calls another method, which calls another method, and so on until one of the called methods invokes the original. Indirect recursion is usually more difficult to trace than direct recursion, in which a method calls itself.
12.3 Using Recursion SR 12.11
The MazeSearch program recursively processes each of the four positions adjacent to the “current” one unless either (1) the current position is outside of the playing grid or (2) the final destination position is reached.
SR 12.12
a. The original maze is defined when the grid array is declared and initialized. b. A test to see if we have arrived at the goal occurs at the second if statement in the traverse method. c. A location is marked as having been tried in the first statement in the first if block of the traverse method. d. A test to see if we already tried a location occurs in the second if statement of the valid method.
SR 12.13
a. valid 0,0 valid 1,0 valid 2,0 valid 1,1 b. valid 0,0 c. valid 0,0 valid 1,0 valid 2,0 valid 1,1 valid 0,0 valid 1,-1 valid 0,1 valid 1,1 valid 0,2 valid -1,0 valid 0,-1
SR 12.14
valid -1,1 valid 0,0
The Towers of Hanoi puzzle of N disks is solved by moving N−1 disks out of the way onto an extra peg, moving the largest disk to
811
812
aPPendIx n Answers to Self-Review Questions
its destination, then moving the N−1 disks from the extra peg to the destination. This solution is inherently recursive because, to move the substack of N−1 disks, we can use the same process. SR 12.15
For an initial stack of one disk, there is one call to the moveTower method. For an initial stack of two disks, there are three calls. For three disks, there are seven calls. For every disk added, the number of calls increases by double the previous number, plus one.
12.4 Recursion in Graphics SR 12.16
The base case of the TiledPictures program is a minimal size for the images to be produced. If the size of the area is smaller than the preset minimum, the recursion terminates.
SR 12.17
A fractal is a geometric shape that can be composed of multiple versions of the same shape at different scales and different angles of orientation. Recursion can be used to draw the repetitive shapes over and over again.
Chapter 13
Collections
13.1 Collections and data Structures SR 13.1 A collection is an object whose purpose is to store and organize primitive data or other objects. Some collections represent classic data structures that are helpful in particular problem-solving situations. SR 13.2 Yes, the ArrayList class provides an abstract data type. The ArrayList class provides a collection of information. It provides operations for storing and accessing the information. The implementation details are hidden from us—that is, we do not need to know anything about how the information is stored or how the operations are implemented in order to use an ArrayList object. SR 13.3 An abstract data type (ADT) is a collection of data and the operations that can be performed on that data. An object is essentially the same thing in that we encapsulate related variables and methods in an object. The object hides the underlying implementation of the ADT, separating the interface from the underlying implementation, permitting the implementation to be changed without affecting the interface.
a P P e n d I x n Answers to Self-Review Questions
13.2 dynamic Representations SR 13.4 A dynamic data structure is constructed using references to link various objects together into a particular organization. It is dynamic in that it can grow and shrink as needed. New objects can be added to the structure, and obsolete objects can be removed from the structure at run time by adjusting references between objects in the structure. SR 13.5 To insert a node into a list, first find the node that comes before the new node (let’s call it beforeNode). Then, set the new node’s next pointer equal to beforeNode’s next pointer. Then, set beforeNode’s next pointer to the new node. A special case exists when inserting a node at the beginning of the list. SR 13.6 To delete a node from a list, first find the node that comes before the node to be deleted (let’s call it beforeNode). Then, set beforeNode’s next pointer to the deleted node’s next pointer. A special case exists when deleting the first node of the list. SR 13.7 set count = 0; current = first; while current != null count++; current = current.next; return count;
SR 13.8 Each node in a doubly linked list has references to both the node that comes before it in the list and the node that comes after it in the list. This organization allows for easy movement forward and backward in the list and simplifies some operations. SR 13.9 A header node for a linked list is a special node that holds information about the list, such as references to the front and rear of the list and an integer to keep track of how many nodes are currently in the list.
13.3 Linear data Structures SR 13.10
A queue is a linear data structure like a list, but it has more constraints on its use. A general list can be modified by inserting or deleting nodes anywhere in the list, but a queue only adds nodes to one end (enqueue) and takes them off of the other (dequeue). Thus, a queue uses a first-in, first-out (FIFO) approach.
SR 13.11
The contents of the queue from front to rear are: 72 37 15
813
814
aPPendIx n Answers to Self-Review Questions
SR 13.12
A stack is a linear data structure that adds (pushes) and removes (pops) nodes from one end. It manages information using a last-in, first-out (LIFO) approach.
SR 13.13
The contents of the stack from top to bottom are: 37 72 5
SR 13.14
The Stack class is defined in the java.util package of the Java standard class library. It implements a generic stack ADT. The Stack class stores Object references, so the stack can be used to store any kind of object.
13.4 non-Linear data Structures SR 13.15
Trees and graphs are both non-linear data structures, meaning that the data they store is not organized in a linear fashion. Trees create a hierarchy of nodes. The nodes in a graph are connected using general edges.
SR 13.16
a. tree, b. graph, c. graph, d. tree
13.5 The Java Collections aPI SR 13.17
The Java Collections API is a set of classes in the Java standard class library that represents collections of various types, such as ArrayList and LinkedList.
SR 13.18
A generic type is a collection object that is implemented such that the type of objects it manages can be established when the collection is created. This allows some compile-time control over the types of objects that are added to the collection and eliminates the need to cast the objects when they are removed from the collection. All collections in the Java Collections API have been implemented as generic types.
Index Symbols
-- (decrement operator),
106–107 '' (single quotes for character literals), 99 – (subtraction operator), 101 !== (equal to operator), 235–236 " " (double quotes for character string literals), 55, 84, 89 $ (dollar sign character), 57–58 % (remainder operator), 101, 303–304 %= (remainder assignment operator), 107–108 & (AND bitwise operator), 703 && (AND logical operator), 236–238 () (parentheses), 88–89, 103–104, 111–112, 141, 239 arithmetic expressions, 103–104 boolean expressions, 239 casting data conversion, 111–112 invoking methods, 141 operator precedence using, 88–89, 103–104 * (asterisk for Import declaration), 151 *– (multiplication assignment operator, 107 * (multiplication operator), 101 . (dot operator for accessing methods), 141 / (division operator), 101–102 / (slash for path separation), 270 /* and */ (multiple line comments), 56 /** and */ (external comments), 56 // (comments),
/= (division assignment
operator), 107 ? : (conditional operator), 300–301 [] (square brackets for arrays), 406–407, 410 \' (single quote escape sequence), 89 \" (double quote escape sequence), 89 \\ (backslash escape sequence), 89 \b (backspace escape sequence), 89 \n (newline escape sequence), 89 \r (carriage return escape sequence), 89 \t (tab escape sequence), 89 ^ (XOR bitwise operator), 704 _ (underscore character), 57–58 { } (class definition), {} (braces for if statements), 247, 251 | (NOT logical operator), 236–238 | (OR bitwise operator), 704 || (OR logical operator), 236–238 ~ (NOT bitwise operator), 704 + (plus symbol), 86–88, 101 addition operator, 101 string concatenation, 86–88 ++ (increment operator), 106–107 += (addition assignment operator), 107 < (less than relational operator), 235–236 << (left–shift bitwise operator), 704 <= (less than or equal to relational operator), 235–236 <> (HTML tags), 124
–= (subtraction assignment
operator), 107 == (not equal to operator),
235–236 > (greater than relational
operator), 235–236 >= (greater than or equal to
relational operator), 235–236 >> (right–shift bitwise operator), 704 >>> (right–shift with zeros bitwise operator), 704
A
abstract classes, 487–488 abstract data types (ADT), 644 abstract methods, 349 abstract modifier (reserved word), 349, 487–488, 711 Abstract Windowing Toolkit (AWT), 170, 494–495 accessor methods, encapsulation, 197–198 action events, 221–222, 274–277, 283–285 actual parameters (arguments), 201 adapter classes, extended events using, 497–500 add method, 171 addresses, 39, 47, 49–50 Internet, 47, 49–50 memory, 39 network, 47 Advanced Research Projects Agency (ARPA) network (ARAPNET), 49 aggregation, 342–346 algorithms, 358–359 aliases, 142–144 analog signals, AND bitwise operator (&), 704
815
816
index
applets, 121–129, 627–637, 667, 719–720 appletviewer tool for, 121–122 applications compared to, 121–122 bytecode for, 122 drawing shapes, 125–129 executing, 122–124 fractals, 630–637 Graphics class, 125–129 HTML tags <> for, 124 import statements for, 122–123 Java programming, 121–129, 719–720 methods for, 123, 719–720 paint method, 123 public declaration of, 123 recursion used for, 627–637 tiled pictures, 627–630 World Wide Web execution of, 124 application programming interfaces (API), 53–54, 148–149, 660–661 applications, 30, 121–122 arc angle, 127 architecture, computer hardware functions, 37–39 arg identifier, 57–58, 428–429 arguments, command-line, 428–429. See also parameters arithmetic/logic unit, 43 ArrayList class, 271–273 arrays, 271, 405–468, 601–604 bounds checking, 410–415 characters in, 412–415 command-line arguments, 428–429 constructors and, 424–426, 431–433 declaration, 407–427 elements, 406–407 event-driven programs using, 444–458, 601–604 graphical user interfaces (GUIs), 439–458, 601–604 index (subscript) values, 271, 406–407, 410–415 initializer lists, 415–416
instantiation, 407–408, 418–420, 424–426 int[] declaration, 407–408, 434 integers in, 410–412 key events using, 453–458 lists as, 601–604 mouse events using, 444–452 multidimensional, 438–439 new operator, 407–408, 418–419 objects and, 407–410, 418–427 off-by-one errors, 410 parameters as, 416–417, 428–433 polygons drawn using, 439–443 polylines drawn using, 440–442 ragged, 439 square brackets [] used for, 406–407, 410 syntax, 415 two-dimensional, 434–438 variable-length parameter lists, 430–433 variables in, 407–410, 415–416 ASCII character set, 99–100, 699–701 assembly language, 63–64 assignment, 93–95, 103–104, 107–108, 111 addition (+=), 107 arithmetic operator precedence and, 103–104 data conversion by, 111 data values and, 93–95 division (/=), 107 expressions and, 93, 103–104, 107–108 Java defined operations, 107–108 multiplication (*=), 107 operators (=), 93, 103–104, 107–108 remainder (%=), 107–108 statements, 93–95 subtraction (–=), 107 variables and, 93–95 asterisk (*) for Import declaration, 151 autoboxing, 169
B
background color, 127 base case, 610–611 base value, 33 bevel borders, 393–394 binary operators, 102 binary search, 541–544 binary trees, 657 binary values, 33–36, 669 bits, 35–36, 669 black–box testing, 373–374 block statements, 245–249 boolean expressions, 234–239, 252–255 conditional statement decisions and, 234 data comparison using, 252–255 equality operators, 235–236 if statements, 234, 238–239, 252–255 logical operators, 236–238 loop execution time using, 235 parentheses () for, 239 relational operators, 235–236 short-circuited operations, 237–238 truth tables, 236–238 boolean literals, 100 boolean operators, 669, 706 boolean primitive data types, 100, 111, 167 borders, 382–385, 391–395 bevel, 393–394 compound, 394 empty, 393–394 etched, 393–394 GUI programs for, 391–395 layout manager for, 382–385 line, 393–394 matte, 394–395 Swing components use of, 391–395 titled, 394 boundaries, 373–374 black-box testing, 373–374 equivalence categories for, 373–374 bounding rectangle, 125–127 bounds checking, 410–415 array index (subscript) values, 410–415 characters, 412–415
index
integers, 410–412 off-by-one errors, 410 box layout, 387–390 break statements, 265, 296–297 browser, 51 bus, 37 buttons, 218–222, 274–285 action events, 221–222, 274–277, 283–285 check boxes, 277–281 conditional statements for, 274–285 event sources, 274–277 GUI programs for, 218–222, 274–277 item events, 278–281 label font styles, 277–281 listener objects, 217–225, 274–277 push, 218–222, 274–277 radio, 281–285 toggle, 285 by value parameter passing, 364–368 byte integer data type, 97–98, 109–111, 167–168 bytecode, Java programming, 65–66, 122 bytes, 40
C
cache, 41 call stack trace, 566 case sensitivity, Java programming, 58–59 casting (), data conversion by, 111–112 catch clause, 566–570 CD (compact disc) devices, 42–43 CD-ROM device, 42 central processing unit (CPU), 28–29, 38, 41, 43–45 arithmetic/logic unit, 43 cache, 41 computer hardware functions, 28–29, 38, 43–45 control unit, 43 fetch-decode-execute cycle, 44 main memory and, 28–29, 38–41 microprocessor, 44–45 registers, 43–44 system clock, 45
von Neumann architecture, 44 change events, 558 char character data type, 100, 110–111, 167 character strings, 55, 84–91, 142, 254–255 data comparison, 254–255 escape sequences, 89–90 if statements for, 254–255 Java programming, 55, 84 literals (" "), 55, 84, 89, 142 object data and, 84–91, 142, 254–255 parameters of, 84 print and println methods for, 84–85 string concatenation, 86–89 Unicode relationships, 254–255 characters, 99–100, 109–111, 253, 412–415, 670, 699–701 array index values, 412–415 ASCII character set, 99–100, 699, 701 assignment conversion for, 111 bounds checking, 412–415 char, 100, 110–111 control characters, 99, 672, 699 conversion of, 109–112 data comparisons, 253 if statements for, 253 literals (''), 99 narrowing conversion for, 109–110 nonprintable (control), 681, 699–701 primitive data as, 99–100 printable, 683, 699–700 Unicode character set, 100, 699–701 widening conversion for, 109–110 check boxes, GUI creation of, 277–281 checked exceptions, 578 child class, 471, 479–485. See also subclasses Circle class, 214–216 class definition ({}), 55 class hierarchies, 484–488, 494–496, 516–517, 575–578 abstract classes, 487–488
child class and, 484–485 Component class, 494–496 exceptions, 575–578 inheritance and, 484–488, 494–496 Object class, 486–487 polymorphism and, 516–517 classes, 53–54, 57–58, 73–75, 139–184, 185–232, 329–369, 469–512, 516–517 abstract, 487–488 adapter classes, 497–500 aggregation, 342–346 assigning responsibilities to, 331 child, 471, 479–484 Component, 494–496 constructors, 207–208 DecimalFormat, 160–161 dependency, 336–342 encapsulation, 195–198 enumerated types, 164–166, 355–358 event adapter, 497–500 formatting output using, 158–163 graphic-user interfaces (GUIs), 169–179, 217–225 graphical objects, 208–216 identification of, 329–331 import declaration, 150–151 inheritance, 74, 469–512 instance data, 193 interfaces, implementation of, 348–355 Java programming and, 73–75 Java standard class library, 54, 57–58, 148–151 JButton, 219–221 JFrame, 170–173, 211–212 JPanel, 170–173, 208–213 JTextField, 222–225 listener, 221 main method, 188–189 Math, 155–158 methods for, 186–192, 195–208, 358–369 NumberFormat, 158–160 Object, 486–487 object-oriented (OO) programming and, 73–75, 329–348
817
818
index
classes (continued) objects and, 73–74, 139–184, 186–187, 195–198, 207–216, 329–331, 336–343, 346–348 packages, 148–151 parent (base), 471, 476–479 polymorphism and, 516–517 qualified names, 150 Random, 152–155 relationships, 336–348 returned values from, 141–142, 152–153, 155–158 software design, 329–348 static members, 331–335 String, 144–147 subclasses, 470–473 System, 161–163 this method for, 346–348 Timer, 501–504 use of, 139–184 visibility modifiers, 196 wrapper, 167–169 writing, 185–232 clients, 195, 328 clock speed, 45 coding guidelines, 713–717 design, 714 documentation, 716–717 Java programming, 713–717 style, 715–717 collections, 643–666 abstract data types (ADT), 644 data structures for, 644–660 dynamic representations, 645–652 generic types, 660–661 graphs, 658–660 heterogeneous, 644 homogeneous, 644 implementation of, 644 interfaces for, 644 Java Collections API, 660–661 linear data structures, 653–656 linked lists, 646–652 nonlinear data structures, 657–660 queues, 653–654 stacks, 654–656 trees, 657–658
color choosers, GUI programs for, 552–553 Color class, 120–121 color representation, Java graphics, 120–121, 127 combo boxes, GUI programs for, 590–595 command-line applications, 170 command-line arguments, 428–429 comments, 56–57, 724–725 documentation, 55–57, 724–725 double slash (//) symbols for, 56 inline documentation, 55, 57 javadoc, 56, 724–725 javadoc (/** and */) symbols for, 56 multiple line (/* and */) symbols for, 56–57 newline character, 56 tags, 724, 725 Comparable interface, 354 compile-time error, 68 compilers, 65–66 Component class, 494–496 compound borders, 394 computer systems, 27–82 architecture, 37–38 central processing unit (CPU), 28, 43–45 development environments, 66–67 digital technology for, 30–36 errors, 68–69, 71–72 hardware components, 28–29, 36–45 information storage and management, 31–36, 39–43 input/output (I/O) devices, 28, 38–39 Internet, 49–50 Java programming, 52–61, 65–67, 70–75 local area network (LAN), 48–49 memory, 28, 39–43 networks, 46–52 object–oriented (OO) programming, 53, 70–75 processing, 28–36
programming languages, 52–67 programs, 28, 52–75 semantics, 67–68 software, 28–30, 50–51, 65–69, 70–75 syntax, 67–68 Uniform Resource Locators (URL), 51–52 wide area network (WAN), 48–49 World Wide Web (WWW), 51–52 conditional operator (? :), 300–301 conditional statements, 233–294, 295–325 boolean expressions for, 234–238 break, 265, 296–297 buttons developed using, 274–285 continue, 265 data comparison using, 252–255 decisions from, 234 dialog box development using, 317–319 do loops, 235, 301–304, 318–319 drawing programs using, 311–317 events determined using, 274–277 flow of control, 234 for loops, 235, 305–310 graphical user interfaces (GUI), 274–285, 311–319 if, 234, 239–252 if-else, 234, 242–251, 300–301 iterators, 267–270, 308–310 loops, 235–238, 256–265, 295, 301–319 nested, 249–251, 262–265 object management using, 271–273 objects and, 267–285 switch, 234, 296–299 ternary operator (? :) for, 300–301 while loops, 235, 256–265, 267–270 confirm dialog box, 318–319
index
connections, 46–48 constants, data value as, 95–96 constructors, 113–115, 141, 190, 201, 207–216, 424–426, 431–433 arrays using, 424–426, 431–433 default, 207 graphical object characteristics from, 208–216 instantiation using, 113–115, 207, 424–426 invoking (calling), 190, 207 Java programming use of, 113–115, 207–208 new operator for, 113–115, 141, 190 parameters and, 431–433 void modifier, 201, 207–208 containers, 170–176, 217, 376–391, 395–397 add method for, 171 content panes, 171–173 GUI components, 170–176, 217, 376–391, 395–397 heavyweight, 170–171 hierarchy for, 174–176, 395–397 labels, 171–172, 177–179 layout manager for, 173, 376–391 lightweight, 170–171 panels, 170–176 panes, 171–173 top-level, 395 containment hierarchy, 174–176, 395–397 content panes, 171–173 continue statements, 265 control (nonprintable) characters, 99, 672, 699 control flow statements, 374 control unit, 43 controllers, 38 coordinate systems, Java graphics, 118–120, 125
d
data, 83–136, 164–166, 189–190, 193, 201–202, 252–255, 296–297, 355–348, 430–433
applets, 121–129 assignment statements, 93–95 boolean, 100, 111 character strings (" "), 84–91, 254–255 characters, 99–100, 109–112, 253 comparison of types, 252–255 constants, 95–96 constructor, 113–115 conversion, 109–112 declarations, 189–190, 193, 201–202 enumerated types, 164–166, 355–358 escape sequences, 89–90 expressions, 101–109 floating point, 97–98, 109–112, 252–253 graphics, 118–129 Graphics class, 125–129 if statements for, 252–255 input, 115, 117 instance, 193 integers, 97–98, 109–112 interactive programs for, 113–117 lexicographic order, 255 literals, 84, 89, 98–100 local, 201–202 method declaration and, 201–202 new operator, 113–115 object comparisons, 254–255 operators, 86–88, 93, 95, 101–108 output, 116 parameters, 84, 430–433 primitive types, 97–101, 109–113 Scanner class, 113–117 switch statement types, 296–297 Unicode relationships, 254–255 variable-length parameter lists, 430–433 variables, 91–95, 193, 201–202 data conversion, 109–113, 169 assignment, 111 autoboxing, 169 casting (), 111–112 narrowing, 110–111
primitive data types and, 109–111, 169 promotion, 111 widening, 109–110 wrapper class objects and, 169 data structures, 644–660 collections and, 644, 653–660 doubly linked lists, 651 dynamic, 645–652 graphs, 658–660 header nodes, 652 linear, 653–656 linked lists, 646–652 nodes, 657–658 nonlinear, 657–660 object storage using, 644 queues, 653–654 stacks, 654–656 trees, 657–658 data transfer devices, 38 debugging software, 66–67, 69 decimal values, 672 DecimalFormat class, 160–161 declaration, 91–93, 95–96, 113–115, 140–142, 150–151, 189–193, 198–199, 201–202, 407–426, 515–516, 528 arrays, 407–426 asterisk (*) for, 151 bounds checking, 410–415 classes, 150–151 constants, 95–96 constructors and, 115, 141, 207, 424–426 data, 189–190, 193, 201–202 import, 150–151 initializer lists, 415–416 instance data, 193 instantiation and, 113–115, 141, 207, 407–408, 418–420, 424–426 int, 91–93, 140, 407–408 java.util packages, 150–151 local data, 201–202 methods, 189–192, 198–199, 201–202 new operator and, 113–115, 141–142, 407–408, 418–420
819
820
index
declaration (continued) objects, 113–115, 140–142, 407–410, 418–426 parameters and, 416–417 polymorphism and, 515–516, 528 reference variables, 514–516, 528 square brackets [] used for, 407–410, 415 String methods for, 140–142, 418–423 syntax and, 415 variables, 92–93, 140–142, 193, 201–202, 408–410, 415–416 decomposition of methods, 359–364 decrement (–) operator, 106–107 default visibility, 672, 709 defect testing, 372–374 delimiters, 115, 270 dependency, 336–342 development environments, 66–67 diagraph, 658–659 dialog boxes, 317–319, 548–553 color choosers, 552–553 conditional statements used for, 317–319 confirm, 318–319 creation of, 317–319 file choosers, 548–551 input, 318–319 loops for creation of, 317–319 message, 318–319 polymorphism used for, 548–553 Swing package for, 317 digital computers, 31–36 analog information compared to, 81 binary values, 33–36 digitized process, 32–33 sampling rate, 31–33 signals, 32–36 direct access storage devices, 41–42 direct recursion, 615–616 directed graph, 658–659 divide-by-zero error, 259 do loop statements, 301–304, 318–319 infinite, 304
remainder operator (%) for, 303–304 repetition of, 302–304 while clause for, 301–302 documentation, 55–57, 673 coding guidelines, 716–717 comments, 55–57, 723 HTML file generation, 726–727 inline, 55, 57 javadoc generator, 56, 723–727 programming style, 54, 57, 715–717 tags, 724 Domain Name System (DNS), 50 domain names, 49–50 domain server, 50 dot (.) operator for accessing methods, 141 double floating–point data type, 97–98, 110–111, 167–168 doubly linked lists, 651 drawing, 125–129, 208–216, 311–317, 439–443 arc angle, 127 arrays used for, 439–443 background color, 127 bounding rectangle, 125–127 bull’s–eye, 311–314 Circle class, 214–216 conditional statements used for, 311–317 constructors for, 208–216 drawing programs using, 311–317 foreground color, 127 graphical objects, 208–216 Graphics class, 125–129, 439–442 Java standard class library for, 442–443 loops used for, 311–317 ovals, 125–127 paintComponent method, 208, 211, 213–214, 311–314 polygons, 439–443 polylines, 440–442 rectangles, 314–317 shapes, 125–129 start angle, 127
DVD devices, 43 dynamic data structures, 645–652
e
Eclipse IDE software, 67 editors, 65 else clause, 249–251 empty borders, 393–394 encapsulation, 74, 195–198, 473–475 accessor methods, 197–198 client, 195 inheritance and, 473–475 modifiers for, 196–198 mutator methods, 197–198 objects, 74, 195–198 service (support) methods, 196 visibility modifiers, 196–197, 473–475 enumerated types, 164–166, 355–358 equality operators, 235–236 equivalence categories, 373–374 errors, 66–69, 258–259, 371–374, 410, 564 black-box testing, 373 compile-time, 68 debugging software for, 66–67, 69 defect testing, 372–374 divide-by-zero, 258–259 exceptions and, 69, 564 logical, 69 off-by-one, 410 programming, 68–69 run-time, 69, 564 syntax, 69 testing programs for, 371–374 white-box (glass-box) testing, 374 escape sequences, 89–90 etched borders, 393–394 event adapter classes, 497–500 event-driven programs, 217–218, 221–222, 274–285, 444–458, 497–500, 547–548, 553–558, 590–604 action events, 221–222
index
adapter classes, 497–500 arrays used for, 444–458 buttons, 218–222, 274–285 change events, 558 combo boxes, 590–595 conditional statements used for, 274–285 determining event sources, 274–277 graphical-user interfaces (GUIs) as, 217–218 inheritance used for, 497–500 item events, 278–281 key events, 453–458 list selection events, 598–604 listeners, 217–225, 274–277, 448–452, 453–457, 497–500, 595 mouse events, 444–452, 497–500 mouse motion events, 444–445 polymorphism used for, 547–548, 553–558 rubberbanding, 449–452 scroll panes, 595–598 sliders, 553–558 split panes, 598–604 event generation, 741 event processing, 547–548 event sources, 274–277, 444–458 exceptions, 69, 563–607 call stack trace, 566 catch clause, 566–570 checked, 578 class hierarchy, 575–578 combo boxes, 590–595 finally clause, 570 graphic user interfaces (GUI), 583–604 handling, 564, 566–570 inheritance and, 575–578 input/output (I/O), 579–583 mnemonics and, 583–589 propagation, 571–574 run-time errors, 69, 564 scroll panes, 595–598 split panes, 598–604 streams in, 579–580 throw statements, 577–578, 580–582 tool tips and, 583–589
try blocks, 566–570 try-catch statements,
566–570 uncaught, 565–566 unchecked, 578 exponential complexity, 626 expressions, 101–109, 235–238, 270, 721–722 arithmetic operators, 101–102 assignment (=) operators, 103–104, 107–108 boolean, 235–238 data and, 101–109 decrement (–) operator, 106–107 equality operators, 235–236 increment (++) operator, 106–107 logical operators, 236–238 operator precedence, 102–106 parentheses () in, 103–104 postfix operator, 106–107 prefix operator, 106–107 regular, 270, 721–722 relational operators, 235–236 trees, 103 extends modifier (reserved word), 208, 471, 486
F
false boolean value, 100 fetch-decode-execute cycle, 44 file choosers, GUI programs for, 548–551 file generation (HTML), 726–727 file servers, 46 final modifier (reserved word), 95–96, 196, 483, 493–494, 711 finally clause, 570 first-in, first-out (fifo) processing, 653 float floating-point data type, 97–98, 110–111, 167 floating-point data types, 97–98, 109–113, 252–253 assignment conversion for, 111 casting (), 111–112 conversion of, 109–113 data comparison, 252–253 if statements for, 252–253 literals, 98
narrowing conversion of, 109–110 primitive data as, 97–98 promotion conversion for, 111 widening conversion of, 110–111 flow layout, 378–382 font styles, GUI programming for, 277–281 for-each loop, 308–310 for loop statements, 235, 305–310, 434–438 for-each version, 308–310 increment code for, 305–307 initialization of, 305–308 iterators and, 308–310 nested, 434–438 repetition of, 305–306 two-dimensional arrays using, 434–438 foreground color, 127 formal parameters, 201 formatting output, 158–163 DecimalFormat class, 160–161 NumberFormat class, 158–160 printf method, 161–163 fourth-generation language (30GL), 64 fractals, 630–637 frames, 170–176 containment hierarchy, 174–176 content pane, 171–173 Jframe class, 170–173 panes, 171 functional specification, 328
G
garbage, object references, 143–144 generic types, 660–661 graph data structures, 658–660 graphic applications, 627–637 graphical user interfaces (GUIs), 30, 170–179, 217– 225, 274–285, 311–319, 375–397, 439–458, 494–504, 547–558, 583–604, 781. See also event-driven programs Abstract Windowing Toolkit (AWT), 170, 494–495
821
822
index
graphical user interfaces (GUIs) (continued) action events, 221–222, 274–277, 283–285 arrays used for, 439–458, 600–604 borders, 382–385, 391–395 buttons, 218–222, 274–277 change events, 558 classes used for, 169–179, 217–225 color choosers and, 552–553 combo boxes, 590–595 components, 170, 217, 376–391, 494–496, 583–589, 741–743 computer systems and, 30 conditional statements used for, 274–285, 311–319 containers, 170–176, 217, 376–391, 395–397 containment hierarchies, 174–176, 395–397 dialog boxes, 317–319 disabling components, 584, 587–589 drawing programs, 311–317, 439–443 event adapter classes, 497–500 event generation, 741 event processing, 547–548 event sources, 274–277, 444–458 exceptions used for, 583–604 file choosers, 548–551 frames, 170–173 inheritance used for, 494–504 interaction of, 217–225 interface implementation, 221 item events, 278–281 key events, 453–458 labels, 171–172, 177–179 layout managers, 173, 376–391 list components, 601–604 listener objects, 217–225, 274–277, 448–452, 453–457, 497–504, 595 loops used for, 311–317 mnemonics and, 583–589 mouse events, 444–452 object-oriented programming and, 375–397 panels, 170–176
polymorphism used for, 547–558 scroll panes, 595–598 sliders, 553–558 software design and, 375–397 split panes, 598–604 Swing package, 170, 317, 494–496, 583 text fields, 222–225 timer objects, 501–504 tool tips and, 583–589 graphics, 118–121, 121–129, 169–179, 208–216, 627–637 applets used for, 121–129 color representation, 120–121, 127 constructors for, 208–216 coordinate systems, 118–120, 125 drawing, 125–129, 208–216 fractals, 630–637 GUI containers for, 170–176 images, 177–179 Java programming, 117–129 Koch snowflakes, 630–637 labels, 171–172, 177–179 monitor resolution, 118 objects as, 208–216 paint method, 123 panels, 170–176 picture resolution, 118 pixels, 118 recursion used for, 627–637 RGB (red-green-blue) values, 120 tiled pictures and, 627–630 Graphics class, 125–129 grid layout, 385–387 GUI, see graphical user interfaces (GUIs)
H
hard disks, 41 hardware components, 28–29, 36–45 central processing unit (CPU), 28–29, 38, 41, 43–45 computer architecture, 37–39 computer processing functions, 28–29 input/output (I/O) devices, 28, 38–39
main memory, 28–29, 39–41 memory, 28–29, 39–43 secondary memory, 28, 41–43 software and, 28 has-a relationships, 342–343 header nodes, 652 Heavyweight containers, 170–171 hexadecimal values, 676 high-level languages, 63–64 HTML file generation, 726–727 HTML tags (<>), 124 hypermedia, 51 hypertext, 50–52 HyperText Markup Language (HTML), 51 HyperText Transfer Protocol (http), 52
i
identifiers, 57–59, 676 abbreviations for, 59 case sensitivity of, 58–59 coding guidelines, 715 naming, 59 reserved words, 57–58 title case for, 59 if-else statements, 234, 242–251, 300–301 block statements, 245–249 conditional (ternary) operators as, 300–301 nested, 249–251 true/false conditions of, 242–245 if statements, 234, 239–255 boolean expressions () for, 234, 238–239, 252–255 braces {} used in, 247, 251 character data comparisons, 253 data comparison using, 252–255 else clause, 242–251 floating-point data comparisons, 252–253 indentation for, 239–240, 242, 247, 251 nested, 249–251 object comparisons, 254–255 image observer, 453 ImageIcon class, 177–179
index
images, 118–121, 177–179, 627–637. See also drawing color representation, 120–121 coordinate systems, 118–120 fractals, 630–637 Java programming for, 118–121 labels with, 177–179 picture resolution, 118 pixels, 118 recursion used for, 627–637 tiled pictures, 627–630 immutable objects, 144 implementation, 221, 329, 349–354, 644 classes, 349–354 collections, 644 interfaces, 221, 349–354 software design and, 329, 349–354 implements reserved word, 348–354 import statement, 115, 122–123, 150–151 asterisk (*) for, 151 class declaration, 115, 150–151 java.util packages and, 122–123, 150–151 increment code, 305–307 increment (++) operator, 106–107 indentation, 239–240, 242, 247, 251, 715 coding guidelines, 715 if statements, 239–240, 242, 247, 251 nested statements, 251 index values, 271, 406–407, 410–415 array elements, 271, 406–407, 410–415 ArrayList class, 271–273 bounds checking, 410–415 characters, 412–415 integers, 410–412 indirect recursion, 615–616 infinite loops, 260–261, 304 infinite recursion, 610–611 information storage and management, 31–36, 39–43 analog, 31 binary values, 33–36 bits, 35–36 capacity of devices, 40–43 digital, 32–36
main memory, 28–29, 39–41 memory devices, 39–43 sampling rate, 31–33 secondary memory, 28, 41–43 signals, 31–36 inheritance, 74, 469–512, 514–527, 575–578 abstract classes, 487–488 child class, 471, 479–484 class hierarchies, 484–488, 494–496, 575–578 Component class, 494–496 encapsulation and, 473–475 event adapter classes, 497–500 exceptions and, 575–578 extends modifier used for, 471, 486 final modifier used for, 483, 493–494 graphical-user interfaces (GUIs), 494–504 interface hierarchies, 489 is-a relationship of, 471–472 multiple, 479–480 Object class, 486–487 object-oriented programming and, 74, 469–512 overriding methods, 481–483, 523 parent (base) class, 471, 476–479 polymorphism via, 514–527 protected modifier used for, 473–475 reference variables, 514–516 reserved words for, 471, 473–479, 483, 486–488, 490, 493–494 restricting, 493–494 shadow variables, 483–484 siblings, 485 software design for, 492–494 software reuse, 74, 470 subclasses, 470–480 super modifier used for, 476–479, 490, 493 Timer class, 501–504 UML diagrams for, 472, 475 visibility and, 473–475, 489–492 initializer lists, 415–416 input data, 115, 117
input dialog box, 318–319 input/output (I/O), 28, 38–39, 579–583 computer devices, 28, 38–39 exceptions and, 579–583 Java standard class library for, 580 streams, 579–583 input validation, 260 insertion sort, 537–538 instance data, 193 instantiation, 113–115, 141, 207, 407–408, 418–420, 424–426 arrays, 407–408, 418–420, 424–426 constructors, 113–115, 207, 424–426 object declaration and, 141, 407–408, 418–420, 424–426 instruction register, 43 int integer data type, 91–93, 97–98, 110–111, 167–169, 407–408, 434 array declaration using, 407–408, 434 autoboxing, 169 conversion for, 110–111 primitive data, as, 97–98 square brackets ([]) for, 407–408, 434 variable value declaration using, 91–93 wrapper classes for, 167–168 integer data types, 97–98, 109–113, 410–412 array index values, 410–412 assignment conversion of, 111 bounds checking, 410–412 casting () conversion of, 111–112 conversion of, 109–113 literals, 98 narrowing conversion for, 109–110 primitive data as, 97–98 promotion conversion of, 111 widening conversion for, 110–111 integrated development environments (IDEs), 66–67
823
824
index
interactive programming, 113–115 new operator, 113–115, 141, 407–408, 418–420 interfaces, 221, 349–355, 489, 528–530. See also graphical user interfaces (GUIs) Comparable, 354 hierarchies, 489 implementation for, 221, 349–354 inheritance and, 489 Iterator, 354–355 methods for, 348–354, 528–530 polymorphism via, 528–530 reference variables for, 528–530 software design and, 349–355 internal frame, 742 internal nodes, 657 Internet, 49–52 addresses, 47, 49–50 Advanced Research Projects Agency (ARAPA), 49 domain names, 49–50 domain server, 50 hypertext, 50–52 protocol (IP), 49 search engines, 51–52 subdomains, 50 top-level domain (TLD), 50 Transmission Control Protocol (TCP), 49 Uniform Resource Locators (URL), 51–52 World Wide Web (WWW), 51–52 interpreters, 75–66 invisible components, 388–390 invoking (calling) methods, 55, 141, 198–199, 369–371 is-a relationship, 471–472 Iterator interface, 354–355 iterators, 267–270, 308–310, 615 conditional statements and, 267–270, 308–310 delimiters, 270 for–each statements for, 308–310 path separation (/), 270
reading text files using, 268–270 recursion versus, 615 Scanner class for, 267–270
J
java.util packages, 150–151 Java Collections API, 660–661 Java Development Kit (JDK), 67 Java programming, 52–61, 65–67, 70–75, 107–108, 113–117, 118–121, 121–129, 143–144, 148–151, 163–166, 196, 207–208, 376–391, 703–707, 719–720, 729–739 applets, 121–129, 719–720 application programming interfaces (API), 53–54, 148–149 applications, 121–122 assignment operators 107–108 bytecode, 65–66, 122 character strings (" "), 55 class definition ({ }), 55 classes, 73–75, 148–151, 207–208 coding guidelines, 671, 713–717 color representation, 120–121 coordinate systems, 118–120 comments, 56–57 compilers, 65–66 constructors, 113–115, 207–208 deprecated, 53 documentation, 55–57, 716–717 encapsulation, 74 enumerated types, 164–166 event generation, 741 garbage collection, 143–144 graphics, 118–129 identifiers, 57–59, 715 inheritance, 74 inline documentation, 55, 57 integrated development environments (IDEs), 66–67 interactive, 113–117 invoking (calling) methods, 55 language, 52–61 layout managers, 376–391 legacy system, 163 main method, 54–55 methods, 55, 73
modifiers, 709–711, 714 new operator, 113–115 object-oriented (OO) language, 53, 72–75 objects, 72–75, 113–115, 207–208 operators, 703–707 packages, 148–151 PaintBox project, 729–739 polymorphism, 74 primitive data, 72 println method, 55 reserved words, 57–59 Scanner class, 113–117 semantics, 67–68 Software Development Kit (SDK), 67 standard class library, 54, 58 syntax, 67–68, 745–757 terminating, 55 visibility modifiers, 196 white space, 60–61, 115, 715 Java standard class library, 54, 58, 148–151, 158–161, 167–168, 271–273, 442–443, 486–487, 660–661, 731 application programming interfaces (API), 53–54, 148–149, 660–661 ArrayList class, 271–273 collections, 660–661 formatting data output, 158–161 generic types, 660–661 identifiers in, 57–58 import declaration, 150–151 java packages, 150–151, 442–443 modifiers, 709–711 Object class, 486–487 online API documentation, 149–150, 747 packages, 148–151 Polygon class, 442–443 input/output (I/O) streams, 580 visibility modifiers, 709–711 wrapper classes, 167–168 javadoc, 56, 723–727 comments, 56, 723 documentation generation, 56, 723–727 files generated for, 726–727 tags, 724–726
index
JButton class, 219–221 JColorChooser class, 551–553 JComboBox class, 590–595 JFileChooser class,
548–551 JFrame class, 170–173,
211–212 JList class, 601–604 JOptionPane class, 317–319 JPanel class, 170–173,
208–213 JScrollBar class, 595–598 JSlider class, 553–558 JSplitPane class, 598–604 JTextField class, 222–225
K
key events, GUI programs for, 453–458 key repetition, 458 keyboard focus, 458 kilobyte (KB), 40
L
labels, 171–172, 177–179, 277–281 font styles, 277–281 GUI containers, 171–172 images and, 176–179 Jlabel class, 171–172, 177 languages, see programming languages last-in, first–out (lifo) processing, 654 late (dynamic) binding, 514 layered pane, 743 layout managers, 173, 376–391 border, 382–385 box, 387–390 containers and, 173, 376–391 flow, 378–382 grid, 385–387 GUI components using, 376–391 invisible components, 388–390 tabbed panes, 377–378 leaf nodes, 657–658 left-shift operator (<<), 704 legacy systems, 163 lexicographic order, 255 lightweight containers, 170–171
line borders, 393–394 linear search, 539–541 linked lists, 646–652 list components, 601–604 listener objects, 217–225, 274–277, 448–452, 453–457, 497–500, 547–548, 553–558 adapter classes extended for, 497–500 buttons, 218–222, 274–285 key events, 453–457 mouse events, 448–452 polymorphism and, 547–548, 553–558 sliders, 553–558 ListPanel class, 600–604 literals, data types as, 84, 89, 98–100, 142, 419 local area network (LAN), 48–49 local data, 201–202 logical error, 69 logical operators, 236–238 long integer data type, 97, 110 loops, 235–238, 256–265, 295, 301–319 boolean expressions for, 235–238 comparison of, 310 dialog box creation using, 317–319 do statements, 235, 301–304, 318–319 drawing programs using, 311–317 execution time, 238 for-each statements, 308–310 for statements, 235, 305–310 graphical user interfaces (GUI), 311–319 infinite, 260–261, 304 nested, 262–265 while statements, 235, 256–265 low–level languages, 63–64
M
machine language, 63 magnetic storage devices, 41–42 main memory, 28–29, 39–41 addresses, 39
cache, 41 central processing unit (CPU) and, 28–29, 41 locations, 39–40 storage capacity, 40–41 main method, 54–55, 188–189, 428–429 Math class, 155–158 matte borders, 394–395 megabyte (MB), 40 memory, 28–29, 39–43 address, 39 bytes, 40 capacity, 40–43 computer hardware functions, 28–29, 39–43 direct access devices, 41–42 locations, 39–40 magnetic devices, 41–42 main, 28–29, 39–41 random access (RAM), 40 read-only (ROM), 40 secondary, 28, 41–43 sequential access devices, 40 storage devices, 40–43 volatility of, 40 message dialog box, 318–319 methods, 55, 73, 84–85, 140–142, 144–147, 152–155, 155–158, 161–163, 168, 186–192, 195–208, 332–335, 348–355, 358–371, 430–433, 481–483, 514–530, 719–720. See also recursion abstract, 349 accessor, 197–198 algorithms for, 358–359 applets, 123, 719–720 classes and, 186–192, 195–208 constructors as, 141, 190, 207–208 declaration of, 189–192, 198–199 decomposition, 359–364 dot (.) operator for accessing, 141 encapsulation of objects, 195–198 header, 198, 200–201 inheritance and, 481–483, 514–527
825
826
index
methods (continued) interfaces and, 348–354, 528–530 invoking (calling), 55, 141, 198–199, 369–371 late (dynamic) binding, 514 local, 201–202 main, 54–55, 188–189 Math class, 155–158 mutator, 197–198 object behavior and, 73, 186–187, 189 object declaration, 140–142 object-oriented programming and, 332–335, 348–355, 358–371 object reference variables, 73, 140–142 operations as, 186–187 overloading, 369–371 overriding, 481–483, 523 parameter passing, 201–202, 364–368, 430–433 parentheses ( ) for invoking, 141 polymorphism and, 514–530 print, 84–85 printf, 161–163 println, 55, 84–85 pseudorandom number generator, 152–155 Random class, 152–155 reference variables, 73, 140–142, 514–516, 528–530 return statement, 200–201 returned values, 141–142, 152–153, 155–158 signature, 370 static, 155, 168, 332–335 String class, 140–142, 144–147 terminating programs, 55 UML class diagrams for, 363–364 variable–length parameter lists, 430–433 variables in, 73, 140–142, 201–202, 514–516, 528–530 wrapper classes and, 168 microprocessor, 44–45
mnemonics, 63 mnemonics, GUI programs for, 583–589 modifiers, 196–197, 473–475, 489–492, 681, 709–711. See also reserved words encapsulation and, 196–198 inheritance and, 473–475, 489–492 Java programming, 709–711 visibility, 196–197, 473–475, 489–492, 689, 709–710 use of, 709 monitor resolution, 118 mouse events, GUI programs for, 444–452, 497–500 mouse motion events, 444–445 multidimensional arrays, 438–439 multiple inheritance, 479–480 mutator methods, encapsulation, 197–198
n
narrowing conversions, 110–111 native modifier (reserved word), 711 nested panels, 174–176 nested statements, 249–251, 262–265, 434–438 boolean expressions, 249–251 else clause applications, 249–251 for loop statements, 249–251 if statements, 249–251 indentation for, 251 palindrome example, 262–265 two-dimensional arrays using, 434–438 while loops, 262–265 networks, 46–52 addresses, 47, 49–50 computer systems, 46–52 connections, 46–48 file servers, 46 Internet, 49–52 local-area (LAN), 48–49 packets, 47–48 point-to-point connection, 46–47 protocol, 49
Uniform Resource Locators (URL), 51–52 wide area (WAN), 48–49 World Wide Web, 51–52 new operator, 113–115, 141–142, 190, 407–408, 418–420 array declaration, 407–408, 418–420 constructors and, 113–115, 141, 190 instantiation using, 113–115, 141, 407–408, 418–420 object data and, 113–115, 141–142, 418–420 String objects and, 141–142, 418–420 nextLine method, 115 nodes, non-linear data structures, 657–658 nonprintable (control) characters, 681, 699–700 NOT bitwise operator (~), 704 null value setting, 141, 651 number systems, 691–697 base-28, 691 bases higher than ten, 693–694 binary, 691 bits, 691 conversions, 695–697 decimal, 672, 691 hexadecimal, 693 place value, 691–693 NumberFormat class, 158–160
O
object-oriented (OO) programming, 53, 70–75, 193–194, 327–404, 492–494, 545–546 aggregation and, 342–346 assigning responsibilities, 331 borders, 382–385, 391–395 classes and, 73–75, 329–331 containment hierarchies, 395–397 dependency and, 336–342 encapsulation, 74 enumerated types, 355–358 graphical user interfaces (GUI), 375–397
index
inheritance for, 74, 492–494 interfaces, 348–355 language, 53 layout managers, 376–391 methods, 73, 332–335, 358–371 objects and, 72–74, 113–115, 329–331, 342–343, 346–348 overloading methods, 369–371 polymorphism for, 74, 545–546 problem solving, 71–72 software design, 70–75, 327–404, 492–494, 545–546 static class members, 331–335 testing, 371–375 this reserved word and, 346–348 Unified Modeling Language (UML) diagrams, 193–194, 472, 475 objects, 72–74, 113–115, 139–184, 207–225, 254–255, 267–285, 329–331, 336–343, 346–348, 407–410, 418–427, 501–504, 643–666 action events for, 221 aggregate, 342–343 aliases of, 142–144 ArrayList class, 271–273 arrays as, 407–410, 418–427 attributes, 73, 186–187 autoboxing, 169 behavior, 72–73, 186 buttons, 218–222, 274–285 character strings (" ") for, 84–91, 142, 254–255 classes and, 73–74, 139–184, 186–187, 195–198, 207–216, 329–331, 336–343, 346–348 client, 195 collections, 643–666 conditional statements for, 267–285 constructors for, 113–115, 141, 207–216, 424–426
containers, 170–171 creating, 140–144 data comparisons, 254–255 declaration of, 113–115, 140–141, 407–410, 418–427 dependencies among, 336–342 dot (.) operator for accessing methods, 141 encapsulation, 74, 195–198 enumerated types, 164–166 event-driven programs, 217–218 events, 217–225, 274–277 frames, 170–173 frames for, 169–173 garbage, 143–144 graphical, 170–179, 208–216 GUI-based classes for, 170–179, 217–225, 274–285 has-a relationships, 342–343 identification of, 329–331 images, 177–179 immutable, 144 index value, 271–273 inheritance and, 74, 501–504 instantiation, 141, 407–410, 418–420, 424–426 iterators, 267–270 labels, 171–172, 177–179 listeners for GUI interfaces, 217–225, 274–277 methods and, 73, 141–142, 195–198 new operator, 113–115, 141–142, 407–408, 418–420 object-oriented programming and, 72–73, 113–115, 329–331, 342–343, 346–348 operations for, 186–187 ordinal values, 164–165 parentheses ( ) for invoking methods, 141 pointers, 141 reference variables, 140–144 returned values, 141–142 software design and, 329–331, 342–343, 346–348 state, 72, 186 String class, 140–142, 144–147, 418–423
string literals ("") for, 142, 419 text fields, 222–225 this reference for, 346–348 timers, 501–504 variables as, 140–144, 164–166 wrapper classes, 167–169 off-by-one errors, 410 operating systems, 29–30 operations, object behavior and, 186–187. See also methods operators, 86–88, 93, 95, 101–108, 141, 235–238, 300–301, 669 addition (+), 101, 107 arithmetic, 101–102 assignment (=), 93, 107–108 binary, 102 bitwise, 669 boolean expression conditions, 235–238 boolean values, 706 conditional (? :), 300–301 conditional statements and, 235–238, 300–301 decrement (–), 106–107 division (/), 101–102, 107 dot (.) for accessing methods, 141 equality, 235–236 increment (++), 106–107 Java programming, 703–707 logical, 236–238 looping statements and, 235–238 multiplication (*), 101, 107 parentheses () for, 88, 103–104 postfix form, 106–107 precedence, 88, 102–106, 682, 683 prefix form, 106–107 relational, 235–236 remainder (%), 101, 107–108, 303–304 string concatenation (+), 86–88 subtraction (–), 101, 107 ternary (conditional), 300–301 unary, 102 OR bitwise operator (|), 704 ordinal value, 164–165
827
828
index
output data, 55, 84–85, 116, 158–163 DecimalFormat class, 160–161 formatting, 158–163 interactive programming, 116 Java standard class library packages, 158–161 NumberFormat class, 158–160 print method, 84–85 printf method, 161–163 println method, 55, 84–85 overloading methods, 369–371 overriding methods, 481–483, 523
P
packages, 148–151, 682, 726 application programming interfaces (API), 148–149 import declaration, 150–151 java.util, 150–151 visibility of, 682, 709 packets, 47–48 paint method, 123 PaintBox project, 729–739 paintComponent method, 208, 211, 213–214, 311–314 palindrome, nested loop example of, 262–265 panels, 170–176 containment hierarchy, 174–176 Jpanel class, 170–173 nested, 174–176 panes, 171–173, 377–378, 595–604 content, 171–173 exceptions used for, 595–604 frames and, 171 GUI programs for, 171–173, 377–378, 595–604 layout manager and, 377–378 list components for, 601–604 scrolls, 595–598 split, 598–604 tabbed, 377–378 parameters, 84, 201–202, 364–368, 416–417, 428–433 actual (arguments), 201 arg identifier, 428–429 arrays as, 416–417, 428–433
by value passing, 364–368 character strings as, 84 command-line arguments, 428–433 constructors and, 431–433 data as, 84 formal, 201 header specification, 201–202 lists, 201 main method and, 428–429 methods, 201–201, 364–368, 430–433 multiple, 428–433 passing, 201–202, 364–368, 416–417, 430–433 software design and, 364–368 String objects and, 428–429 variable-length lists, 430–433 parent (base) class, 471, 476–479 path separation (/), 270 peripherals, 38 petabyte (PB), 40 picture resolution, 118 pixels, 118 place value, 682 point-to-point connection, 46–47 pointers, 141 polygons, drawing, 439–443 polylines, drawing, 440–442 polymorphism, 74, 513–561 class hierarchy and, 516–517 color choosers and, 552–553 event processing using, 547–548 file choosers and, 548–551 graphical user interfaces (GUI), 547–558 inheritance and, 74, 514–527 interfaces and, 528–530 late (dynamic) binding, 514 methods and, 514–527 reference variables, 514–516, 528–530 searching, 539–545 sliders and, 553–558 software design for, 545–546 sorting, 530–538 super reserved word used for, 523 postfix operator form, 106–107 prefix operator form, 106–107 primary colors, 120
primitive data types, 72, 97–101, 109–113, 167–169, 252–253, 410–415, 683 array index values, 410–415 assignment conversion of, 111 autoboxing, 169 booleans, 100, 167 bounds checking, 410–415 casting () conversion of 111–112 char, 100, 110–111 characters, 99–100, 109–112, 412–415, 670, 699–701 conversion of, 109–113 data values as, 97–101 double, 97–98, 110–111 false, 100 float, 97–98, 110–111 floating point, 97–98, 109–112, 252–253 int, 97–98, 110–111, 167–169 integers, 97–98, 109–113, 410–412 Java programming and, 72 literals, 98 long, 97, 110 narrowing conversion of, 110–111 promotion conversion of, 111 short, 97–98, 109–111 true, 100 types, 97–101 widening conversion for, 109–110 wrapper classes, 167–169 print method, 84–85 printable characters, 683–699 printf method, 161–163 println method, 55, 84–85 private modifier, 196, 709 program counter, 43 programming languages, 52–69 assembly, 63–64 character strings (" "), 55 class definition ({ }), 55 comments, 56–57 compilers for, 65–66 computer error and, 68–69 documentation, 55–57 fourth-generation (30GL), 64 high-level, 63–64 identifiers, 57–59 interpreters for, 65–66
index
invoking (calling) methods, 55 Java, 52–61 low-level, 63–64 machine, 63 methods and, 55 mnemonics, 63 object-oriented (OO), 53 reserved words, 57–58 semantics, 67–68 statements and, 52 syntax, 67–68 target, 65 translating code for, 65–66 programs, 28, 52–75 class definition ({ }), 55 comments, 56–57 compilers, 65–66 computer hardware and, 28 debuggers, 66–67 development environments, 66–67 development of, 62–69 documentation, 55–57 editors, 65 errors, 66–69 integrated development environments (IDEs), 66–67 interpreters, 75–66 invoking (calling) methods, 55 Java, 52–61, 66–69 languages, 52–69 methods, 55, 73 object–oriented (OO), 53, 70–75 semantics, 67–68 software tools for, 28, 65–67 source code, 65 statements, 52 syntax, 67–68 terminating, 55 progress bar, 743 promotion, data conversion by, 111 propagating the exception, 571–574 protected modifier, 196, 473–475, 709 protocol, 49 pseudocode, 359 pseudorandom number generator, 152–155 public modifier, 55, 57–58, 123, 196, 709
push buttons, GUI creation of, 218–222, 274–277
Q
queues, 653–654
R
radio buttons, GUI creation of, 281–285 ragged arrays, 439 random access memory (RAM), 40 Random class, 152–155 read–only memory (ROM), 40 recordable CD (CD–R) devices, 42 recursion, 609–642 direct, 615–616 fractals and, 630–637 graphic applications, 627–637 indirect, 615–616 infinite, 610–611 iteration versus, 615 math use of, 611–612 problem-solving use of, 616–626 programming, 612–616 recursive thinking, 610–612 tiled pictures and, 627–630 Towers of Hanoi problem, 621–626 traversing a maze, 617–621 reference variables, 73, 140–144, 515–516, 528–530 garbage, 143–144 inheritance and, 515–516 interfaces and, 528–530 object aliases for, 142–144 object declaration and, 140–142 polymorphic, 514–516, 528–530 string methods, 140–142 registers, 43–44 regular expressions, 117, 721–722 relational operators, 235–236 remainder (%) operator, 101, 107–108, 303–304 repetition statements, see loops
reserved words, 57–59, 95–96, 100, 196–197, 200–201, 207–208, 331–335, 346–354, 473–479, 483, 486–488, 493–494, 685, 709 abstract, 349, 487–488, 667 boolean, 100 class, 58 constants declared using, 95–96 extends, 471, 486 false, 100 final, 95–96, 196, 483, 493–494, 354, 675 identifiers, 57–58 implements, 348–354 inheritance using, 471, 473–479, 486–488, 490, 493–494 interfaces and, 348–354 Java modifiers, 709–711 Java programming, 58–59 object-oriented design using, 331–335, 346–354 private modifier, 196, 709 protected modifier, 196, 473–475, 709 public modifier, 57–58, 196, 709 return, 200–201, 207 static modifier, 57–58, 331–335, 711 super, 476–479, 490, 493, 523 this reserved word and, 346–348 true, 100 visibility modifiers, 196–197, 473–475 void, 57–58, 200–201, 207–208 return statement, 200–201 returned values, 141–142, 152–153, 155–158 Math class, 155–158 Random class, 152–155 String class, 141–142 review, code evaluation by, 372 rewritable CD (CD–RW) devices, 42 RGB (red-green-blue) values, 120 right-shift operator (>>), 704
829
830
index
right-shift with zeros operator (>>>), 704 robust programs, 260 root nodes, 657–658 rubberbanding, 449–452 run-time error, 69 running sums, 259
S
sampling rate, 31–33 Scanner class, 113–117, 267–270 scope of a variable, 193 scroll panes, GUI programs for, 595–598 search engines, 51–52 searching, 539–545 binary, 541–544 comparison of approaches, 545 linear, 539–541 polymorphism and, 539–545 secondary memory, 28, 41–43 direct access storage devices, 41–42 magnetic storage devices, 41–42 random access memory (RAM), 40 read-only memory (ROM), 40 sequential access storage devices, 40 storage capacity, 41–43 seed value, 152–153 selection sort, 531–533 selection statements, see conditional statements semantics, 67–68 sentinel values, 257–259 sequential access storage devices, 40 service (support) methods, encapsulation, 196 shadow variables, 483–484 short integer data type, 97–98, 109–111 siblings, 485 signals, 31–36 analog, 31 digital, 32–36 sampling rate, 31–33 signature, method invocation and, 370 sliders, GUI programs for, 553–558
software, 28–30, 50–51, 65–69, 70–75, 492–494, 545–546 application, 30 compile-time error, 68 compilers, 65–66 computer system functions, 28–30 debugging, 66–67, 69 development environments, 66–67 editors, 65 errors, 66–69 graphical user interface (GUI), 30 hardware components and, 30 inheritance and design of, 492–494 interpreters, 65–66 Java Development Kit (JDK), 67 logical error, 69 object-oriented programming, 70–75 operating systems, 29–30 polymorphism and design of, 545–546 program development tools, 65–67 run-time error, 69 user interface, 29 software design, 70–75, 327–404, 492–494, 545–546 aggregation and, 342–346 borders, 382–385, 391–395 boundaries, 373–374 classes and, 329–369 clients, 328 containment hierarchies, 395–397 dependency and, 336–342 development activities, 328–329 enumerated types, 355–358 functional specification, 328 graphical user interfaces (GUIs), 375–397 identification of objects and classes, 329–331 implementation, 329, 349–354 inheritance and, 492–494 interfaces and, 348–355 layout managers, 376–391 methods, 332–335, 358–371
objects and, 72–74, 329–331, 342–343, 346–348 parameter passing, 364–368 polymorphism and, 545–546 principles of, 70–75 static class members, 331–335 testing programs for, 329, 371–374 this reserved word and, 346–348 Software Development Kit (SDK), 67 software failure, 137–138, 231–232, 293–294, 403–404, 467–468, 511–512 Ariane 31 Fight 527, 511–512 Denver Airport Baggage Handling System, 231–232 LA Air Traffic Control, 467–468 NASA Mars Climate Orbiter and Polar Lander, 137–138 Therac-51, 293–294 2003 Northeast blackout, 403–404 software reuse, 74, 470 sorting, 530–538 comparison of approaches, 538 insertion, 537–538 polymorphism and, 530–538 selection, 531–533 source code, 65 spacing, coding guidelines for, 715 split panes, GUI programs for, 598–604 stack data structures, 654–656 standard input stream, 115 start angle, 127 statement coverage, 374 static class members, 55, 57–58, 155, 168, 326, 331–335, 711 methods, 155, 168, 332–335 static modifier, 55, 57–58, 331–335, 711 variables, 326, 332
index
streams, exceptions and, 579–580 string concatenation, 86–89 string literals (" "), 55, 84, 142, 419 String objects, 140–142, 144–147, 418–423, 428–429 arg identifier, 428–429 arrays of, 418–423, 428–429 command–line arguments for, 428–429 declaration of objects using, 140–142, 418–423 immutable objects in, 144 index of characters, 144 instantiation using, 141, 418–420 main method and, 428–429 methods, 142–142, 144–147 new operator for, 141–142, 418–420 parameters as, 428–429 reference variables, 140–142 returned values, 141–142 subclasses, 470–484 child class as, 471 creating, 470–473 extends reserved word used for, 471 multiple inheritance, 479–480 overriding methods, 481–483 parent (base) class, 471 protected modifier used for, 473–475 shadow variables, 483–484 super reserved word used for, 476–479 UML class diagrams for, 472, 475 subdomains, 50 subscript values, see index values super modifier(reserved word), 476–479, 490, 493, 523 Swing packages, 170, 317, 391–395, 494–496, 583 switch statements, 234, 296–299 break statement and, 296–297 data types for, 297
default case, 296–297 equal conditions of, 298–299 single value cases of, 296 synchronized modifier (reserved word), 711 syntax, 67–68, 415, 745–757 syntax error, 69 System.err standard I/O stream, 579–580 System.in standard I/O stream, 579 System.out standard I/O stream, 579–580 System class, 161–163 system clock, 45
T
tabbed panes, 377–378 tables, tags, javadoc comments, 724, 725 target language, 65 terabyte (TB), 40 test case, 373 test suite, 373 testing programs, 329, 371–374 black–box, 373–374 boundaries, 373–374 defect, 372–374 equivalence categories, 373–374 review, 372 software design and, 329, 371–374 statement coverage, 374 walkthrough, 372 white-box (glass-box), 374 text fields, 222–225 text files, reading using iterators, 268–270 text processing, 743 this reserved word, 346–348 throw statements, 577–578, 580–582 throws clause, 269–270, 576–581 tiled pictures and, 627–630 Timer class, 501–504 title case, 59 titled borders, 394 toggle buttons, 285 tokens, 115 tool bar, 742 tool tips and, GUI programs for, 583–589
top-level containers, 395 top-level domain (TLD), 50 touch screen systems, 39 Towers of Hanoi recursion problem, 621–626 transient modifier (reserved word), 711 Transmission Control Protocol (TCP), 49 traversing a maze recursion problem, 617–621 tree component, 743 tree data structures, 657–658 true boolean value, 100 truth tables, 236–238 try blocks, 566–570 try-catch statements, 566–570 two-dimensional arrays, 434–438
U
unary operators, 102 unchecked exceptions, 578 Unicode Character Set, 100, 699–701 Unified Modeling Language (UML) diagrams, 193–194, 472, 475 Uniform Resource Locators (URL), 51–52 uninitialized variables, 140 USB flash drives, 41 user interface, 29
V
variable-length parameter lists, 430–433 variables, 91–95, 140–144, 164–166, 193, 201–202, 332, 355–358, 407–410, 415–416, 483–484, 514–516, 528–530 aliases of, 142–144 arrays, 407–410, 415–416 assignment statements, 93–95 data value as, 91–95 declarations, 92–93, 140–142, 193, 201–202, 407–410, 415–416, 515–516, 528 enumerated types, 164–166, 355–358 inheritance and, 483–484, 515–516
831
832
index
variables (continued) initializer lists, 415–416 instance data, 193 instantiation, 141, 193 int value declaration of, 91–93, 140, 407–408, 415–416 interfaces and, 528–530 interfaces for, 528–530 late binding, 514 local data, 201–202 method declaration of, 201–202, 407–410 new operator for, 141–142 null value setting, 141 objects and, 140–144, 164–166 ordinal value, 164–165 polymorphism and, 514–516, 528–530 reference, 140–142, 514–516, 528–530 scope of, 223 shadowing, 483–484 static (class), 326, 332 uninitialized, 140 visibility modifiers, 196–197, 473–475, 489–492, 709–710 default, 689, 709
encapsulation and, 196–197, 473–475 inheritance and, 473–475, 489–492 Java programming, 709–710 package, 682, 709 private, 196, 689, 709 protected, 473–475, 689, 709 public, 196, 689, 709 void modifier, 55, 57–58, 167, 200–201, 207–208 Java programming use of, 55, 57–58, 207–208 method header specification, 200–201 return statement and, 200–201, 207 wrapper class for, 167 volatile modifier (reserved word), 711 von Neumann architecture, 44
W
walkthrough, code evaluation by, 372 while clause for do statements, 301–302
while loop statements, 235,
256–265, 267–270 break statements for,
265 continue statements for, 265
divide-by-zero error, 258–259 infinite, 260–261 input validation, 260 iteration using, 267–270 nested, 262–295 repetition of, 256–257 running sums, 259 sentinel values, 257–259 white-box (glass-box) testing, 374 white space, 60–61, 115, 689 wide area network (WAN), 48–49 widening conversions, 109–110 World Wide Web (WWW), 51–52, 124 wrapper classes, 167–169 writing classes, 185–232
x
XOR bitwise operator (^), 704
Copyright © 2012-2024.