Java Software Solutions, 9th edition By John Lewis
Email: richard@qwconsultancy.com
Java Software Solutions, 9e (Lewis/Loftus) Chapter 1 Introduction TRUE/FALSE 1. All information is stored in the computer using binary numbers. ANS: T The computer is a digital device meaning that it stores information in one of two states using binary. We must determine then how to represent meaningful information (such as a name or a program instruction or an image) in binary. 2. Java is an object-oriented programming language. ANS: T Java is classified as a high-level programming language but it is also classified as an object-oriented programming language because it allows the programmer to implement data structures as classes. 3. System.out.print is used in a program to denote that a documentation comment follows. ANS: F Documentation comments follow // marks or are embedded between */ and */. System.out.print is an instruction used to output a message to the screen (the Java console window). 4. Java byte codes are directly executable whereas Java source code is not. ANS: F Neither Java source code nor Java byte codes are executable. Both must be compiled or interpreted into machine code. Java byte codes are useful however in that they are machine-independent but semi-compiled code that allows your Java code to be transmitted over the Internet and executed on another computer even if that other computer is a completely different type. 5. The Java compiler is able to find all programmer errors. ANS: F The Java compiler can find syntax errors but cannot find either logical errors (errors that are caused because of poor logic in writing the program) or run-time errors (errors that arise during the execution of the program). 6. Java is a case-sensitive language which means Current, CURRENT, and current will all reference the same identifier. ANS: F
Java is case sensitive which means that Current, CURRENT, and current will all be recognized as different identifiers. This causes problems with careless programmers who do not spell an identifier consistently in terms of upper and lower case characters. 7. Code placed inside of comments will not be compiled and, therefore, will not execute. ANS: T The compiler discards comments; therefore, any code inside a comment is discarded and is not compiled. Your executable program consists only of the code that is compiled. 8. The word Public is a reserved word. ANS: F public is a reserved word, but since Java is case sensitive, Public differs from public and therefore Public is not a reserved word.
9. Reserved words in Java can be redefined by the programmer to mean something other than their original intentions. ANS: F Java reserved words cannot be redefined. 10. In a Java program, dividing by zero is a syntax error. ANS: F Dividing by 0 is not detected at compile time, and because a computer cannot divide by 0, this is a runtime error. 11. In a Java program, dividing by zero is a syntax error. ANS: F Dividing by 0 is not detected at compile time, and because a computer cannot divide by 0, this is a runtime error. 12. During translation, the compiler puts its output (the compiled Java program) into ROM. ANS: F ROM stands for read-only-memory. The compiled output (the byte codes) may be placed into RAM (writable random access memory) or into a file (on your hard drive, for example). 13. Objects are defined by a class that describes the characteristics common to all instances of the class. ANS: T An object is an instance of a class. And, the purpose of a class is to describe these common characteristics.
14. Inheritance is a form of software reuse. ANS: T Inheritance allows us to capitalize on the similarities among various kinds of classes that have a common base (parent) class. Thus we reuse the base class each time a class inherits from it. 15. Polymorphism is the idea that we can refer to multiple types of related objects in consistent ways. ANS: T Polymorphism allows us to use the same name for similar behaviors that occur among diverse and possibly unrelated objects. For example, to "open" may refer to a file, or to a device, or to a communications line, etc. The same term, "open," is being used even though the objects that are being opened are quite different. 16. In Java, identifiers may be of any length up to a limit determined by the compiler. ANS: F Java (and Java compilers) do not limit the length of the identifiers you use. Identifiers may be as long as you wish. Good programming practice, however, will limit the lengths of the identifiers you create.
MULTIPLE CHOICE 1. A Java program is best classified as a. b. c. d. e.
hardware software storage processor input
ANS: B Programs are classified as software to differentiate them from the mechanisms of the computer (hardware). Storage and the processor are two forms of hardware while input is the information that the program processes. 2. Six bits can be used to represent __________ distinct items or values. a. b. c. d. e.
6 20 24 32 64
ANS: E With n bits, we can represent 2^n different values. 2^6 = 64. 3. When executing a program, the processor reads each program instruction from a. secondary memory (storage) b. the Internet
c. registers stored in the processor d. main memory e. Any of these ANS: D The program is first loaded from secondary memory into main memory before it is executed so that the processor is not slowed down by reading each instruction. This idea of executing programs stored in memory is called the Stored Program Computer and was pioneered by John Von Neumann in the 1940s. 4. Which memory capacity is the largest? a. b. c. d. e.
1,500,000,000,000 bytes 100 gigabytes 3,500,000 kilobytes 10 terabytes 12,000,000 megabytes
ANS: E We convert each of these capacities to bytes (rounding off) to compare them. The value in A remains the same, 1 1/2 trillion bytes. The value in B is 100 billion bytes. The value in C is 3 1/2 billion bytes. The value in D is 10 trillion bytes. The answer in E is 12 trillion bytes. 5. Binary numbers are composed entirely of a. b. c. d. e.
0s 1s 0s and 1s any digits between 0 and 9 0s, 1s, and 2s
ANS: C Binary is base 2. In Mathematics, numbers in base n are composed entirely of digits between 0 and n1. 6. Volatility is a property of a. b. c. d. e.
RAM ROM disk software computer networks
ANS: A
Volatility means that the contents of memory are lost if the electrical power is shut off. This is true of RAM (Random Access Memory), but not ROM (Read Only Memory) or disk. Software and computer networks are not forms of memory. 7. The ability to directly obtain a stored item by referencing its address is known as a. b. c. d.
random access sequential access read-only access fetch access
e. volatility ANS: A Random access is meant to convey the idea that accessing any item is equally easy, and that any item is retrievable based solely on its address. Random access is the form of access used by both RAM and ROM memory. Disk access, called direct access, is a similar idea, and direct and random access are sometimes referred to synonymously. Sequential access is used by tape. 8. Which phase of the fetch-decode-execute cycle might use a circuit in the arithmetic-logic unit? a. b. c. d. e.
fetch decode execute during fetch or execute, but not decode any of the phases
ANS: C The fetch phase retrieves (fetches) the next program instruction from memory. The decode phase determines which circuit(s) needs to be used to execute the instruction. The instruction is executed during the execute phase. If the instruction is either an arithmetic operation (like add or multiply) or a logical operation (like comparing two values), then it is carried out by the ALU. 9. In order for a computer to be accessible over a computer network, the computer needs its own a. b. c. d. e.
MODEM communication line network address packet router
ANS: C In order to differentiate between the computers on a network, each is given its own, unique, network address. In this way, a message intended for one computer can be recognized by that computer through the message's destination address. A MODEM is a device that is used to allow a computer to communicate to another computer over a telephone line. A communication line is the network media itself. A packet is a collection of data that is sent over a network. A router is a hardware device used to take a message from one network and move it to another based on the message's destination address. 10. For a computer to communicate over the Internet, it must use a. b. c. d. e.
the TCP protocol the IP protocol the combined TCP/IP protocol the Ethernet protocol the ARPANET protocol
ANS: C IP is the Internet Protocol, but the TCP (Transmission Control Protocol) also must be used because it handles such problems as how to piece together packets of the same message that arrive out of order. Ethernet is a LAN protocol, which might be used in addition to TCP/IP in some networks, but it is not needed to communicate over the Internet. There is no such thing as the ARPANET protocol. 11. A URL (Uniform Resource Locator) specifies the address of a a. computer on any network
b. c. d. e.
computer on the Internet local area network (LAN) on the Internet a document or other type of file on the Internet a Java program on the Internet
ANS: D URLs are used to locate documents (or other types of files such as an image or sound file) anywhere on the Internet. A URL contains the address of the LAN or WAN and the specific computer from which the file is to be retrieved; it specifies the file's address, not just the computer's address. 12. It is important to dissect a problem into manageable pieces before trying to solve the problem because a. most problems are too complex to be solved as a single, large activity b. most problems are solved by multiple people and it is easy to assign each piece to a separate person c. ir is easier to integrate small pieces of a program into one program than it is to integrate one big chunk of code into one program d. the first solution may not solve the problem correctly e. All of these ANS: A Any interesting problem will be too complex to solve easily as a single activity. By decomposing the problem, we can build small solutions for each piece and then integrate the pieces. Answer D is true, but it is not the reason why we will break a problem into pieces. 13. Once we have implemented a solution, we are not done with the problem because a. b. c. d.
the solution may not be the best (most efficient) the solution may have errors and need testing and fixing the solution may, at a later date, need revising to handle new specifications the solution may, at a later date, need revising because of new programming language features e. All of these ANS: E A program should not be considered as a finished product until we are reasonably assured that it is efficient and error-free. Further, it is common that programs require modification in the future because of a change to specifications or a change to the language or computer running the program. 14. Java is an example of a(n) a. b. c. d. e.
machine language Assembly language high-level language fourth generation language both high-level and fourth generation language
ANS: E While Java was created during the fourth generation, it is clearly also a high-level language. Machine language is the executable language of a machine, with programs written in 1s and 0s only. Assembly language uses mnemonics. Fourth generation languages are tools wrapped inside of programs so that the user has the flexibility to write some code to executed from within the program.
15. Of the following, which statement is not true regarding Java as a programming language? a. Java is a relatively recent language; it was introduced in 1995. b. Java is a language whose programs do not require translating into machine language before they are executed. c. Java is an object-oriented language. d. Java is a language that embraces the idea of writing programs to be executed with the World Wide Web. e. All of these are true ANS: B All languages require translation into machine language. The other statements are all true about Java. 16. Comments should a. b. c. d. e.
rephrase all the code to explain it in English be insightful and explain the intention of an instruction or block of code only be included with code that is difficult to understand be used to define variables that have hard to understand names All of these
ANS: B Comments should not rephrase in English what an instruction says, but instead should explain what that instruction is doing in relation to the program. Introductory programmers often have difficult explaining their code and wind up stating the obvious in their comments. While answer D is partially correct, it is not entirely true even though all variables should have comments that explain their use. 17. The main method for a Java program is defined by a. b. c. d. e.
public static main() public static main(String[] args); public static main(String[] args) private static main(String[] args) The main method could be defined by all of these except B
ANS: C In A, the parameter is missing. The parameters are defined later in the text, but in effect, they allow the user to run the program and include some initial arguments if the program calls for it. In B, the semicolon at the end of the statement is not allowed. In D, private instead of public would make the program non-executable by anyone and thus makes the definition meaningless. 18. What does the following line of Java code do? //System.out.println("Hello"); a. b. c. d. e.
nothing cause Hello to be output cause a syntax error cause ("Hello") to be output There is no way to tell without executing the code.
ANS: A The characters // denote the beginning of a comment. The comment is not compiled and so, nothing would happen when this code is executed.
19. What comment might be added to explain the following instruction? System.out.println("Hello World"); a. b. c. d. e.
// prints "Hello World" to the screen //prints a message //used to demonstrate an output message // // meaningless instruction
ANS: C Comments in A and B state the obvious while the comments in D and E are meaningless. The comment in C explains why the instruction appears in the program. 20. Which character belowis not allowed in an identifier? a. b. c. d. e.
$ _ 0 1 ^
ANS: E Java identifiers can consist of any letter, digit, $ or _ as long as the identifier starts with a letter or _. ^ is not a legal character. 21. Which of the following is not syntactically legal in Java? a. b. c. d. e.
System.out.println("Hi"); public class Foo s t a t i c main(String[] args) {} only A is legally valid; all the others are illegal
ANS: C The Java compiler would not recognize "s t a t i c" as "static" because the Java compiler treats white space (blanks) as separators between entities. The other statements are all legal, including "{}" which is a block that happens to have no statements within it. 22. Which of the following is a legal Java identifier? a. b. c. d. e.
i class 1likeclass! idon'tlikeclass i-like-class
ANS: A Java identifiers cannot have the characters !, ' or - in them so answers C, D and E are wrong. The word class is a reserved word in Java and cannot be used as an identifier. The identifier i is perfectly legal although it is not necessarily a good identifier since it is not descriptive of its use. 23. A unique aspect of Java that allows code compiled on one machine to be executed on a machine with a different hardware platform is Java's
a. b. c. d. e.
bytecodes syntax use of objects use of exception handling All of these
ANS: A The translation process for a Java program is to first compile it into bytecodes, which are architecturally neutral (that is, they can be used no matter what the architectural platform is). To execute the program, the bytecodes must be further compiled by a Java compiler or interpreted by a Java Virtual Machine. 24. Java is similar in syntax to which of the following high-level languages? a. b. c. d. e.
Pascal Ada C++ FORTRAN BASIC
ANS: C The creators of Java decided to use syntax similar to C++ so that C++ programmers could easily learn Java. Variable declarations, assignment statements, loops, selection statements and comments are among the features that have nearly identical syntax. There are many differences however, so don't assume that any C or C++ programmer will easily or instantly be able to program in Java. 25. An error in a program that results in the program outputtinh $100 instead of the correct answer, $250, is a a. b. c. d. e.
compiler error syntax error run-time error logical error snafu
ANS: D While this is an error, programmers classify the type of error in order to more easily solve the problem. Syntax errors are caught by the compiler and the program cannot run without fixing all syntax errors. Run-time errors arise during program execution and cause the program to stop running. Logical errors are errors whereby the program can run to completion, but gives the wrong answer. If the result should have been $250, then the logic of the program is wrong since it output $100. A snafu is a term expressing a messed up situation in combat and should not be used by respectable programmers! 26. Which of the following is true regarding Java syntax and semantics? a. A Java compiler can determine if you have followed proper syntax but not proper semantics. b. A Java compiler can determine if you have followed proper semantics but not proper syntax. c. A Java compiler can determine if you have followed both proper syntax and proper semantics. d. A Java compiler cannot determine if you have followed either proper syntax or proper semantics.
e. A Java compiler can determine if you have followed proper syntax but not proper semantics only if you follow the Java naming convention rules. ANS: A Compilers for all languages have the ability to detect syntax errors because improper use of the syntax leads to situations where the compilers cannot translate the code properly. However, compilers are unable to follow the semantics of a program because this requires a degree of understanding what the program is intended to do and computers have no sense of understanding (at least at this point). 27. Using Java naming convention, which of the following would be a good variable name for the current value of a stock? a. b. c. d. e.
curstoval theCurrentValueOfThisStock currentStockVal csv current
ANS: C Java allows long variable names but the programmer must find a good compromise between an excessive long name (as with B) and names too short to understand their use (A and D). The name current possibly might be reasonable if there are no other "current" values being referenced in the program. 28. Which of the following is a legal Java identifier? a. b. c. d. e.
1ForAll oneForAll one/4/all 1_4_all 1forall
ANS: B Java identifiers cannot start with a number (so the answers in A, D and E are illegal) and cannot include the / character, so the answer in C is illegal. 29. A color image is broken down into individual pixels (points), each of which is represented by a. b. c. d.
a 1 for white and a 0 for black 3 values denoting the intensity of red, green, and blue in the image a single number indicating the intensity of color between white and black two numbers, where one indicates where the color is between white and black and the other denotes the brightness e. None of these; it is not possible to represent color ANS: B Black and white images are stored using 0s and 1s while color images are stored using three values, one each for the degree of red, the degree of blue, and the degree of green. 30. Which of the following characters does not need to have an associated closing character in a Java program? a. { b. (
c. [ d. < e. All of these require closing characters ANS: D { is used to open a block, and so } is needed to close the block. ( is used to open an expression and so ) is needed to close an expression. [ is used to start an array index so ] is needed to close the array index. < is "less than" and > is "greater than" and these are not needed together, so < requires no closing character. 31. Mistyping println as printn will result in a. b. c. d. e.
a syntax error a run-time error a logical error no error the statement being converted to a comment
ANS: A If the Java compiler cannot make sense of a command, the compiler cannot convert it and responds with a syntax error. While println is recognized as a command, printn is not, and so the compiler provides a syntax error.
PROBLEM 1. What is wrong with the following class definition? public class Program1 { public static void main(String[ ] args) { System.out.println("My first Java program") } } ANS: The one executable statement in the main method is missing a ";" at the end of the line. Executable statements end with ";". 2. What is wrong with the following class definition? public class Program2 public static void main(String[] args) { System.out.println("My second Java program"); } ANS: The definition of a class is placed within {} statements, which are missing here. 3. Given the following class definition, what are the reserved words and what are the identifiers? public class Program3
{ public static void main(String[] args) { System.out.println("My third Java program"); } } ANS: The reserved words are public, class, static, void. The identifiers are main, String, System.out, Program3, and args. main is the name of a method defined within the Program3 class. string and System.out are classes already defined in Java and println is a method of System.out. Program3 is a class, defined here, and args is a variable. 4. Provide a brief explanation of the role of main memory, the control unit, the arithmetic logic unit, and registers. (Refer to figure 1.13 in the text) ANS: Main memory is used to store the currently executing processes along with their data. The control unit performs the fetch-decode-execute cycle, which fetches an instruction from memory, decodes it and determines how it is to be executed. The arithmetic logic unit comprises a number of circuits that execute arithmetic and logic instructions. Registers are used to store values in the CPU temporarily while the current instruction(s) need them. 5. What is the output of the following code when the main method is executed? public class Question4 { public static void main(String[] args) { System.out.println("hi there"); System.out.println(" "); System.out.println("how are you doing } }
today?
");
ANS: hi there how are
you doing
today?
Notice that while the Java compiler ignores "white space", blanks that appear in a println statement inside of quote marks are retained and output in that manner. 6. What is wrong with the following println statement? System.out.println("My fourth Java Program); ANS: It is missing a closing ". The compiler will look for a second " before the end of the statement. So, like {}, (), and [], an initial " must have a corresponding closing ". 7. Provide identifier names that would be used to represent a person's social security number, income tax withheld, and net pay.
ANS: socialSecurityNumber, or ssn, incomeTaxWithheld or incomeTax, and netPay all would be reasonable. 8. There are a number of reserved words in Java that have no current meaning (denoted with an * in figure 1.18 in the text). Why? ANS: Java language designers anticipate introducing these statements in future versions, but have not yet implemented them because they are lower priority, or it has not been decided how they will be implemented or precisely what they will mean. 9. A document of text is 15 pages long. Each page contains approximately 200 words and the average length of each word is 5 characters. Also assume one blank space between each word and no punctuation. How many bytes will it take to store this document in memory or on disk using ASCII? ANS: A character is stored in ASCII using 8 bits or 1 byte. Therefore, 5 characters per word plus 1 blank space between words take 6 bytes per word (except for the first). Each page stores 200 words and there are 15 pages. So we need 15 * 200 * 6 - 1 (no blank space to start the text) = 17,999 bytes which is 17.58 kilobytes, or nearly 18 Kbytes. 10. Provide a brief description of the roles of the following hardware elements (that is, what each is used for): a) CPU b) Main memory c) Secondary memory devices d) Input/Output devices ANS: a) The CPU is the processor. It executes all program instructions. It does this through the fetchdecode-execute cycle where the next program instruction is fetched from memory, decoded in the CPU, and then executed by one or more circuits. b) Main memory is stored on chips on the motherboard and is used for quick access to the current program for the fetch-decode-execute cycle and to store data being used by this program. c) Secondary memory devices are storage devices, used to store programs and data not currently being used. Storage devices, such as the hard disk, also are used to store things for permanence and archives. d) Input/Output devices are used to communicate with the computer. Input devices, like the keyboard, take commands and data from the user and output devices, like the monitor, display the results of the process/computation. 11. Examine figure 1.7 before answering this question. What 8-bit value comes immediately before and what 8-bit value comes immediately after 10010111? ANS: 10010110 comes immediately before 10010111 and 10010100 comes immediately after 10010111.
12. Rewrite the following comment so that is can appear over multiple lines. // This is one really enormously long comment that might run off the page ANS: We can do this in two ways, preceding each line with // or by enclosing the comment in /* and */. /* This is one really enormously long comment that might run off the page */ or // This is one really enormously // long comment that might run // off the page 13. Rewrite the following program with better formatting to make it easier to read. public class MyProgram { public static void main( String[] args) { System.out.println( "Wow, this is messed up!" ); } } ANS: There are many ways this program might appear. The following would be very acceptable: public class MyProgram { public static void main(String[] args) { System.out.println("Wow, this is messed up!"); } } 14. Write a Java program that will output on two separate lines the names of the authors of this textbook. ANS: public class OutputNames { public static void main(String[] args) { System.out.println("John Lewis"); // 1st author's name System.out.println("William Loftus");// 2nd author's name } }
15. Correct all the syntax errors in the following program. Public Class Program \\ A problem program ( Public static voided main[Strings() args] { system.out.println('This program'); \* oh, my... *\ system.out.println('has several syntax errors'); \* lots of errors *\ } ) ANS: public class Program // A problem program { public static void main(String[] args) { System.out.println("This program"); /* oh, my... */ System.out.println("has several syntax errors"); /* lots of errors */ } } 16. Write a Java program that will display the following three lines when it is run: * * * * * * * * * ANS: public class Stars { public static void main(String[] args) { System.out.println(" *"); System.out.println(" * * *"); System.out.println("* * * * *"); } }
17. Name five of the fundamental terms which encompass object-oriented programming. ANS:
There are seven terms to choose from: object, attribute, method, class, encapsulation, inheritance, and polymorphism.
Java Software Solutions, 9e (Lewis/Loftus) Chapter 1 Introduction TRUE/FALSE 1. All information is stored in the computer using binary numbers. ANS: T The computer is a digital device meaning that it stores information in one of two states using binary. We must determine then how to represent meaningful information (such as a name or a program instruction or an image) in binary. 2. Java is an object-oriented programming language. ANS: T Java is classified as a high-level programming language but it is also classified as an object-oriented programming language because it allows the programmer to implement data structures as classes. 3. System.out.print is used in a program to denote that a documentation comment follows. ANS: F Documentation comments follow // marks or are embedded between */ and */. System.out.print is an instruction used to output a message to the screen (the Java console window). 4. Java byte codes are directly executable whereas Java source code is not. ANS: F Neither Java source code nor Java byte codes are executable. Both must be compiled or interpreted into machine code. Java byte codes are useful however in that they are machine-independent but semi-compiled code that allows your Java code to be transmitted over the Internet and executed on another computer even if that other computer is a completely different type. 5. The Java compiler is able to find all programmer errors. ANS: F The Java compiler can find syntax errors but cannot find either logical errors (errors that are caused because of poor logic in writing the program) or run-time errors (errors that arise during the execution of the program). 6. Java is a case-sensitive language which means Current, CURRENT, and current will all reference the same identifier. ANS: F
Java is case sensitive which means that Current, CURRENT, and current will all be recognized as different identifiers. This causes problems with careless programmers who do not spell an identifier consistently in terms of upper and lower case characters. 7. Code placed inside of comments will not be compiled and, therefore, will not execute. ANS: T The compiler discards comments; therefore, any code inside a comment is discarded and is not compiled. Your executable program consists only of the code that is compiled. 8. The word Public is a reserved word. ANS: F public is a reserved word, but since Java is case sensitive, Public differs from public and therefore Public is not a reserved word.
9. Reserved words in Java can be redefined by the programmer to mean something other than their original intentions. ANS: F Java reserved words cannot be redefined. 10. In a Java program, dividing by zero is a syntax error. ANS: F Dividing by 0 is not detected at compile time, and because a computer cannot divide by 0, this is a run-time error. 11. In a Java program, dividing by zero is a syntax error. ANS: F Dividing by 0 is not detected at compile time, and because a computer cannot divide by 0, this is a run-time error. 12. During translation, the compiler puts its output (the compiled Java program) into ROM. ANS: F ROM stands for read-only-memory. The compiled output (the byte codes) may be placed into RAM (writable random access memory) or into a file (on your hard drive, for example). 13. Objects are defined by a class that describes the characteristics common to all instances of the class. ANS: T An object is an instance of a class. And, the purpose of a class is to describe these common characteristics.
14. Inheritance is a form of software reuse. ANS: T Inheritance allows us to capitalize on the similarities among various kinds of classes that have a common base (parent) class. Thus we reuse the base class each time a class inherits from it. 15. Polymorphism is the idea that we can refer to multiple types of related objects in consistent ways. ANS: T Polymorphism allows us to use the same name for similar behaviors that occur among diverse and possibly unrelated objects. For example, to "open" may refer to a file, or to a device, or to a communications line, etc. The same term, "open," is being used even though the objects that are being opened are quite different. 16. In Java, identifiers may be of any length up to a limit determined by the compiler. ANS: F Java (and Java compilers) do not limit the length of the identifiers you use. Identifiers may be as long as you wish. Good programming practice, however, will limit the lengths of the identifiers you create.
MULTIPLE CHOICE 1. A Java program is best classified as a. b. c. d. e.
hardware software storage processor input
ANS: B Programs are classified as software to differentiate them from the mechanisms of the computer (hardware). Storage and the processor are two forms of hardware while input is the information that the program processes. 2. Six bits can be used to represent __________ distinct items or values. a. b. c. d. e.
6 20 24 32 64
ANS: E With n bits, we can represent 2^n different values. 2^6 = 64. 3. When executing a program, the processor reads each program instruction from a. secondary memory (storage) b. the Internet
c. registers stored in the processor d. main memory e. Any of these ANS: D The program is first loaded from secondary memory into main memory before it is executed so that the processor is not slowed down by reading each instruction. This idea of executing programs stored in memory is called the Stored Program Computer and was pioneered by John Von Neumann in the 1940s. 4. Which memory capacity is the largest? a. b. c. d. e.
1,500,000,000,000 bytes 100 gigabytes 3,500,000 kilobytes 10 terabytes 12,000,000 megabytes
ANS: E We convert each of these capacities to bytes (rounding off) to compare them. The value in A remains the same, 1 1/2 trillion bytes. The value in B is 100 billion bytes. The value in C is 3 1/2 billion bytes. The value in D is 10 trillion bytes. The answer in E is 12 trillion bytes. 5. Binary numbers are composed entirely of a. b. c. d. e.
0s 1s 0s and 1s any digits between 0 and 9 0s, 1s, and 2s
ANS: C Binary is base 2. In Mathematics, numbers in base n are composed entirely of digits between 0 and n-1. 6. Volatility is a property of a. b. c. d. e.
RAM ROM disk software computer networks
ANS: A
Volatility means that the contents of memory are lost if the electrical power is shut off. This is true of RAM (Random Access Memory), but not ROM (Read Only Memory) or disk. Software and computer networks are not forms of memory. 7. The ability to directly obtain a stored item by referencing its address is known as a. b. c. d.
random access sequential access read-only access fetch access
e. volatility ANS: A Random access is meant to convey the idea that accessing any item is equally easy, and that any item is retrievable based solely on its address. Random access is the form of access used by both RAM and ROM memory. Disk access, called direct access, is a similar idea, and direct and random access are sometimes referred to synonymously. Sequential access is used by tape. 8. Which phase of the fetch-decode-execute cycle might use a circuit in the arithmetic-logic unit? a. b. c. d. e.
fetch decode execute during fetch or execute, but not decode any of the phases
ANS: C The fetch phase retrieves (fetches) the next program instruction from memory. The decode phase determines which circuit(s) needs to be used to execute the instruction. The instruction is executed during the execute phase. If the instruction is either an arithmetic operation (like add or multiply) or a logical operation (like comparing two values), then it is carried out by the ALU. 9. In order for a computer to be accessible over a computer network, the computer needs its own a. b. c. d. e.
MODEM communication line network address packet router
ANS: C In order to differentiate between the computers on a network, each is given its own, unique, network address. In this way, a message intended for one computer can be recognized by that computer through the message's destination address. A MODEM is a device that is used to allow a computer to communicate to another computer over a telephone line. A communication line is the network media itself. A packet is a collection of data that is sent over a network. A router is a hardware device used to take a message from one network and move it to another based on the message's destination address. 10. For a computer to communicate over the Internet, it must use a. b. c. d. e.
the TCP protocol the IP protocol the combined TCP/IP protocol the Ethernet protocol the ARPANET protocol
ANS: C IP is the Internet Protocol, but the TCP (Transmission Control Protocol) also must be used because it handles such problems as how to piece together packets of the same message that arrive out of order. Ethernet is a LAN protocol, which might be used in addition to TCP/IP in some networks, but it is not needed to communicate over the Internet. There is no such thing as the ARPANET protocol. 11. A URL (Uniform Resource Locator) specifies the address of a a. computer on any network
b. c. d. e.
computer on the Internet local area network (LAN) on the Internet a document or other type of file on the Internet a Java program on the Internet
ANS: D URLs are used to locate documents (or other types of files such as an image or sound file) anywhere on the Internet. A URL contains the address of the LAN or WAN and the specific computer from which the file is to be retrieved; it specifies the file's address, not just the computer's address. 12. It is important to dissect a problem into manageable pieces before trying to solve the problem because a. most problems are too complex to be solved as a single, large activity b. most problems are solved by multiple people and it is easy to assign each piece to a separate person c. ir is easier to integrate small pieces of a program into one program than it is to integrate one big chunk of code into one program d. the first solution may not solve the problem correctly e. All of these ANS: A Any interesting problem will be too complex to solve easily as a single activity. By decomposing the problem, we can build small solutions for each piece and then integrate the pieces. Answer D is true, but it is not the reason why we will break a problem into pieces. 13. Once we have implemented a solution, we are not done with the problem because a. b. c. d.
the solution may not be the best (most efficient) the solution may have errors and need testing and fixing the solution may, at a later date, need revising to handle new specifications the solution may, at a later date, need revising because of new programming language features e. All of these ANS: E A program should not be considered as a finished product until we are reasonably assured that it is efficient and error-free. Further, it is common that programs require modification in the future because of a change to specifications or a change to the language or computer running the program. 14. Java is an example of a(n) a. b. c. d. e.
machine language Assembly language high-level language fourth generation language both high-level and fourth generation language
ANS: E While Java was created during the fourth generation, it is clearly also a high-level language. Machine language is the executable language of a machine, with programs written in 1s and 0s only. Assembly language uses mnemonics. Fourth generation languages are tools wrapped inside of programs so that the user has the flexibility to write some code to executed from within the program.
15. Of the following, which statement is not true regarding Java as a programming language? a. Java is a relatively recent language; it was introduced in 1995. b. Java is a language whose programs do not require translating into machine language before they are executed. c. Java is an object-oriented language. d. Java is a language that embraces the idea of writing programs to be executed with the World Wide Web. e. All of these are true ANS: B All languages require translation into machine language. The other statements are all true about Java. 16. Comments should a. b. c. d. e.
rephrase all the code to explain it in English be insightful and explain the intention of an instruction or block of code only be included with code that is difficult to understand be used to define variables that have hard to understand names All of these
ANS: B Comments should not rephrase in English what an instruction says, but instead should explain what that instruction is doing in relation to the program. Introductory programmers often have difficult explaining their code and wind up stating the obvious in their comments. While answer D is partially correct, it is not entirely true even though all variables should have comments that explain their use. 17. The main method for a Java program is defined by a. b. c. d. e.
public static main() public static main(String[] args); public static main(String[] args) private static main(String[] args) The main method could be defined by all of these except B
ANS: C In A, the parameter is missing. The parameters are defined later in the text, but in effect, they allow the user to run the program and include some initial arguments if the program calls for it. In B, the semicolon at the end of the statement is not allowed. In D, private instead of public would make the program non-executable by anyone and thus makes the definition meaningless. 18. What does the following line of Java code do? //System.out.println("Hello"); a. b. c. d. e.
nothing cause Hello to be output cause a syntax error cause ("Hello") to be output There is no way to tell without executing the code.
ANS: A The characters // denote the beginning of a comment. The comment is not compiled and so, nothing would happen when this code is executed.
19. What comment might be added to explain the following instruction? System.out.println("Hello World"); a. b. c. d. e.
// prints "Hello World" to the screen //prints a message //used to demonstrate an output message // // meaningless instruction
ANS: C Comments in A and B state the obvious while the comments in D and E are meaningless. The comment in C explains why the instruction appears in the program. 20. Which character belowis not allowed in an identifier? a. b. c. d. e.
$ _ 0 1 ^
ANS: E Java identifiers can consist of any letter, digit, $ or _ as long as the identifier starts with a letter or _. ^ is not a legal character. 21. Which of the following is not syntactically legal in Java? a. b. c. d. e.
System.out.println("Hi"); public class Foo s t a t i c main(String[] args) {} only A is legally valid; all the others are illegal
ANS: C The Java compiler would not recognize "s t a t i c" as "static" because the Java compiler treats white space (blanks) as separators between entities. The other statements are all legal, including "{}" which is a block that happens to have no statements within it. 22. Which of the following is a legal Java identifier? a. b. c. d. e.
i class 1likeclass! idon'tlikeclass i-like-class
ANS: A Java identifiers cannot have the characters !, ' or - in them so answers C, D and E are wrong. The word class is a reserved word in Java and cannot be used as an identifier. The identifier i is perfectly legal although it is not necessarily a good identifier since it is not descriptive of its use. 23. A unique aspect of Java that allows code compiled on one machine to be executed on a machine with a different hardware platform is Java's
a. b. c. d. e.
bytecodes syntax use of objects use of exception handling All of these
ANS: A The translation process for a Java program is to first compile it into bytecodes, which are architecturally neutral (that is, they can be used no matter what the architectural platform is). To execute the program, the bytecodes must be further compiled by a Java compiler or interpreted by a Java Virtual Machine. 24. Java is similar in syntax to which of the following high-level languages? a. b. c. d. e.
Pascal Ada C++ FORTRAN BASIC
ANS: C The creators of Java decided to use syntax similar to C++ so that C++ programmers could easily learn Java. Variable declarations, assignment statements, loops, selection statements and comments are among the features that have nearly identical syntax. There are many differences however, so don't assume that any C or C++ programmer will easily or instantly be able to program in Java. 25. An error in a program that results in the program outputtinh $100 instead of the correct answer, $250, is a a. b. c. d. e.
compiler error syntax error run-time error logical error snafu
ANS: D While this is an error, programmers classify the type of error in order to more easily solve the problem. Syntax errors are caught by the compiler and the program cannot run without fixing all syntax errors. Run-time errors arise during program execution and cause the program to stop running. Logical errors are errors whereby the program can run to completion, but gives the wrong answer. If the result should have been $250, then the logic of the program is wrong since it output $100. A snafu is a term expressing a messed up situation in combat and should not be used by respectable programmers! 26. Which of the following is true regarding Java syntax and semantics? a. A Java compiler can determine if you have followed proper syntax but not proper semantics. b. A Java compiler can determine if you have followed proper semantics but not proper syntax. c. A Java compiler can determine if you have followed both proper syntax and proper semantics. d. A Java compiler cannot determine if you have followed either proper syntax or proper semantics.
e. A Java compiler can determine if you have followed proper syntax but not proper semantics only if you follow the Java naming convention rules. ANS: A Compilers for all languages have the ability to detect syntax errors because improper use of the syntax leads to situations where the compilers cannot translate the code properly. However, compilers are unable to follow the semantics of a program because this requires a degree of understanding what the program is intended to do and computers have no sense of understanding (at least at this point). 27. Using Java naming convention, which of the following would be a good variable name for the current value of a stock? a. b. c. d. e.
curstoval theCurrentValueOfThisStock currentStockVal csv current
ANS: C Java allows long variable names but the programmer must find a good compromise between an excessive long name (as with B) and names too short to understand their use (A and D). The name current possibly might be reasonable if there are no other "current" values being referenced in the program. 28. Which of the following is a legal Java identifier? a. b. c. d. e.
1ForAll oneForAll one/4/all 1_4_all 1forall
ANS: B Java identifiers cannot start with a number (so the answers in A, D and E are illegal) and cannot include the / character, so the answer in C is illegal. 29. A color image is broken down into individual pixels (points), each of which is represented by a. b. c. d.
a 1 for white and a 0 for black 3 values denoting the intensity of red, green, and blue in the image a single number indicating the intensity of color between white and black two numbers, where one indicates where the color is between white and black and the other denotes the brightness e. None of these; it is not possible to represent color ANS: B Black and white images are stored using 0s and 1s while color images are stored using three values, one each for the degree of red, the degree of blue, and the degree of green. 30. Which of the following characters does not need to have an associated closing character in a Java program? a. { b. (
c. [ d. < e. All of these require closing characters ANS: D { is used to open a block, and so } is needed to close the block. ( is used to open an expression and so ) is needed to close an expression. [ is used to start an array index so ] is needed to close the array index. < is "less than" and > is "greater than" and these are not needed together, so < requires no closing character. 31. Mistyping println as printn will result in a. b. c. d. e.
a syntax error a run-time error a logical error no error the statement being converted to a comment
ANS: A If the Java compiler cannot make sense of a command, the compiler cannot convert it and responds with a syntax error. While println is recognized as a command, printn is not, and so the compiler provides a syntax error.
PROBLEM 1. What is wrong with the following class definition? public class Program1 { public static void main(String[ ] args) { System.out.println("My first Java program") } } ANS: The one executable statement in the main method is missing a ";" at the end of the line. Executable statements end with ";". 2. What is wrong with the following class definition? public class Program2 public static void main(String[] args) { System.out.println("My second Java program"); } ANS: The definition of a class is placed within {} statements, which are missing here. 3. Given the following class definition, what are the reserved words and what are the identifiers? public class Program3
{ public static void main(String[] args) { System.out.println("My third Java program"); } } ANS: The reserved words are public, class, static, void. The identifiers are main, String, System.out, Program3, and args. main is the name of a method defined within the Program3 class. string and System.out are classes already defined in Java and println is a method of System.out. Program3 is a class, defined here, and args is a variable. 4. Provide a brief explanation of the role of main memory, the control unit, the arithmetic logic unit, and registers. (Refer to figure 1.13 in the text) ANS: Main memory is used to store the currently executing processes along with their data. The control unit performs the fetch-decode-execute cycle, which fetches an instruction from memory, decodes it and determines how it is to be executed. The arithmetic logic unit comprises a number of circuits that execute arithmetic and logic instructions. Registers are used to store values in the CPU temporarily while the current instruction(s) need them. 5. What is the output of the following code when the main method is executed? public class Question4 { public static void main(String[] args) { System.out.println("hi there"); System.out.println(" "); System.out.println("how are you doing } }
today?
");
ANS: hi there how are
you doing
today?
Notice that while the Java compiler ignores "white space", blanks that appear in a println statement inside of quote marks are retained and output in that manner. 6. What is wrong with the following println statement? System.out.println("My fourth Java Program); ANS: It is missing a closing ". The compiler will look for a second " before the end of the statement. So, like {}, (), and [], an initial " must have a corresponding closing ". 7. Provide identifier names that would be used to represent a person's social security number, income tax withheld, and net pay.
ANS: socialSecurityNumber, or ssn, incomeTaxWithheld or incomeTax, and netPay all would be reasonable. 8. There are a number of reserved words in Java that have no current meaning (denoted with an * in figure 1.18 in the text). Why? ANS: Java language designers anticipate introducing these statements in future versions, but have not yet implemented them because they are lower priority, or it has not been decided how they will be implemented or precisely what they will mean. 9. A document of text is 15 pages long. Each page contains approximately 200 words and the average length of each word is 5 characters. Also assume one blank space between each word and no punctuation. How many bytes will it take to store this document in memory or on disk using ASCII? ANS: A character is stored in ASCII using 8 bits or 1 byte. Therefore, 5 characters per word plus 1 blank space between words take 6 bytes per word (except for the first). Each page stores 200 words and there are 15 pages. So we need 15 * 200 * 6 - 1 (no blank space to start the text) = 17,999 bytes which is 17.58 kilobytes, or nearly 18 Kbytes. 10. Provide a brief description of the roles of the following hardware elements (that is, what each is used for): a) CPU b) Main memory c) Secondary memory devices d) Input/Output devices ANS: a) The CPU is the processor. It executes all program instructions. It does this through the fetch-decode-execute cycle where the next program instruction is fetched from memory, decoded in the CPU, and then executed by one or more circuits. b) Main memory is stored on chips on the motherboard and is used for quick access to the current program for the fetch-decode-execute cycle and to store data being used by this program. c) Secondary memory devices are storage devices, used to store programs and data not currently being used. Storage devices, such as the hard disk, also are used to store things for permanence and archives. d) Input/Output devices are used to communicate with the computer. Input devices, like the keyboard, take commands and data from the user and output devices, like the monitor, display the results of the process/computation. 11. Examine figure 1.7 before answering this question. What 8-bit value comes immediately before and what 8-bit value comes immediately after 10010111? ANS: 10010110 comes immediately before 10010111 and 10010100 comes immediately after 10010111.
12. Rewrite the following comment so that is can appear over multiple lines. // This is one really enormously long comment that might run off the page ANS: We can do this in two ways, preceding each line with // or by enclosing the comment in /* and */. /* This is one really enormously long comment that might run off the page */ or // This is one really enormously // long comment that might run // off the page 13. Rewrite the following program with better formatting to make it easier to read. public class MyProgram { public static void main( String[] args) { System.out.println( "Wow, this is messed up!" ); } } ANS: There are many ways this program might appear. The following would be very acceptable: public class MyProgram { public static void main(String[] args) { System.out.println("Wow, this is messed up!"); } } 14. Write a Java program that will output on two separate lines the names of the authors of this textbook. ANS: public class OutputNames { public static void main(String[] args) { System.out.println("John Lewis"); // 1st author's name System.out.println("William Loftus");// 2nd author's name } }
15. Correct all the syntax errors in the following program. Public Class Program \\ A problem program ( Public static voided main[Strings() args] { system.out.println('This program'); \* oh, my... *\ system.out.println('has several syntax errors'); \* lots of errors *\ } ) ANS: public class Program // A problem program { public static void main(String[] args) { System.out.println("This program"); /* oh, my... */ System.out.println("has several syntax errors"); /* lots of errors */ } } 16. Write a Java program that will display the following three lines when it is run: * * * * * * * * * ANS: public class Stars { public static void main(String[] args) { System.out.println(" *"); System.out.println(" * * *"); System.out.println("* * * * *"); } }
17. Name five of the fundamental terms which encompass object-oriented programming. ANS:
There are seven terms to choose from: object, attribute, method, class, encapsulation, inheritance, and polymorphism.
Java Software Solutions, 9e (Lewis/Loftus) Chapter 2 Data and Expressions TRUE/FALSE 1. If x is a String, then x = new String("OH"); and x = "OH"; will accomplish the same thing. ANS: T In Java, to instantiate (assign a value to) an object, you must use new and the class's constructor. However, since Strings are so common in Java, they can be instantiated in a way similar to assigning primitive types their values. So, both of the above assignment statements will accomplish the same task. 2. If x is the String "Hi There", then x.toUpperCase().toLowerCase(); will return the original value of x. ANS: F x.toUpperCase() returns x as all capital letters, while x.toLowerCase()will return x as all lower case letters. So, this code will first convert x to all upper case letters and then convert the new version to all lower case characters. 3. If String name = "George W. Bush"; then the instruction name.length(); will return 14. ANS: T There are 14 characters between the quote marks including two blanks and a period. 4. If String a = "ABCD" and String b = "abcd" then a.equals(b); returns false but a.equalsIgnoreCase(b); returns true. ANS: T Since "ABCD" is not the same as "abcd", the equals method returns false, but by ignoring case in equalsIgnoreCase, the two are considered to be the same. 5. Unlike the String class where you must pass a message to an object (instance) of the class, as in x.length(), in order to use either the Scanner or Math classes, you pass messages directly to the class name, as in Math.abs()or scan.nextInt(). ANS: T The Math and Scanner classes use methods known as static methods (or class methods) which are invoked by passing a message directly to the class name itself rather than to an object of the class. 6. In order to generate a random number, you must use Math.random().
ANS: F There is also a Random class available in java.util. This class can generate random int, float, and double values. This is a better mechanism for generating random numbers because you can instantiate several different random number generators. 7. A double is wider than a float and a float is wider than an int. ANS: T Wider types are larger in size or can store a greater range of values. The double is 64 bits whereas the float is 32 bits and the float, because of the way it is stored, can store a significantly larger range of values than the int. 8. A variable of type boolean will store either a 0 or a 1. ANS: F A boolean variable can store only one of two values, but these values are the reserved words true and false. In C, C++, and C# booleans are implemented as int variables that store only a 0 or a 1, but in Java, the authors of the language opted to use the boolean literals true and false as this is considered to be semantically more understandable (and is much safer). 9. In Java, 'a' and 'A' are considered to be different values. ANS: T Characters values are stored using ASCII, and 'a' and 'A' have different ASCII values as well as different Unicode values. 10. You cannot cast a String to be a char and you cannot cast a String which stores a number to be an int, float, or double. ANS: T There is no mechanism available to cast a String to one of the primitive types, but there are methods available to perform a similar action and return a character at a given location (CharAt) or to return the int, float, or double value equivalent to the number stored in the String. 11. The values of (double)5/2 and (double)(5/2) are identical. ANS: F In the first expression, the (double) cast applies to theint 5, changing it to the double value, 5.0. Then 5.0/2 is calculated, yielding the double value, 2.5. In the second expression the int division is performed first, yielding the value 2. 2 is then changed to a double, yielding the double value, 2.0. 12. There are three ways that data conversion may occur: by assignment, by promotion, and by casting.
ANS: T Assignment conversion occurs when a value on the right side of the assignment operator is converted prior to being stored in the variable on the left. Promotion occurs within an expression when values of differing widths are combined. Casting is a programmer's explicit way to control the data conversion process. 13. As explained in the Software Failure section in the text, the Mars Lander most likely crash landed when its descent engines cut off too high over the Mars surface. ANS: T The software on board the lander mistook the vibrations caused by the deployment of the lander's legs for the vibration caused by actually landing on the planet's surface.
MULTIPLE CHOICE Example Code Ch 02-1 public class Questions1_4 { public static void main(String[] args) { System.out.print("Here"); System.out.println("There " + "Everywhere"); System.out.println("But not" + "in Texas"); } } 1. Refer to the class definition in Example Code Ch 02-1. The program will print the word "Here" and then print a. b. c. d. e.
"There Everywhere" on the line after "Here" "The" on the line after "Here" and "Everywhere" on the line after "There" "There Everywhere" on the same line as "Here" "ThereEverywhere" on the same line as "Here" "ThereEverywhere" on the line after "Here"
ANS: C System.out.print will output the word Here but will leave the cursor at that point rather than starting a new line. The next statement will output There Everywhere immediately after the word Here. Since there is a blank space within the quote marks for There, there is a blank space inserted between There and Everywhere. 2. Refer to the class definition in Example Code Ch 02-1. The final println command will output a. b. c. d. e.
"But not in Texas" "But notin Texas" "But not" on one line and "in Texas" on the next line "But not+in Texas" "But not + in Texas"
ANS: B
The + performs String concatenation, so that But not and in Texas are concatenated together. Notice that there is no blank space after not or before in so that when they are concatenated, they are placed together without a blank space. 3. Refer to the class definition in Example Code Ch 02-1. How many lines of output are provided by this program? a. b. c. d. e.
1 2 3 4 5
ANS: B There will be one line of output for the first two statements combined because the print statement does not return the cursor to start a new line. And since the second statement is a println, it returns the cursor and the last println outputs its message on a separate line. 4. Refer to the class definition in Example Code Ch 02-1. A reasonable documentation comment for this program might be a. //a program that demonstrates the differences between print, println, and how + works b. //a program that outputs a message about Texas c. //a program that demonstrates nothing at all d. //a program that outputs the message "Here There Everywhere But not in Texas e. //a program that contains three output statements ANS: A Remember that comments should not state the obvious (ruling out D and E) but instead should explain what the program is doing or why. This program demonstrates print and println and +. 5. The following statement will output __________ lines of text. System.out.println("1 big bad wolf\t8 the 3 little pigs\n4 dinner\r2night"); a. b. c. d. e.
1 2 3 4 5
ANS: B The \t escape sequence inserts a tab, but leaves the cursor on the same line. The \n escape sequence causes a new line to be produced so that 4 dinner is output on the next line. The escape sequence \r causes the carriage to return (that is, the cursor to be moved back to the left margin) but because it does not start a new line, 2night is output over 4 dinn resulting in a second line that looks like 2nighter. 6. If you want to output the text "hi there" including the quote marks, which of the following would you use?
a. b. c. d. e.
System.out.println("hi there"); System.out.println(""hi there""); System.out.println("\"hi there"); System.out.println("\"hi there\""); None of these; it is not possible to output a quote mark because it is used to mark the beginning and end of the String to be displayed.
ANS: D \" is an escape sequence used to place a quote mark in a String, so it is used here to output the quote marks with the rest of the String. 7. The word println is a(n) a. b. c. d. e.
method reserved word variable class String
ANS: A The word println is passed as a message to the System.out object, and so println is a method. 8. A Java variable is the name of a a. numeric data value stored in memory b. data value stored in memory that cannot change during the program's execution c. data value stored in memory that can change its value but cannot change its type during the program's execution d. data value stored in memory that can change both its value and its type during the program's execution e. data value or a class stored in memory that can change both its value and its type during the program's execution ANS: C A variable can change its value as long as it is within the same type, but the variable cannot change type. A constant is similar to a variable but it cannot change its value. Variables can be numeric but are not restricted to being numeric, they can also be boolean, char, or an object of any class. 9. Of the following types, which one cannot store a numeric value? a. b. c. d. e.
int double float char All of these can store numeric values
ANS: D int and byte are used to store whole numbers (integers) and float is used to store a real or floating point value (value with a decimal point). A char stores a single character including letters, punctuation marks and digits. However, storing the numeric digit '5' is not the same as storing the number 5.
10. What is the value of z after the following assignment statement is executed? float z = 5/10; a. b. c. d. e.
0.0 0.5 5.0 0.05 None of these; a run-time error will occur because z is a float and 5/10 is an int.
ANS: A 5 and 10 are both int values, so 5 / 10 is an integer division. The result is 0. Even though z is a float and can store the real answer, 0.5, it only gets 0 because of the integer division. In order to get 0.5, we would have to first cast 5 or 10 as a float. 11. Which of the following situations would require a cast? a. b. c. d. e.
using charAt to take an element of a String and store it in a char storing an int in a float storing a float in a double storing a float in an int All of these require casts
ANS: D For A, charAt returns a char, so there is no problem. In B and C, the situations are widening operations taking a narrower type and storing the value in a wider type. Only in D is there a situation where a wider type is being stored in a narrower type, so a cast is required. 12. If x is an int and y is a float, which of the following statements is not a legal assignment statement? a. b. c. d. e.
y = x; x = y; y = (float)x; x = (int)y; All of these are legal assignment statements
ANS: B Since x is an int, it cannot except a float unless the float is cast as an int. There is no explicit cast in the assignment statement in B. In A, a cast is not necessary because a float (y) can accept an int value (x), and in C and D, explicit casts are present making them legal. 13. What will be the result of the following assignment statement, given that b = 5 and c = 10? int a = b * (-c + 2)/2; a. b. c. d. e.
30 -30 20 -20 -6
ANS: D The unary minus is applied first giving -c + 2 = -8. Next, the * is performed giving 5*-8=40, and finally the / is performed giving -40/2 = -20.
14. Which of the following is true regarding the mod operator, %? a. b. c. d. e.
It can only be performed on int values and its result is a double. It can only be performed on int values and its result is an int. It can only be performed on float or double.values and its result is an int. It can only be performed on float or double.values and its result is a double. It can be performed on any numeric values and its result is always numeric.
ANS: E Mod, or modulo, returns the remainder that results from a division. The remainder is always is numeric. Although usually integer values are used, the % operator may be used on all kinds of numeric data. 15. Assume that x, y, and z are all ints equal to 50, 20, and 6 respectively. What is the result of: x / y / z a. b. c. d. e.
0 12 16 this would cause a syntax error this would cause a run-time error because it is a division by zero
ANS: A This division is performed left to right, so first 50/20 is performed. Since 50 and 20 are ints, this results in 2. Next, 2/6 is performed which is 0. Notice that if the division were performed right to left, the evaluation would instead be 50/(20/6) = 50/3 = 16. 16. Assume that x and y are ints equal to 10 and 5 respectively. What is the output of the following statement? System.out.println(x + y); a. b. c. d. e.
15 105 10 5 x + y this would cause an error since neither x nor y is a String
ANS: A Java first computes x+y and then casts it as a String to be output. x+y= 10 + 5 = 15, so the statement outputs 15. 17. Assume that x and y are ints equal to 10 and 5 respectively. What is the output of the following statement? System.out.println("" + x + y); a. b. c. d. e.
15 105 10 5 x + y this would cause an error since neither x nor y is a String
ANS: B The "" causes the rest of the expression to be treated as a String, and so the two + signs are used as String concatenation. Therefore x+y becomes x concatenated with y, or 105. 18. If you want to store the value "Harry Potter" in the String variable name, which of the following statements could you use? a. b. c. d. e.
String name = "Harry Potter"; String name = new String("Harry Potter"); String name = "Harry" + " " + "Potter"; String name = new String("Harry" + " " + "Potter"); Any of these would work
ANS: E There are two ways to store a character string into a String variable, by constructing a new String using new String(string value); or by using an assignment statement, so either A or B will work. In C and D, we have variations where the String concatenation operator is used. So all four approaches will work. 19. Given three String variables, a, b, and c, which of the following statements could you use to achieve the same thing as: c = a + b; a. b. c. d. e.
c = a.length() + b.length(); c = (int)a + (int)b; c = a.concat(b); c = b.concat(a); c = a.plus(b);
ANS: C The statement c = a + b uses the concatenation operator (not to be confused with numeric addition). The same result can be achieved by passing a the concat message with b as the parameter. Answer D will set c to be b + a rather than a + b. 20. If the String major = "Computer Science", what is returned by major.charAt(1)? a. b. c. d. e.
'C' 'o' 'm' "C" "Computer"
ANS: B Neither D nor E would be correct because charAt returns a char (single character) whereas these answers are Strings. So, the question is, which character is returned? In Java, the first character of a String is numbered 0. So charAt(1) returns the second character of the String, or 'o'. 21. Which of the following would return the last character of the String x? a. x.charAt(0); b. x.charAt(last); c. x.charAt(length(x));
d. x.charAt(x.length()-1); e. x.charAt(x.length()); ANS: D Since last is not defined, B is syntactically invalid. The 0th character is the first in the String, so A is true only if the String has a single character. The answer in C is syntactically invalid as length can only be called by passing the message to x. Finally, D and E are syntactically valid, but since length returns the size of the String, and since the first character starts at the 0th position, the last character is at x.length()-1, so E would result in a run-time error. 22. Given String name = "Arleen Crabtree". What will the following instruction return? name.toUpperCase().replace('R', 'Z'); a. b. c. d. e.
"ARLEEN CRABTREE" "AZLEEN CZABTREE" "Azleen Czabtree" "Arleen Crabtree" "ArZleen CrZabtree"
ANS: B The toUpperCase method returns the String as all upper case characters, or "ARLEEN CRABTREE". The replace method will replace each instance of R with Z. 23. Which library package would you import to use NumberFormat and DecimalFormat? a. b. c. d. e.
java.beans java.io java.lang java.text java.util
ANS: D Both of these classes are used for "text processing", that is, to handle values like Strings. Such classes are found in java.text. You might think these would be in java.io, but this library has classes related to input and sending output to locations other than the monitor. 24. Which library package would you import to use the class Random? a. b. c. d. e.
java.beans java.io java.lang java.text java.util
ANS: E This is a Java numeric utility, and so is found in the java.util package. 25. The Random class has a method, nextFloat() which returns a random float value between a. b. c. d.
-1 and +1 0 and 1 0 and 99 1 and 100
e. -2,147,483,648 and +2,147,483,647 ANS: B The method nextFloat() returns a float value between 0 and 1 so that it may be used as a probability. 26. If you want to output a double so that at least one digit appears to the left side of the decimal point and exactly one digit appears to the right side, which pattern would you give a DecimalFormat variable when you instantiate it? a. b. c. d. e.
"0.0" "0.#" "0.0#" "0.##" "#.#"
ANS: A The pattern "0.0" says to output all of the digits to the left of the decimal point or a 0 if there are none (you want at least 1 digit to the left, including a 0 if there are no digits) and exactly one digit to the right of the decimal point, even if the digit is 0. The patterns "0.#" and "#.#" would not output any digits to the right side of the decimal point if the value had no decimal portion (e.g., 39.0). The patterns in C and D can output up to 2 values to the right of the decimal point. 27. Given the double likelihood = 0.013885 and given DecimalFormat dformatter = DecimalFormat("0.00##"); What would be the output if you execute the following: System.out.println(df.format(likelihood)); a. b. c. d. e.
0.013885 0.0139 0.0145 .0138 .014
ANS: B The format "0.00##" means that at least 1 digit should appear to the left of the decimal point, even if it is 0, that at least two digits should appear to the right of the decimal point even if they are zeros, and if there are two additional digits to the right, they should also be printed, rounding the value off as needed. So, this gives 0.0139 since the number, 0.013885 will be rounded up to 0.0139. 28. Using getCurrencyInstance() formats a variable, automatically inserting a. b. c. d. e.
a decimal point for cents a dollar sign a percent sign all three of these a decimal point for cents and a dollar sign but not a percent sign
ANS: E getCurrencyInstance will format a double or float variable so that it has 2 digits to the right of the decimal point and a dollar sign preceding the value. getPercentInstance is used to format a double or float to be output with a percent sign.
29. What will be the value of z after the following statement is executed? int z = 50 /10.00; a. b. c. d. e.
5 5.0 50 10 None of thse; a run-time error will occur because z is an int and 50/10.00 is not
ANS: E Because 10.00 is not an int, the division produces a double precision value which cannot be stored in the int z. For this to work, the result of the division must be cast as an int before being stored in z, or the value 10.00 would have to first be cast as an int before the division takes place. 30. Since you cannot take the square root of a negative number, which of the following could you use to find the square root of the variable x? a. b. c. d. e.
Math.sqrt(x*x); Math.sqrt((int)x); Math.sqrt(Math.abs(x)); Math.abs(Math.sqrt(x)); Math.sqrt(-x);
ANS: C Math.abs returns the absolute value of x. If x is negative, Math.sqrt(x)causes a run-time error, but Math.sqrt(Math.abs(x))does not since x is first converted to its positive equivalent before the square root is performed. Answer A returns x (square root of x^2 is x). In answer B, casting x to an int will not resolve the problem if x is negative. In answer D, the two Math functions are performed in opposite order and so if x is negative, it still generates a run-time error. Answer E only will work if x is not positive and so if x is positive, it now generates a run-time error. 31. Given x is a double and has the value 0.362491. To output this value as 36%, you could use the NumberFormat class with: NumberFormat nf = NumberFormat.getPercentInstance(); Which of the following statements then would output x as 36%? a. b. c. d. e.
System.out.println(x); System.out.println(nf); System.out.println(nf.format(x)); System.out.println(nf.x); System.out.println(format(x));
ANS: C nf is an object and so must be passed a message to use it. The method to format a float or double is called format and the value to be formatted is the parameter passed to format. Therefore, the proper way to do this is nf.format(x). The answer in A merely outputs 0.362491 while the answers to B, C, and E are syntactically invalid. Example Code Ch 02-2 import java.util.Scanner;
public class Questions33_34 { public static void main(String[] args) { int x, y, z; double average; Scanner scan = new Scanner(System.in); System.out.println("Enter an integer value"); x = scan.nextInt(); System.out.println("Enter another integer value"); y = scan.nextInt(); System.out.println("Enter a third integer value"); z = scan.nextInt(); average = (x + y + z) / 3; System.out.println("The result of my calculation is " + average); } } 32. Refer to Example Code Ch 02-2. This code computes a. b. c. d. e.
The correct average of x, y, and z as a double The correct average of x, y, and z as an int The average of x, y, and z as a double but the result may not be accurate The sum of x, y, and z as an int The remainder of the sum of x, y, and z divided by 3
ANS: C Because the division is an int division, even though the result is stored in a double, the resulting double may not be accurate. For instance, if x, y and z are 1, 2, and 4, the double average should be 2.33333 but average will instead be 2.00000. 33. Refer to Example Code Ch 02-2. What is the output if x = 0, y = 1, and z = 1? a. b. c. d. e.
0 0.0 0.6666666666666666 0.6666666666666667 0.67
ANS: B The division is performed as an int division since x, y, z, and 3 are all ints. Therefore, average gets the value 0.0. It is output as 0.0 instead of 0 because average is a double, which outputs at least one decimal digit unless specified otherwise using the DecimalFormat class. 34. In order to create a constant, which of the following Java reserved words is used? a. b. c. d. e.
private static int final class
ANS: D
The reserved word final indicates that this is the final value that will be stored in this variable, thus making it unchangeable, or constant. While constants can be of type int, constants can be of any other type as well. It is the final reserved word that makes the value unchangeable. 35. Given three int variables with the values a = 5, b = 7, and c = 12, what is the value of z after the following statement is executed? int z = (a * b - c) / a; a. b. c. d. e.
0 4 5 -5 23
ANS: B (a * b - c) / a = (5 * 7 - 12) / 5 = (35 - 12) / 5 = 23 / 5, and since 23 and 5 are int values, the division is performed as an int division, or 23 / 5 = 4. 36. Java is a strongly typed language. What is meant by "strongly typed"? a. Every variable must have an associated type before it can be used. b. Variables can be used without declaring their types. c. Every variable has a single type associated with it throughout its existence in the program and the variable can only store values of that type. d. Variables are allowed to change type during their existence in a program so long as the value a variable currently stores is of the type it currently declared to be. e. Variables are allowed to change types during their existence in a program but only if the change is to a narrower type. ANS: C Strong typing is a property of a programming language whereby the variable's type does not change during the variable's existence, and any value stored in that variable is of that type. The reason that strong typing is important is it guarantees that a program that was successfully compiled will not have run-time errors associated with the misuse of types for the variables declared. 37. As presented in the Software Failure section of the text, the root cause of the Mars Climate Orbiter problem was a. b. c. d. e.
the cost of the project an inability to track the orbiter at long distances atmospheric friction a communication issue between subsystems None of these
ANS: D The cause was determined to be an embarrassing communication issue between subsystems. The navigation subsystem used imperial units of measure (pound-force) and the spacecraft's software itself expected data in metric units (newtons).
PROBLEM
1. Write a set of instructions to prompt the user for an int value and input it using the Scanner class into the variable x and prompt the user for a float value and input it using the Scanner class into the variable y. ANS: Scanner scan = Scanner.create(System.in); System.out.println("Enter an integer"); int x = scan.nextInt(); System.out.println("Enter a float"); float y = scan.nextFloat(); 2. Provide an example of how you might use a boolean, a float, a char, a String, and an
int. ANS: Answers may vary. Samples: boolean to store whether a person is of voting age or not float: to store someone's GPA char: to store someone's middle initial String: to store someone's social security number int: to store someone's age 3. Explain what the following statement computes: int z = (int)Math.ceil(Math.sqrt(x)/Math.sqrt(y)); ANS: The integer value which bounds sqrt(x)/sqrt(y)where bounds means it is equal to the result of the division or the next int larger than the result of the division if the result has a remainder. 4. Given four int values, x1, x2, y1, y2, write the code to compute the distance between the two points (x1, y1) and (x2, y2), storing the result in the double distance. ANS: double distance = Math.sqrt(Math.pow(x1 - y1, 2) + Math.pow(x2 y2,2)); 5. Write an assignment statement to compute the gas mileage of a car where the int values milesTraveled and gallonsNeeded have already been input. The variable gasMileage needs to be declared and should be a double. ANS: double gasMileage = (double)milesTraveled/gallonsNeeded; The reason that the value milesTraveled is cast as a double is to ensure that the division is performed as a double and not an int.
6. Write the paint method for an applet so that it contains 4 concentric circles (each circle is inside the previous circle), where the largest circle is bounded by a 400x400 box and the smallest is bounded by a 100x100 box. Each circle is centered on an applet that is 400x400. Make each circle a different color of your choice. ANS: public void paint(Graphics page) { page.setColor(Color.white); page.fillOval(0, 0, 400, 400); page.setColor(Color.yellow); page.fillOval(50, 50, 300, 300); page.setColor(Color.orange); page.fillOval(100, 100, 200, 200); page.setColor(Color.red); page.fillOval(150, 150, 100, 100); } 7. Given two points in an applet represented by the four int variables x1, y1, x2 and y2, write a paint method to draw a line between the two points and write the location of the two points next to the two points. ANS: public void paint(Graphics page) { page.setColor(Color.blue); page.drawLine(x1, y1, x2, y2); page.drawString("" + x1 + ", " + y1, x1, y1); page.drawString("" + x2 + ", " + y2, x2, y2); } 8. An employer has decided to award a weekly pay raise to all employees by taking the square root of the difference between his weight and the employee's weight. For instance, an employee who weighs 16 pounds less than the employer will get a $4 per week raise. The raise should be in whole dollars (an int). Assume that employerWeight and employeeWeight are both int variables that have been input. Write an assignment statement to compute the int value for raise. ANS: raise = (int) Math.sqrt(Math.abs(employerWeight - employeeWeight)); The absolute value of the difference must be taken in case the employee weighs more than the employer, which would then result in an attempt to take the square root of a negative number. So Math.abs is used. After computing the absolute value of the difference, the square root is taken and the result (a double) is cast as an int to be stored in raise. 9. Using the various String methods, manipulate a String called current to be the last character of current followed by the remainder of its characters in order, placing the result in a String called rearranged. ANS:
String rearranged = current.charAt(current.length() - 1) + current.substring(0, current.length() - 2); The last character, which is found at charAt(current.length() - 1) is the first item in rearranged, followed by the substring of current starting at 0 (the first character) and going to current.length() - 2 (the second to last character). 10. How many ways are there to test to see if two String variables, a and b, are equal to each other if we ignore their case (for instance, "aBCd" would be considered equal to "ABcd")? ANS: There are at least 10 ways that this can be done: a.toLowerCase().equals(b.toLowerCase()); b.toLowerCase().equals(a.toLowerCase()); a.toUpperCase().equals(b.toUpperCase()); b.toUpperCase().equals(a.toUpperCase()); a.equalsIgnoreCase(b); b.equalsIgnoreCase(a); a.equalsIgnoreCase(b.toLowerCase()); a.equalsIgnoreCase(b.toUpperCase()); b.equalsIgnoreCase(a.toLowerCase()); b.equalsIgnoreCase(a.toUpperCase()); 11. How do the statements "import java.util.*;" and "import java.util.Random;"
differ from each other? ANS: In the former, all of the classes defined in the java.util library are imported whereas in the latter, only the Random class is imported from the java.util library. The former approach is easier but more time consuming and wasteful of memory, so the latter approach is more appropriate if you only want to use a single class from a given library. 12. Assume that a = "1", b = "2", y = 3, and z = 4. How do the following two statements differ? System.out.println(a + b + y + z); System.out.println(y + z + a + b); ANS: In the first statement, since a and b are Strings, a + b + c + d is treated as String concatenation and the statement outputs 1234. In the second statement, y + z is treated as int addition, which is then cast as a String to be concatenated with y + z, giving 712 instead of 3412 as you might expect. 13. Write a program which will input an int value, x, and compute and output the values of 2^x and x^10 as int values. ANS: import java.util.Scanner;
public class Compute14 { public static void main(String[] args) { Scanner scan = Scanner.create(System.in); System.out.println("Enter an integer value"); int x = scan.nextInt(); int twoToTheX = (int) Math.pow(2, x); int xToThe10th = (int) Math.pow(x, 10); System.out.println("The results are " + twoToTheX + " and " + xToThe10th); } } 14. What is wrong with the following assignment statement? Assume x and y are both String objects. String z = x.equals(y); ANS: The equals method returns a boolean value, not a String. The values true and false are not the same as the values "true" and "false. 15. Write a program that will input some number of cents (less than 100) and output the number of quarters, dimes, nickels and pennies needed to add up to that amount. ANS: import java.util.Scanner; public class Change { public static void main(String[] args) { Scanner scan = Scanner.create(System.in); System.out.println("Enter the amount of change"); int amount = scan.nextInt(); System.out.println("The change for " + amount " cents is: "); int quarters = amount / 25; System.out.println(" " + quarters + " quarters"); amount = amount - quarters * 25; int dimes = amount / 10; System.out.println(" " + dimes + " dimes"); amount = amount - dimes * 10; int nickels = amount / 5; System.out.println(" " + nickels + " nickels"); amount = amount - nickels * 5; int pennies = amount; System.out.println(" " + pennies + " pennies"); } } 16. Write an output statement which will output the following characters exactly as shown: / ' \" / ' \
ANS: System.out.println("/ \ ' \ \ \" / \ ' \ \ ");
17. Provide three examples of code using assignment statements where one assignment statement would result in a syntax error, one would result in a logical error, and one would result in a run-time error. ANS: Answers will vary. Examples: // syntax error caused by right side providing a double and the left side wants an int: int x = 5.0 / 2.0; // logical error caused by not casting the division as a double: double x = (intValue1 + intValue2) / 2; // run-time error caused by division by 0 when y - y is evaluated: int x = 5 / (y - y); 18. What are the syntax errors from the following program? public class Enigma { public static void main(String[] args) { System.out.println("Input a String"); String x = scan.nextString(); int size = x.length; char last = x.charAt(size); System.out.println("The last character in your string ", x, " is ", last); } } ANS: There are 3 syntax errors. First, the Scanner class has not been imported so that the scan.nextString()will yield a syntax error. Second, the statement x.length requires parentheses as length is a method of the class String, so this is a message passed to x. Finally, the System.out.println statement is not valid because of the use of a comma instead of + to concatenate the various parts of the String. Note that in spite of these syntax errors, there is a runtime error. This error would arise because size will store the length of the String, but the last character will be at location size-1 instead of size. Thus, the statement char last = x.charAt(size); will result in a run-time error because size is beyond the bounds of the String x.
Java Software Solutions, 9e (Lewis/Loftus) Chapter 2 Data and Expressions TRUE/FALSE 1. If x is a String, then x = new String("OH"); and x = "OH"; will accomplish the same thing. ANS: T In Java, to instantiate (assign a value to) an object, you must use new and the class's constructor. However, since Strings are so common in Java, they can be instantiated in a way similar to assigning primitive types their values. So, both of the above assignment statements will accomplish the same task. 2. If x is the String "Hi There", then x.toUpperCase().toLowerCase(); will return the original value of x. ANS: F x.toUpperCase() returns x as all capital letters, while x.toLowerCase()will return x as all lower case letters. So, this code will first convert x to all upper case letters and then convert the new version to all lower case characters. 3. If String name = "George W. Bush"; then the instruction name.length(); will return 14. ANS: T There are 14 characters between the quote marks including two blanks and a period. 4. If String a = "ABCD" and String b = "abcd" then a.equals(b); returns false but a.equalsIgnoreCase(b); returns true. ANS: T Since "ABCD" is not the same as "abcd", the equals method returns false, but by ignoring case in equalsIgnoreCase, the two are considered to be the same. 5. Unlike the String class where you must pass a message to an object (instance) of the class, as in x.length(), in order to use either the Scanner or Math classes, you pass messages directly to the class name, as in Math.abs()or scan.nextInt(). ANS: T The Math and Scanner classes use methods known as static methods (or class methods) which are invoked by passing a message directly to the class name itself rather than to an object of the class. 6. In order to generate a random number, you must use Math.random(). ANS: F
There is also a Random class available in java.util. This class can generate random int, float, and double values. This is a better mechanism for generating random numbers because you can instantiate several different random number generators. 7. A double is wider than a float and a float is wider than an int. ANS: T Wider types are larger in size or can store a greater range of values. The double is 64 bits whereas the float is 32 bits and the float, because of the way it is stored, can store a significantly larger range of values than the int. 8. A variable of type boolean will store either a 0 or a 1. ANS: F A boolean variable can store only one of two values, but these values are the reserved words true and false. In C, C++, and C# booleans are implemented as int variables that store only a 0 or a 1, but in Java, the authors of the language opted to use the boolean literals true and false as this is considered to be semantically more understandable (and is much safer). 9. In Java, 'a' and 'A' are considered to be different values. ANS: T Characters values are stored using ASCII, and 'a' and 'A' have different ASCII values as well as different Unicode values. 10. You cannot cast a String to be a char and you cannot cast a String which stores a number to be an int, float, or double. ANS: T There is no mechanism available to cast a String to one of the primitive types, but there are methods available to perform a similar action and return a character at a given location (CharAt) or to return the int, float, or double value equivalent to the number stored in the String. 11. The values of (double)5/2 and (double)(5/2) are identical. ANS: F In the first expression, the (double) cast applies to theint 5, changing it to the double value, 5.0. Then 5.0/2 is calculated, yielding the double value, 2.5. In the second expression the int division is performed first, yielding the value 2. 2 is then changed to a double, yielding the double value, 2.0. 12. There are three ways that data conversion may occur: by assignment, by promotion, and by casting. ANS: T
Assignment conversion occurs when a value on the right side of the assignment operator is converted prior to being stored in the variable on the left. Promotion occurs within an expression when values of differing widths are combined. Casting is a programmer's explicit way to control the data conversion process. 13. As explained in the Software Failure section in the text, the Mars Lander most likely crash landed when its descent engines cut off too high over the Mars surface. ANS: T The software on board the lander mistook the vibrations caused by the deployment of the lander's legs for the vibration caused by actually landing on the planet's surface.
MULTIPLE CHOICE Example Code Ch 02-1 public class Questions1_4 { public static void main(String[] args) { System.out.print("Here"); System.out.println("There " + "Everywhere"); System.out.println("But not" + "in Texas"); } } 1. Refer to the class definition in Example Code Ch 02-1. The program will print the word "Here" and then print a. b. c. d. e.
"There Everywhere" on the line after "Here" "The" on the line after "Here" and "Everywhere" on the line after "There" "There Everywhere" on the same line as "Here" "ThereEverywhere" on the same line as "Here" "ThereEverywhere" on the line after "Here"
ANS: C System.out.print will output the word Here but will leave the cursor at that point rather than starting a new line. The next statement will output There Everywhere immediately after the word Here. Since there is a blank space within the quote marks for There, there is a blank space inserted between There and Everywhere. 2. Refer to the class definition in Example Code Ch 02-1. The final println command will output a. b. c. d. e.
"But not in Texas" "But notin Texas" "But not" on one line and "in Texas" on the next line "But not+in Texas" "But not + in Texas"
ANS: B
The + performs String concatenation, so that But not and in Texas are concatenated together. Notice that there is no blank space after not or before in so that when they are concatenated, they are placed together without a blank space. 3. Refer to the class definition in Example Code Ch 02-1. How many lines of output are provided by this program? a. b. c. d. e.
1 2 3 4 5
ANS: B There will be one line of output for the first two statements combined because the print statement does not return the cursor to start a new line. And since the second statement is a println, it returns the cursor and the last println outputs its message on a separate line. 4. Refer to the class definition in Example Code Ch 02-1. A reasonable documentation comment for this program might be a. //a program that demonstrates the differences between print, println, and how + works b. //a program that outputs a message about Texas c. //a program that demonstrates nothing at all d. //a program that outputs the message "Here There Everywhere But not in Texas e. //a program that contains three output statements ANS: A Remember that comments should not state the obvious (ruling out D and E) but instead should explain what the program is doing or why. This program demonstrates print and println and +. 5. The following statement will output __________ lines of text. System.out.println("1 big bad wolf\t8 the 3 little pigs\n4 dinner\r2night"); a. b. c. d. e.
1 2 3 4 5
ANS: B The \t escape sequence inserts a tab, but leaves the cursor on the same line. The \n escape sequence causes a new line to be produced so that 4 dinner is output on the next line. The escape sequence \r causes the carriage to return (that is, the cursor to be moved back to the left margin) but because it does not start a new line, 2night is output over 4 dinn resulting in a second line that looks like 2nighter. 6. If you want to output the text "hi there" including the quote marks, which of the following would you use?
a. b. c. d. e.
System.out.println("hi there"); System.out.println(""hi there""); System.out.println("\"hi there"); System.out.println("\"hi there\""); None of these; it is not possible to output a quote mark because it is used to mark the beginning and end of the String to be displayed.
ANS: D \" is an escape sequence used to place a quote mark in a String, so it is used here to output the quote marks with the rest of the String. 7. The word println is a(n) a. b. c. d. e.
method reserved word variable class String
ANS: A The word println is passed as a message to the System.out object, and so println is a method. 8. A Java variable is the name of a a. numeric data value stored in memory b. data value stored in memory that cannot change during the program's execution c. data value stored in memory that can change its value but cannot change its type during the program's execution d. data value stored in memory that can change both its value and its type during the program's execution e. data value or a class stored in memory that can change both its value and its type during the program's execution ANS: C A variable can change its value as long as it is within the same type, but the variable cannot change type. A constant is similar to a variable but it cannot change its value. Variables can be numeric but are not restricted to being numeric, they can also be boolean, char, or an object of any class. 9. Of the following types, which one cannot store a numeric value? a. b. c. d. e.
int double float char All of these can store numeric values
ANS: D int and byte are used to store whole numbers (integers) and float is used to store a real or floating point value (value with a decimal point). A char stores a single character including letters, punctuation marks and digits. However, storing the numeric digit '5' is not the same as storing the number 5.
10. What is the value of z after the following assignment statement is executed? float z = 5/10; a. b. c. d. e.
0.0 0.5 5.0 0.05 None of these; a run-time error will occur because z is a float and 5/10 is an int.
ANS: A 5 and 10 are both int values, so 5 / 10 is an integer division. The result is 0. Even though z is a float and can store the real answer, 0.5, it only gets 0 because of the integer division. In order to get 0.5, we would have to first cast 5 or 10 as a float. 11. Which of the following situations would require a cast? a. b. c. d. e.
using charAt to take an element of a String and store it in a char storing an int in a float storing a float in a double storing a float in an int All of these require casts
ANS: D For A, charAt returns a char, so there is no problem. In B and C, the situations are widening operations taking a narrower type and storing the value in a wider type. Only in D is there a situation where a wider type is being stored in a narrower type, so a cast is required. 12. If x is an int and y is a float, which of the following statements is not a legal assignment statement? a. b. c. d. e.
y = x; x = y; y = (float)x; x = (int)y; All of these are legal assignment statements
ANS: B Since x is an int, it cannot except a float unless the float is cast as an int. There is no explicit cast in the assignment statement in B. In A, a cast is not necessary because a float (y) can accept an int value (x), and in C and D, explicit casts are present making them legal. 13. What will be the result of the following assignment statement, given that b = 5 and c = 10? int a = b * (-c + 2)/2; a. b. c. d. e.
30 -30 20 -20 -6
ANS: D The unary minus is applied first giving -c + 2 = -8. Next, the * is performed giving 5*-8=-40, and finally the / is performed giving -40/2 = -20.
14. Which of the following is true regarding the mod operator, %? a. b. c. d. e.
It can only be performed on int values and its result is a double. It can only be performed on int values and its result is an int. It can only be performed on float or double.values and its result is an int. It can only be performed on float or double.values and its result is a double. It can be performed on any numeric values and its result is always numeric.
ANS: E Mod, or modulo, returns the remainder that results from a division. The remainder is always is numeric. Although usually integer values are used, the % operator may be used on all kinds of numeric data. 15. Assume that x, y, and z are all ints equal to 50, 20, and 6 respectively. What is the result of: x / y / z a. b. c. d. e.
0 12 16 this would cause a syntax error this would cause a run-time error because it is a division by zero
ANS: A This division is performed left to right, so first 50/20 is performed. Since 50 and 20 are ints, this results in 2. Next, 2/6 is performed which is 0. Notice that if the division were performed right to left, the evaluation would instead be 50/(20/6) = 50/3 = 16. 16. Assume that x and y are ints equal to 10 and 5 respectively. What is the output of the following statement? System.out.println(x + y); a. b. c. d. e.
15 105 10 5 x + y this would cause an error since neither x nor y is a String
ANS: A Java first computes x+y and then casts it as a String to be output. x+y= 10 + 5 = 15, so the statement outputs 15. 17. Assume that x and y are ints equal to 10 and 5 respectively. What is the output of the following statement? System.out.println("" + x + y); a. b. c. d. e.
15 105 10 5 x + y this would cause an error since neither x nor y is a String
ANS: B The "" causes the rest of the expression to be treated as a String, and so the two + signs are used as String concatenation. Therefore x+y becomes x concatenated with y, or 105. 18. If you want to store the value "Harry Potter" in the String variable name, which of the following statements could you use? a. b. c. d. e.
String name = "Harry Potter"; String name = new String("Harry Potter"); String name = "Harry" + " " + "Potter"; String name = new String("Harry" + " " + "Potter"); Any of these would work
ANS: E There are two ways to store a character string into a String variable, by constructing a new String using new String(string value); or by using an assignment statement, so either A or B will work. In C and D, we have variations where the String concatenation operator is used. So all four approaches will work. 19. Given three String variables, a, b, and c, which of the following statements could you use to achieve the same thing as: c = a + b; a. b. c. d. e.
c = a.length() + b.length(); c = (int)a + (int)b; c = a.concat(b); c = b.concat(a); c = a.plus(b);
ANS: C The statement c = a + b uses the concatenation operator (not to be confused with numeric addition). The same result can be achieved by passing a the concat message with b as the parameter. Answer D will set c to be b + a rather than a + b. 20. If the String major = "Computer Science", what is returned by major.charAt(1)? a. b. c. d. e.
'C' 'o' 'm' "C" "Computer"
ANS: B Neither D nor E would be correct because charAt returns a char (single character) whereas these answers are Strings. So, the question is, which character is returned? In Java, the first character of a String is numbered 0. So charAt(1) returns the second character of the String, or 'o'. 21. Which of the following would return the last character of the String x? a. x.charAt(0); b. x.charAt(last); c. x.charAt(length(x));
d. x.charAt(x.length()-1); e. x.charAt(x.length()); ANS: D Since last is not defined, B is syntactically invalid. The 0th character is the first in the String, so A is true only if the String has a single character. The answer in C is syntactically invalid as length can only be called by passing the message to x. Finally, D and E are syntactically valid, but since length returns the size of the String, and since the first character starts at the 0th position, the last character is at x.length()-1, so E would result in a run-time error. 22. Given String name = "Arleen Crabtree". What will the following instruction return? name.toUpperCase().replace('R', 'Z'); a. b. c. d. e.
"ARLEEN CRABTREE" "AZLEEN CZABTREE" "Azleen Czabtree" "Arleen Crabtree" "ArZleen CrZabtree"
ANS: B The toUpperCase method returns the String as all upper case characters, or "ARLEEN CRABTREE". The replace method will replace each instance of R with Z. 23. Which library package would you import to use NumberFormat and DecimalFormat? a. b. c. d. e.
java.beans java.io java.lang java.text java.util
ANS: D Both of these classes are used for "text processing", that is, to handle values like Strings. Such classes are found in java.text. You might think these would be in java.io, but this library has classes related to input and sending output to locations other than the monitor. 24. Which library package would you import to use the class Random? a. b. c. d. e.
java.beans java.io java.lang java.text java.util
ANS: E This is a Java numeric utility, and so is found in the java.util package. 25. The Random class has a method, nextFloat() which returns a random float value between a. b. c. d.
-1 and +1 0 and 1 0 and 99 1 and 100
e. -2,147,483,648 and +2,147,483,647 ANS: B The method nextFloat() returns a float value between 0 and 1 so that it may be used as a probability. 26. If you want to output a double so that at least one digit appears to the left side of the decimal point and exactly one digit appears to the right side, which pattern would you give a DecimalFormat variable when you instantiate it? a. b. c. d. e.
"0.0" "0.#" "0.0#" "0.##" "#.#"
ANS: A The pattern "0.0" says to output all of the digits to the left of the decimal point or a 0 if there are none (you want at least 1 digit to the left, including a 0 if there are no digits) and exactly one digit to the right of the decimal point, even if the digit is 0. The patterns "0.#" and "#.#" would not output any digits to the right side of the decimal point if the value had no decimal portion (e.g., 39.0). The patterns in C and D can output up to 2 values to the right of the decimal point. 27. Given the double likelihood = 0.013885 and given DecimalFormat dformatter = DecimalFormat("0.00##"); What would be the output if you execute the following: System.out.println(df.format(likelihood)); a. b. c. d. e.
0.013885 0.0139 0.0145 .0138 .014
ANS: B The format "0.00##" means that at least 1 digit should appear to the left of the decimal point, even if it is 0, that at least two digits should appear to the right of the decimal point even if they are zeros, and if there are two additional digits to the right, they should also be printed, rounding the value off as needed. So, this gives 0.0139 since the number, 0.013885 will be rounded up to 0.0139. 28. Using getCurrencyInstance() formats a variable, automatically inserting a. b. c. d. e.
a decimal point for cents a dollar sign a percent sign all three of these a decimal point for cents and a dollar sign but not a percent sign
ANS: E getCurrencyInstance will format a double or float variable so that it has 2 digits to the right of the decimal point and a dollar sign preceding the value. getPercentInstance is used to format a double or float to be output with a percent sign.
29. What will be the value of z after the following statement is executed? int z = 50 /10.00; a. b. c. d. e.
5 5.0 50 10 None of thse; a run-time error will occur because z is an int and 50/10.00 is not
ANS: E Because 10.00 is not an int, the division produces a double precision value which cannot be stored in the int z. For this to work, the result of the division must be cast as an int before being stored in z, or the value 10.00 would have to first be cast as an int before the division takes place. 30. Since you cannot take the square root of a negative number, which of the following could you use to find the square root of the variable x? a. b. c. d. e.
Math.sqrt(x*x); Math.sqrt((int)x); Math.sqrt(Math.abs(x)); Math.abs(Math.sqrt(x)); Math.sqrt(-x);
ANS: C Math.abs returns the absolute value of x. If x is negative, Math.sqrt(x)causes a run-time error, but Math.sqrt(Math.abs(x))does not since x is first converted to its positive equivalent before the square root is performed. Answer A returns x (square root of x^2 is x). In answer B, casting x to an int will not resolve the problem if x is negative. In answer D, the two Math functions are performed in opposite order and so if x is negative, it still generates a run-time error. Answer E only will work if x is not positive and so if x is positive, it now generates a run-time error. 31. Given x is a double and has the value 0.362491. To output this value as 36%, you could use the NumberFormat class with: NumberFormat nf = NumberFormat.getPercentInstance(); Which of the following statements then would output x as 36%? a. b. c. d. e.
System.out.println(x); System.out.println(nf); System.out.println(nf.format(x)); System.out.println(nf.x); System.out.println(format(x));
ANS: C nf is an object and so must be passed a message to use it. The method to format a float or double is called format and the value to be formatted is the parameter passed to format. Therefore, the proper way to do this is nf.format(x). The answer in A merely outputs 0.362491 while the answers to B, C, and E are syntactically invalid. Example Code Ch 02-2 import java.util.Scanner;
public class Questions33_34 { public static void main(String[] args) { int x, y, z; double average; Scanner scan = new Scanner(System.in); System.out.println("Enter an integer value"); x = scan.nextInt(); System.out.println("Enter another integer value"); y = scan.nextInt(); System.out.println("Enter a third integer value"); z = scan.nextInt(); average = (x + y + z) / 3; System.out.println("The result of my calculation is " + average); } } 32. Refer to Example Code Ch 02-2. This code computes a. b. c. d. e.
The correct average of x, y, and z as a double The correct average of x, y, and z as an int The average of x, y, and z as a double but the result may not be accurate The sum of x, y, and z as an int The remainder of the sum of x, y, and z divided by 3
ANS: C Because the division is an int division, even though the result is stored in a double, the resulting double may not be accurate. For instance, if x, y and z are 1, 2, and 4, the double average should be 2.33333 but average will instead be 2.00000. 33. Refer to Example Code Ch 02-2. What is the output if x = 0, y = 1, and z = 1? a. b. c. d. e.
0 0.0 0.6666666666666666 0.6666666666666667 0.67
ANS: B The division is performed as an int division since x, y, z, and 3 are all ints. Therefore, average gets the value 0.0. It is output as 0.0 instead of 0 because average is a double, which outputs at least one decimal digit unless specified otherwise using the DecimalFormat class. 34. In order to create a constant, which of the following Java reserved words is used? a. b. c. d. e.
private static int final class
ANS: D
The reserved word final indicates that this is the final value that will be stored in this variable, thus making it unchangeable, or constant. While constants can be of type int, constants can be of any other type as well. It is the final reserved word that makes the value unchangeable. 35. Given three int variables with the values a = 5, b = 7, and c = 12, what is the value of z after the following statement is executed? int z = (a * b - c) / a; a. b. c. d. e.
0 4 5 -5 23
ANS: B (a * b - c) / a = (5 * 7 - 12) / 5 = (35 - 12) / 5 = 23 / 5, and since 23 and 5 are int values, the division is performed as an int division, or 23 / 5 = 4. 36. Java is a strongly typed language. What is meant by "strongly typed"? a. Every variable must have an associated type before it can be used. b. Variables can be used without declaring their types. c. Every variable has a single type associated with it throughout its existence in the program and the variable can only store values of that type. d. Variables are allowed to change type during their existence in a program so long as the value a variable currently stores is of the type it currently declared to be. e. Variables are allowed to change types during their existence in a program but only if the change is to a narrower type. ANS: C Strong typing is a property of a programming language whereby the variable's type does not change during the variable's existence, and any value stored in that variable is of that type. The reason that strong typing is important is it guarantees that a program that was successfully compiled will not have run-time errors associated with the misuse of types for the variables declared. 37. As presented in the Software Failure section of the text, the root cause of the Mars Climate Orbiter problem was a. b. c. d. e.
the cost of the project an inability to track the orbiter at long distances atmospheric friction a communication issue between subsystems None of these
ANS: D The cause was determined to be an embarrassing communication issue between subsystems. The navigation subsystem used imperial units of measure (pound-force) and the spacecraft's software itself expected data in metric units (newtons).
PROBLEM
1. Write a set of instructions to prompt the user for an int value and input it using the Scanner class into the variable x and prompt the user for a float value and input it using the Scanner class into the variable y. ANS: Scanner scan = Scanner.create(System.in); System.out.println("Enter an integer"); int x = scan.nextInt(); System.out.println("Enter a float"); float y = scan.nextFloat(); 2. Provide an example of how you might use a boolean, a float, a char, a String, and an
int. ANS: Answers may vary. Samples: boolean to store whether a person is of voting age or not float: to store someone's GPA char: to store someone's middle initial String: to store someone's social security number int: to store someone's age 3. Explain what the following statement computes: int z = (int)Math.ceil(Math.sqrt(x)/Math.sqrt(y)); ANS: The integer value which bounds sqrt(x)/sqrt(y)where bounds means it is equal to the result of the division or the next int larger than the result of the division if the result has a remainder. 4. Given four int values, x1, x2, y1, y2, write the code to compute the distance between the two points (x1, y1) and (x2, y2), storing the result in the double distance. ANS: double distance = Math.sqrt(Math.pow(x1 - y1, 2) + Math.pow(x2 - y2,2)); 5. Write an assignment statement to compute the gas mileage of a car where the int values milesTraveled and gallonsNeeded have already been input. The variable gasMileage needs to be declared and should be a double. ANS: double gasMileage = (double)milesTraveled/gallonsNeeded; The reason that the value milesTraveled is cast as a double is to ensure that the division is performed as a double and not an int.
6. Write the paint method for an applet so that it contains 4 concentric circles (each circle is inside the previous circle), where the largest circle is bounded by a 400x400 box and the smallest is bounded by a 100x100 box. Each circle is centered on an applet that is 400x400. Make each circle a different color of your choice. ANS: public void paint(Graphics page) { page.setColor(Color.white); page.fillOval(0, 0, 400, 400); page.setColor(Color.yellow); page.fillOval(50, 50, 300, 300); page.setColor(Color.orange); page.fillOval(100, 100, 200, 200); page.setColor(Color.red); page.fillOval(150, 150, 100, 100); } 7. Given two points in an applet represented by the four int variables x1, y1, x2 and y2, write a paint method to draw a line between the two points and write the location of the two points next to the two points. ANS: public void paint(Graphics page) { page.setColor(Color.blue); page.drawLine(x1, y1, x2, y2); page.drawString("" + x1 + ", " + y1, x1, y1); page.drawString("" + x2 + ", " + y2, x2, y2); } 8. An employer has decided to award a weekly pay raise to all employees by taking the square root of the difference between his weight and the employee's weight. For instance, an employee who weighs 16 pounds less than the employer will get a $4 per week raise. The raise should be in whole dollars (an int). Assume that employerWeight and employeeWeight are both int variables that have been input. Write an assignment statement to compute the int value for raise. ANS: raise = (int) Math.sqrt(Math.abs(employerWeight - employeeWeight)); The absolute value of the difference must be taken in case the employee weighs more than the employer, which would then result in an attempt to take the square root of a negative number. So Math.abs is used. After computing the absolute value of the difference, the square root is taken and the result (a double) is cast as an int to be stored in raise. 9. Using the various String methods, manipulate a String called current to be the last character of current followed by the remainder of its characters in order, placing the result in a String called rearranged. ANS:
String rearranged = current.charAt(current.length() - 1) + current.substring(0, current.length() - 2); The last character, which is found at charAt(current.length() - 1) is the first item in rearranged, followed by the substring of current starting at 0 (the first character) and going to current.length() - 2 (the second to last character). 10. How many ways are there to test to see if two String variables, a and b, are equal to each other if we ignore their case (for instance, "aBCd" would be considered equal to "ABcd")? ANS: There are at least 10 ways that this can be done: a.toLowerCase().equals(b.toLowerCase()); b.toLowerCase().equals(a.toLowerCase()); a.toUpperCase().equals(b.toUpperCase()); b.toUpperCase().equals(a.toUpperCase()); a.equalsIgnoreCase(b); b.equalsIgnoreCase(a); a.equalsIgnoreCase(b.toLowerCase()); a.equalsIgnoreCase(b.toUpperCase()); b.equalsIgnoreCase(a.toLowerCase()); b.equalsIgnoreCase(a.toUpperCase()); 11. How do the statements "import java.util.*;" and "import java.util.Random;"
differ from each other? ANS: In the former, all of the classes defined in the java.util library are imported whereas in the latter, only the Random class is imported from the java.util library. The former approach is easier but more time consuming and wasteful of memory, so the latter approach is more appropriate if you only want to use a single class from a given library. 12. Assume that a = "1", b = "2", y = 3, and z = 4. How do the following two statements differ? System.out.println(a + b + y + z); System.out.println(y + z + a + b); ANS: In the first statement, since a and b are Strings, a + b + c + d is treated as String concatenation and the statement outputs 1234. In the second statement, y + z is treated as int addition, which is then cast as a String to be concatenated with y + z, giving 712 instead of 3412 as you might expect. 13. Write a program which will input an int value, x, and compute and output the values of 2^x and x^10 as int values. ANS: import java.util.Scanner; public class Compute14
{ public static void main(String[] args) { Scanner scan = Scanner.create(System.in); System.out.println("Enter an integer value"); int x = scan.nextInt(); int twoToTheX = (int) Math.pow(2, x); int xToThe10th = (int) Math.pow(x, 10); System.out.println("The results are " + twoToTheX + " and " + xToThe10th); } } 14. What is wrong with the following assignment statement? Assume x and y are both String objects. String z = x.equals(y); ANS: The equals method returns a boolean value, not a String. The values true and false are not the same as the values "true" and "false. 15. Write a program that will input some number of cents (less than 100) and output the number of quarters, dimes, nickels and pennies needed to add up to that amount. ANS: import java.util.Scanner; public class Change { public static void main(String[] args) { Scanner scan = Scanner.create(System.in); System.out.println("Enter the amount of change"); int amount = scan.nextInt(); System.out.println("The change for " + amount " cents is: "); int quarters = amount / 25; System.out.println(" " + quarters + " quarters"); amount = amount - quarters * 25; int dimes = amount / 10; System.out.println(" " + dimes + " dimes"); amount = amount - dimes * 10; int nickels = amount / 5; System.out.println(" " + nickels + " nickels"); amount = amount - nickels * 5; int pennies = amount; System.out.println(" " + pennies + " pennies"); } } 16. Write an output statement which will output the following characters exactly as shown: / ' \" / ' \ ANS:
System.out.println("/ \ ' \ \ \" / \ ' \ \ ");
17. Provide three examples of code using assignment statements where one assignment statement would result in a syntax error, one would result in a logical error, and one would result in a run-time error. ANS: Answers will vary. Examples: // syntax error caused by right side providing a double and the left side wants an int: int x = 5.0 / 2.0; // logical error caused by not casting the division as a double: double x = (intValue1 + intValue2) / 2; // run-time error caused by division by 0 when y - y is evaluated: int x = 5 / (y - y); 18. What are the syntax errors from the following program? public class Enigma { public static void main(String[] args) { System.out.println("Input a String"); String x = scan.nextString(); int size = x.length; char last = x.charAt(size); System.out.println("The last character in your string ", x, " is ", last); } } ANS: There are 3 syntax errors. First, the Scanner class has not been imported so that the scan.nextString()will yield a syntax error. Second, the statement x.length requires parentheses as length is a method of the class String, so this is a message passed to x. Finally, the System.out.println statement is not valid because of the use of a comma instead of + to concatenate the various parts of the String. Note that in spite of these syntax errors, there is a run-time error. This error would arise because size will store the length of the String, but the last character will be at location size-1 instead of size. Thus, the statement char last = x.charAt(size); will result in a run-time error because size is beyond the bounds of the String x.
Java Software Solutions, 9e (Lewis/Loftus) Chapter 3 Using Classes and Objects TRUE/FALSE 1. Only difficult programming problems require a pseudocode solution before the programmer creates the program itself. ANS: F Some form of design should be created for all problems before the program is written, with the possible exception of only the most trivial of problems. The form of the design may vary. For instance, programmers in the 1960s and 1970s often used flowcharts instead of pseudocode. 2. You may apply the prefix and postfix increment and decrement operators to instances of the Integer class. ANS: F These operators may only be applied to numeric data. An instance of a class is an object and and not a piece of primitive data. 3. In Java, the symbol "=" and the symbol "==" are used interchangeably. ANS: F "=" is used for assignment statements while "==" is used to test equality in conditional statements. 4. When comparing any primitive type of variable, the == operator should always be used to test if two values are equal. ANS: F This is true of int, short, byte, long, char and boolean, but not of double or float variables. If two double variables, x and y, are being tested, (x == y) is true only if they are exactly equal to the last decimal point. It is common instead to compare these two values but allow for a small difference in value. For instance, if THETA = 0.000001, we might test x and y by (x - y <= THETA) instead of (x == y) to get a better idea of whether they are close enough to be considered equal. 5. These two ways to set up a String will yield identical results: String my_string = "12345"; String my_string = 12345; ANS: F In fact, the second statement won't even compile! The second statement will receive a syntax error about incompatible types. There is no automatic conversion from a number to a String. 6. These two ways to set up a String will yield identical results: String my_string = new String("a bunch of words");
String my_string = "a bunch of words"; ANS: T Java has a very strong notion about what Strings are and how they function. The second declaration is merely shorthand for the first. The string reference will be initialized identically by both declarations. 7. These two ways to set up a String will yield identical results: String my_string = new String("123.45"); String my_string = "" + 123.45; ANS: T Java understands the + operator when used to combine Strings with numbers means that the number should be converted into a numeric String, and then concatenation should occur. 8. These two ways to set up a String will yield identical results: String my_string = new String(12345); String my_string = new String("12345"); ANS: F In fact, the first statement won't even compile! There is no overloaded version of the String constructor that accepts a numeric argument. 9. The following statement will display the value 127. System.out.println("123" + 4); ANS: F "123" is a String. So, the + will cause String concatenation to occur. The int 4 will be converted into the String "4", and the String "1234" will be created and displayed. 10. You may use the String.replace() method to remove characters from a String. ANS: F The replace() method only replaces single characters with other single characters. The replace() method will not add or delete characters to a String; the String length will remain the same. 11. If you need to import not only the top-level of a package, but all its secondary levels as well, you should use the following: import package.*.*; ANS: F The import statement can only be used with a single * (wild card). If you need to import all the secondary levels of a package as well, you must write them out explicitly: import package.A.*; import package.B.*;
12. All the methods in the Math class are declared to be static. ANS: T The Math class methods are designed to be generally useful in arithmetic expressions, so no instances of anything are required to make use of them. This is achieved by ensuring that all the Math methods are static. 13. The printf method within System.out is designed to ease the conversion of legacy C code into Java. ANS: T
C programs use the C printf function for output. Java's printf method is modeled closely after the C printf function, so C output statements can be translated into Java extremely easily. 14. The names of the wrapper classes are just the names of the primitive data types, but with an initial uppercase letter. ANS: F This is true for most of the wrapper classes, but it is false for int (Integer) and char (Character).
MULTIPLE CHOICE 1. In Java a variable may contain a. b. c. d. e.
a value or a reference a package a method a class Any of these
ANS: A Java variables contain values or references to instances of classes (which contain values and/or additional references). 2. If two variables contain aliases of the same object then a. b. c. d. e.
the object may be modified using either alias the object cannot be modified unless there's a single reference to it a third alias is created if/when the object is modified the object will become an "orphan" if both variables are set to null answers A and D are both correct
ANS: E By definition, an alias provides a means by which an object can be modified (an alias is like a pointer). If both variables are set to null, then the object is not referenced by any variable (via any alias) and it does, indeed, become an "orphan" and it will be garbage collected at some point in the future.
3. Which properties are true of String objects? a. b. c. d. e.
Their lengths never change. The shortest String has zero length. Individual characters within a String may be changed using the replace method. The index of the first character in a String is one. Only answers A and B are true.
ANS: E Strings are immutable. That means that once a String object is created it cannot be changed. Therefore the length of a String never changes once it has been created. The shortest length String is "". Since there are no characters between the quotes, the length is zero. The replace method allows you to create a new String from an original one, replacing some of the characters. The index of the first location in a String is zero, not one. Also, the last byte of every String contains the end-of-string character which is a byte of low-values, or binary zeros.
4. What happens if you attempt to use a variable before it has been initialized? a. b. c. d. e.
A syntax error may be generated by the compiler. A run-time error may occur during execution. A "garbage" or "uninitialized" value will be used in the computation. A value of zero is used. Only answers A and B are correct.
ANS: E Many times the compiler is able to detect the attempted use of an uninitialized variable and it will generate a syntax error in this case. If such a use escapes detection by the compiler then a run-time error occurs upon usage. Java is a very "safe" language, so it does not allow "garbage" or zero to be used if an uninitialized variable is used in a computation. 5. What is the function of the dot operator? a. It serves to separate the integer portion from the fractional portion of a floating-point number. b. It allows one to access the data within an object when given a reference to the object. c. It allows one to invoke a method within an object when given a reference to the object. d. It is used to terminate commands, similar to the way a period terminates a sentence in English. e. Both B and C are correct. ANS: E The dot operator is appended directly after the object reference, followed by the data or method to which access is desired. In the case of data, the access may be for reading or writing. In the case of a method, the access is to allow one to invoke the method. The dot within a floating-point number is a decimal point and not a dot operator. 6. In Java, instantiation means a. b. c. d. e.
noticing the first time something is used creating a new object of the class creating a new alias for an existing object launching a method none of these
ANS: B Instantiation is the process of creating a new instance of an object. This usually is accomplished by using the new operator. In the case of Strings, new instances (instantiation) may be created just by using quotes in an expression. For example: String s; s = "A new string (instance)"; 7. Assume you write a program that uses the Random class but you fail to include an import statement for java.util.Random or java.util.*. What will happen when you attempt to compile and run your program? a. b. c. d.
The program won't run but it will compile with a warning about missing the class. The program won't compile and you'll receive a syntax error about the missing class. The program will compile but you'll receive a warning about the missing class. The program will encounter a run-time error when it attempts to access any member of the Random class. e. none of these ANS: B The missing class means that there will be undefined variables and/or methods. The compiler will detect these and will issue error messages. Your program won't be executable. 8. In the StringMutation program shown in Listing 3.1, if phrase is initialized to "Einstein", what will Mutation # 3 yield if mutation1 = phrase.concat(".")? a. b. c. d. e.
Einstein. EINSTEIN. XINSTXIN. einstein. xinstxin.
ANS: C Mutation #2 changes every letter to upper case. Then Mutation #3 replaces Es with Xs. 9. Which of the following will yield a pseudorandom number in the range [-5, +5), given: Random gen = new Random(); a. b. c. d. e.
gen.nextFloat()*5 gen.nextFloat()*10-5 gen.nextFloat()*5-10 gen.nextInt()*10-5 gen.nextInt(10)-5
ANS: B nextFloat yields a pseudorandom number in the range [0, 1); multiplying by 10 yields numbers in the range [0, 10); subtracting 5 yields numbers in the range [-5, 5). 10. What will be displayed by the following command? System.out.println(Math.pow(3, 3-1)); a. 9 b. 8 c. 6
d. 4 e. 27 ANS: A This evaluates to Math.pow(3, 2) which is 3^2 which is 9 11. Given the following two lines of code, what can be said about s1 and s2? String s1 = "testing" + "123"; String s2 = new String("testing 123"); a. b. c. d. e.
s1 and s2 are both references to the same String object. the line declaring s1 is legal in Java; the line declaring s2 will produce a syntax error. s1 and s2 are references to different String objects. s1 and s2 will compare "equal." None of the above
ANS: C Both declarations are legal Java. s1 is a String reference, and it is initialized to the String "testing123". s2 is a String reference, and it is initialized to the String "testing 123". Note the space between the "testing" and the "123". So the two Strings are not equal. 12. An alias is when a. b. c. d. e.
two different reference variables refer to the same physical object two different numeric variables refer to the same physical object two different numeric variables contain identical values two variables have the same name None of these
ANS: A An "alias" occurs when there are two or more references to the same physical object so that by following either reference, one can read/write/modify the object. 13. An API is a. b. c. d. e.
an Abstract Programming Interface an Application Programmer's Interface an Application Programming Interface an Abstract Programmer's Interface an Absolute Programming Interface
ANS: C An API is an Application Programming Interface. This is a collection of related classes that have been built for specific purposes. APIs usually reside in a class library. 14. Java.text's NumberFormat class includes methods that a. b. c. d. e.
allow you to format currency allow you to format percentages round their display during the formatting process truncate their display during the formatting process A, B, C, but not D
ANS: E
NumberFormat always rounds; it never truncates. And it does provide methods for both currency and percentages. 15. The advantages of the DecimalFormat class compared to the NumberFormat class include a. b. c. d. e.
precise control over the number of digits to be displayed control over the presence of a leading zero the ability to truncate values rather than round them the ability to display a percent sign (%) automatically at the beginning of the display only A and B
ANS: E While DecimalFormat does provide far more control than NumberFormat, truncation remains in the hands of the programmer via one or more of the Math methods. The % symbol would appear at the end of the display, not the beginning. 16. The advantage(s) of the Random class's pseudorandom number generators, compared to the Math.random method, is(are) that a. b. c. d. e.
you may create several random number generators the generators in Random are more efficient than the one in Math.random you can generate random ints, floats, and ints within a range you can initialize and reinitialize Random generators all except B are true
ANS: E The efficiency of all the random number generators are the same. The advantages of Random generators over Math.random include all the other properties. 17. The String class's compareTo method a. b. c. d. e.
compares two strings in a case-independent manner yields true or false yields 0 if the two strings are identical rerturns 1 if the first string comes lexically before the second string None of these
ANS: C compareTo yields 0 if the two strings are identical, -1 if the first string comes lexically before the second, +1 if the first string comes lexically after the second. 18. Which statement is true, given the following code fragment? String strA = "aBcDeFg"; String strB = strA.toLowerCase(); strB = strB.toUpperCase(); string strC = strA.toUpperCase(); a. b. c. d. e.
strB.equals(strC) would be true strB.compareTo(strC) would yield 0 strA.equals(strC) would be true strA.compareTo(strC) would yield 0 None of these
ANS: B strB contains the uppercase forms of all the letters in strA; so does strC. So compareTo would yield 0, indicating equality. 19. In addition to providing a mechanism to convert primitive data into objects, what else do the wrapper classes provide? a. b. c. d. e.
enumerations static constants arrays to contain the data exceptions None of these
ANS: B The wrapper classes also provide static constants, like MIN_VALUE and MAX_VALUE (the smallest and largest ints). 20. Which is now the preferred approach for developing Java programs that use graphics and GUIs? a. b. c. d. e.
Swing AWT JavaFX API All of these are preferred approaches
ANS: C The JavaFX API has now replaced the AWT and Swing for developing graphical programs. 21. In a development environment that fully supports JavaFX, which of the following is true? a. The launch method of the scene class is called automatically. b. The launch method of the Application class is called automatically. c. Since the launch method is called automatically, you do not need to write the main method. d. Since the launch method is called automatically, you do not need to call it in the main method. e. Both B and C are true ANS: E 22. Which of the following packages includes classes that represent shapes in JavaFX? a. b. c. d. e.
javafx.scene.shape javafx.shape.scene javafx.shapes javafx.stage.shape javafx.stage.scene
ANS: A 23. Write a declaration for a Rectangle named squareShape that is 400 pixels wide, 400 pixels high, and its upper-left corner position is at point (50, 50). a. Rectangle squareShape = new squareShape(50, 50, 400, 400);
b. c. d. e.
squareShape = new Rectangle(50, 50, 400, 400); Rectangle squareShape = new Rectangle(50, 400, 50, 400); Rectangle squareShape = new Rectangle(50, 50, 400, 400); Rectangle = new squareShape(400, 400, 50, 50);
ANS: D 24. What does the following code fragment do? Circle circle = new Circle(100, 100, 50); circle.setFill(Color.GREEN); Rectangle rectangle = new Rectangle(70, 70, 225, 75); rectangle.setStroke(Color.BLUE); rectangle.setStrokeWidth(2); rectangle.setFill(null); a. It creates a green circle, centered at coordinates (100, 100). b. It creates a rectangle which overlaps the circle since its upper-left corner is at coordinates (70, 70) and its dimensions are 225 X 75. c. Since the rectangle's fill color is set to null, the circle will be visible through the rectangle. d. The rectangle will have a blue border. e. All of these are true. ANS: E Shapes are drawn in the order they are added to a container such as a group or pane. So, to make one shape appear in front of another, it should be added after it. If the fill color of the rectangle is set to null, anything behind it will show through. PROBLEM 1. Rewrite the following five assignment statements into a single statement using prefix and postfix increment and decrement operators as necessary. Assume all variables are int variables. x = y + 1; y = y + 1; z = z - 1; x = x - z; x = x + 1; ANS: x = (y++ + 1) - (--z) + 1; 2. Consider the condition (x == y). How is this handled if x and y are primitive types? How is this handled if x and y are objects? ANS: If x and y are primitive types, then the values stored in them are compared and true is returned if the two values are equal. If they are objects, then the object that each references are compared. If they are the same object, it returns true, otherwise it returns false.
3. Given two String variables, s1 and s2, is it possible for (s1 != s2)to be true while (s1.equals(s2)) is also true? Why or why not? ANS: The condition (s1 != s2) means that s1 and s2 are references to two distinct objects. It says nothing about the contents of the referenced objects. So, the contents of s1 may well be identical or different from the contents of s2. Therefore it is quite possible that (s1.equals(s2)) is true while (s1 != s2) is also true. 4. What is a wrapper class? Why are wrapper classes useful? ANS: A wrapper class is a class that allows you to embed one piece of primitive data within an object. There are methods for extracting the data from the object. Wrapper classes are useful where you have methods (or constructors) that only accept objects and not primitive data. By wrapping the primitive data within an object the functionality of the method (and its class) may be accessed. Problem Ch 03-1 Assume an interactive Java program which asks the user for his/her first name and last name, and outputs the user's initials. 5. Refer to Problem Ch 03-1. For the program to get a name interactively a Scanner object must be instantiated. Write the Java statement to do this. ANS: Scanner scan = new Scanner(System.in); 6. Refer to Problem Ch 03-1. Write a statement using a Scanner method to get the first name interactively. ANS: firstName = scan.nextLine(); 7. Refer to Problem Ch 03-1. Write a method to extract the initial from the first name. ANS: firstInitial = firstName.substring(0,1); 8. Refer to Problem Ch 03-1. Write a statement to guarantee that the initial will be a capital letter. ANS: firstInitial = firstInitial.toUpperCase();
9. What is autoboxing? ANS: Autoboxing provides automatic conversions between primitive values and corresponding wrapper objects. It makes your code shorter by relieving you of the need to provide explicit wrapping of primitive values and explicit extraction of primitive values. 10. Write a statement to create a Color object equivalent to Color.ORANGE using the rgb method. ANS: Color orange = Color.rgb(255, 165, 0); 11. Why is it often a good idea to group particular elements together in a scene? ANS: This makes it much easier to apply transformations such as rotations and position shifts to an entire group at once.
Java Software Solutions, 9e (Lewis/Loftus) Chapter 3 Using Classes and Objects TRUE/FALSE 1. Only difficult programming problems require a pseudocode solution before the programmer creates the program itself. ANS: F Some form of design should be created for all problems before the program is written, with the possible exception of only the most trivial of problems. The form of the design may vary. For instance, programmers in the 1960s and 1970s often used flowcharts instead of pseudocode. 2. You may apply the prefix and postfix increment and decrement operators to instances of the Integer class. ANS: F These operators may only be applied to numeric data. An instance of a class is an object and and not a piece of primitive data. 3. In Java, the symbol "=" and the symbol "==" are used interchangeably. ANS: F "=" is used for assignment statements while "==" is used to test equality in conditional statements. 4. When comparing any primitive type of variable, the == operator should always be used to test if two values are equal. ANS: F This is true of int, short, byte, long, char and boolean, but not of double or float variables. If two double variables, x and y, are being tested, (x == y) is true only if they are exactly equal to the last decimal point. It is common instead to compare these two values but allow for a small difference in value. For instance, if THETA = 0.000001, we might test x and y by (x y <= THETA) instead of (x == y) to get a better idea of whether they are close enough to be considered equal. 5. These two ways to set up a String will yield identical results: String my_string = "12345"; String my_string = 12345; ANS: F In fact, the second statement won't even compile! The second statement will receive a syntax error about incompatible types. There is no automatic conversion from a number to a String. 6. These two ways to set up a String will yield identical results: String my_string = new String("a bunch of words");
String my_string = "a bunch of words"; ANS: T Java has a very strong notion about what Strings are and how they function. The second declaration is merely shorthand for the first. The string reference will be initialized identically by both declarations. 7. These two ways to set up a String will yield identical results: String my_string = new String("123.45"); String my_string = "" + 123.45; ANS: T Java understands the + operator when used to combine Strings with numbers means that the number should be converted into a numeric String, and then concatenation should occur. 8. These two ways to set up a String will yield identical results: String my_string = new String(12345); String my_string = new String("12345"); ANS: F In fact, the first statement won't even compile! There is no overloaded version of the String constructor that accepts a numeric argument. 9. The following statement will display the value 127. System.out.println("123" + 4); ANS: F "123" is a String. So, the + will cause String concatenation to occur. The int 4 will be converted into the String "4", and the String "1234" will be created and displayed. 10. You may use the String.replace() method to remove characters from a String. ANS: F The replace() method only replaces single characters with other single characters. The replace() method will not add or delete characters to a String; the String length will remain the same. 11. If you need to import not only the top-level of a package, but all its secondary levels as well, you should use the following: import package.*.*; ANS: F The import statement can only be used with a single * (wild card). If you need to import all the secondary levels of a package as well, you must write them out explicitly: import package.A.*; import package.B.*;
12. All the methods in the Math class are declared to be static. ANS: T The Math class methods are designed to be generally useful in arithmetic expressions, so no instances of anything are required to make use of them. This is achieved by ensuring that all the Math methods are static. 13. The printf method within System.out is designed to ease the conversion of legacy C code into Java. ANS: T
C programs use the C printf function for output. Java's printf method is modeled closely after the C printf function, so C output statements can be translated into Java extremely easily. 14. The names of the wrapper classes are just the names of the primitive data types, but with an initial uppercase letter. ANS: F This is true for most of the wrapper classes, but it is false for int (Integer) and char (Character).
MULTIPLE CHOICE 1. In Java a variable may contain a. b. c. d. e.
a value or a reference a package a method a class Any of these
ANS: A Java variables contain values or references to instances of classes (which contain values and/or additional references). 2. If two variables contain aliases of the same object then a. b. c. d. e.
the object may be modified using either alias the object cannot be modified unless there's a single reference to it a third alias is created if/when the object is modified the object will become an "orphan" if both variables are set to null answers A and D are both correct
ANS: E By definition, an alias provides a means by which an object can be modified (an alias is like a pointer). If both variables are set to null, then the object is not referenced by any variable (via any alias) and it does, indeed, become an "orphan" and it will be garbage collected at some point in the future.
3. Which properties are true of String objects? a. b. c. d. e.
Their lengths never change. The shortest String has zero length. Individual characters within a String may be changed using the replace method. The index of the first character in a String is one. Only answers A and B are true.
ANS: E Strings are immutable. That means that once a String object is created it cannot be changed. Therefore the length of a String never changes once it has been created. The shortest length String is "". Since there are no characters between the quotes, the length is zero. The replace method allows you to create a new String from an original one, replacing some of the characters. The index of the first location in a String is zero, not one. Also, the last byte of every String contains the end-of-string character which is a byte of low-values, or binary zeros.
4. What happens if you attempt to use a variable before it has been initialized? a. b. c. d. e.
A syntax error may be generated by the compiler. A run-time error may occur during execution. A "garbage" or "uninitialized" value will be used in the computation. A value of zero is used. Only answers A and B are correct.
ANS: E Many times the compiler is able to detect the attempted use of an uninitialized variable and it will generate a syntax error in this case. If such a use escapes detection by the compiler then a run-time error occurs upon usage. Java is a very "safe" language, so it does not allow "garbage" or zero to be used if an uninitialized variable is used in a computation. 5. What is the function of the dot operator? a. It serves to separate the integer portion from the fractional portion of a floating-point number. b. It allows one to access the data within an object when given a reference to the object. c. It allows one to invoke a method within an object when given a reference to the object. d. It is used to terminate commands, similar to the way a period terminates a sentence in English. e. Both B and C are correct. ANS: E The dot operator is appended directly after the object reference, followed by the data or method to which access is desired. In the case of data, the access may be for reading or writing. In the case of a method, the access is to allow one to invoke the method. The dot within a floating-point number is a decimal point and not a dot operator. 6. In Java, instantiation means a. b. c. d. e.
noticing the first time something is used creating a new object of the class creating a new alias for an existing object launching a method none of these
ANS: B Instantiation is the process of creating a new instance of an object. This usually is accomplished by using the new operator. In the case of Strings, new instances (instantiation) may be created just by using quotes in an expression. For example: String s; s = "A new string (instance)"; 7. Assume you write a program that uses the Random class but you fail to include an import statement for java.util.Random or java.util.*. What will happen when you attempt to compile and run your program? a. b. c. d.
The program won't run but it will compile with a warning about missing the class. The program won't compile and you'll receive a syntax error about the missing class. The program will compile but you'll receive a warning about the missing class. The program will encounter a run-time error when it attempts to access any member of the Random class. e. none of these ANS: B The missing class means that there will be undefined variables and/or methods. The compiler will detect these and will issue error messages. Your program won't be executable. 8. In the StringMutation program shown in Listing 3.1, if phrase is initialized to "Einstein", what will Mutation # 3 yield if mutation1 = phrase.concat(".")? a. b. c. d. e.
Einstein. EINSTEIN. XINSTXIN. einstein. xinstxin.
ANS: C Mutation #2 changes every letter to upper case. Then Mutation #3 replaces Es with Xs. 9. Which of the following will yield a pseudorandom number in the range [-5, +5), given: Random gen = new Random(); a. b. c. d. e.
gen.nextFloat()*5 gen.nextFloat()*10-5 gen.nextFloat()*5-10 gen.nextInt()*10-5 gen.nextInt(10)-5
ANS: B nextFloat yields a pseudorandom number in the range [0, 1); multiplying by 10 yields numbers in the range [0, 10); subtracting 5 yields numbers in the range [-5, 5). 10. What will be displayed by the following command? System.out.println(Math.pow(3, 3-1)); a. 9 b. 8 c. 6
d. 4 e. 27 ANS: A This evaluates to Math.pow(3, 2) which is 3^2 which is 9 11. Given the following two lines of code, what can be said about s1 and s2? String s1 = "testing" + "123"; String s2 = new String("testing 123"); a. b. c. d. e.
s1 and s2 are both references to the same String object. the line declaring s1 is legal in Java; the line declaring s2 will produce a syntax error. s1 and s2 are references to different String objects. s1 and s2 will compare "equal." None of the above
ANS: C Both declarations are legal Java. s1 is a String reference, and it is initialized to the String "testing123". s2 is a String reference, and it is initialized to the String "testing 123". Note the space between the "testing" and the "123". So the two Strings are not equal. 12. An alias is when a. b. c. d. e.
two different reference variables refer to the same physical object two different numeric variables refer to the same physical object two different numeric variables contain identical values two variables have the same name None of these
ANS: A An "alias" occurs when there are two or more references to the same physical object so that by following either reference, one can read/write/modify the object. 13. An API is a. b. c. d. e.
an Abstract Programming Interface an Application Programmer's Interface an Application Programming Interface an Abstract Programmer's Interface an Absolute Programming Interface
ANS: C An API is an Application Programming Interface. This is a collection of related classes that have been built for specific purposes. APIs usually reside in a class library. 14. Java.text's NumberFormat class includes methods that a. b. c. d. e.
allow you to format currency allow you to format percentages round their display during the formatting process truncate their display during the formatting process A, B, C, but not D
ANS: E
NumberFormat always rounds; it never truncates. And it does provide methods for both currency and percentages. 15. The advantages of the DecimalFormat class compared to the NumberFormat class include a. b. c. d. e.
precise control over the number of digits to be displayed control over the presence of a leading zero the ability to truncate values rather than round them the ability to display a percent sign (%) automatically at the beginning of the display only A and B
ANS: E While DecimalFormat does provide far more control than NumberFormat, truncation remains in the hands of the programmer via one or more of the Math methods. The % symbol would appear at the end of the display, not the beginning. 16. The advantage(s) of the Random class's pseudorandom number generators, compared to the Math.random method, is(are) that a. b. c. d. e.
you may create several random number generators the generators in Random are more efficient than the one in Math.random you can generate random ints, floats, and ints within a range you can initialize and reinitialize Random generators all except B are true
ANS: E The efficiency of all the random number generators are the same. The advantages of Random generators over Math.random include all the other properties. 17. The String class's compareTo method a. b. c. d. e.
compares two strings in a case-independent manner yields true or false yields 0 if the two strings are identical rerturns 1 if the first string comes lexically before the second string None of these
ANS: C compareTo yields 0 if the two strings are identical, -1 if the first string comes lexically before the second, +1 if the first string comes lexically after the second. 18. Which statement is true, given the following code fragment? String strA = "aBcDeFg"; String strB = strA.toLowerCase(); strB = strB.toUpperCase(); string strC = strA.toUpperCase(); a. b. c. d. e.
strB.equals(strC) would be true strB.compareTo(strC) would yield 0 strA.equals(strC) would be true strA.compareTo(strC) would yield 0 None of these
ANS: B strB contains the uppercase forms of all the letters in strA; so does strC. So compareTo would yield 0, indicating equality. 19. In addition to providing a mechanism to convert primitive data into objects, what else do the wrapper classes provide? a. b. c. d. e.
enumerations static constants arrays to contain the data exceptions None of these
ANS: B The wrapper classes also provide static constants, like MIN_VALUE and MAX_VALUE (the smallest and largest ints). 20. Which is now the preferred approach for developing Java programs that use graphics and GUIs? a. b. c. d. e.
Swing AWT JavaFX API All of these are preferred approaches
ANS: C The JavaFX API has now replaced the AWT and Swing for developing graphical programs. 21. In a development environment that fully supports JavaFX, which of the following is true? a. The launch method of the scene class is called automatically. b. The launch method of the Application class is called automatically. c. Since the launch method is called automatically, you do not need to write the main method. d. Since the launch method is called automatically, you do not need to call it in the main method. e. Both B and C are true ANS: E 22. Which of the following packages includes classes that represent shapes in JavaFX? a. b. c. d. e.
javafx.scene.shape javafx.shape.scene javafx.shapes javafx.stage.shape javafx.stage.scene
ANS: A 23. Write a declaration for a Rectangle named squareShape that is 400 pixels wide, 400 pixels high, and its upper-left corner position is at point (50, 50). a. Rectangle squareShape = new squareShape(50, 50, 400, 400);
b. c. d. e.
squareShape = new Rectangle(50, 50, 400, 400); Rectangle squareShape = new Rectangle(50, 400, 50, 400); Rectangle squareShape = new Rectangle(50, 50, 400, 400); Rectangle = new squareShape(400, 400, 50, 50);
ANS: D 24. What does the following code fragment do? Circle circle = new Circle(100, 100, 50); circle.setFill(Color.GREEN); Rectangle rectangle = new Rectangle(70, 70, 225, 75); rectangle.setStroke(Color.BLUE); rectangle.setStrokeWidth(2); rectangle.setFill(null); a. It creates a green circle, centered at coordinates (100, 100). b. It creates a rectangle which overlaps the circle since its upper-left corner is at coordinates (70, 70) and its dimensions are 225 X 75. c. Since the rectangle's fill color is set to null, the circle will be visible through the rectangle. d. The rectangle will have a blue border. e. All of these are true. ANS: E Shapes are drawn in the order they are added to a container such as a group or pane. So, to make one shape appear in front of another, it should be added after it. If the fill color of the rectangle is set to null, anything behind it will show through. PROBLEM 1. Rewrite the following five assignment statements into a single statement using prefix and postfix increment and decrement operators as necessary. Assume all variables are int variables. x = y + 1; y = y + 1; z = z - 1; x = x - z; x = x + 1; ANS: x = (y++ + 1) - (--z) + 1; 2. Consider the condition (x == y). How is this handled if x and y are primitive types? How is this handled if x and y are objects? ANS: If x and y are primitive types, then the values stored in them are compared and true is returned if the two values are equal. If they are objects, then the object that each references are compared. If they are the same object, it returns true, otherwise it returns false.
3. Given two String variables, s1 and s2, is it possible for (s1 != s2)to be true while (s1.equals(s2)) is also true? Why or why not? ANS: The condition (s1 != s2) means that s1 and s2 are references to two distinct objects. It says nothing about the contents of the referenced objects. So, the contents of s1 may well be identical or different from the contents of s2. Therefore it is quite possible that (s1.equals(s2)) is true while (s1 != s2) is also true. 4. What is a wrapper class? Why are wrapper classes useful? ANS: A wrapper class is a class that allows you to embed one piece of primitive data within an object. There are methods for extracting the data from the object. Wrapper classes are useful where you have methods (or constructors) that only accept objects and not primitive data. By wrapping the primitive data within an object the functionality of the method (and its class) may be accessed. Problem Ch 03-1 Assume an interactive Java program which asks the user for his/her first name and last name, and outputs the user's initials. 5. Refer to Problem Ch 03-1. For the program to get a name interactively a Scanner object must be instantiated. Write the Java statement to do this. ANS: Scanner scan = new Scanner(System.in); 6. Refer to Problem Ch 03-1. Write a statement using a Scanner method to get the first name interactively. ANS: firstName = scan.nextLine(); 7. Refer to Problem Ch 03-1. Write a method to extract the initial from the first name. ANS: firstInitial = firstName.substring(0,1); 8. Refer to Problem Ch 03-1. Write a statement to guarantee that the initial will be a capital letter. ANS: firstInitial = firstInitial.toUpperCase();
9. What is autoboxing? ANS: Autoboxing provides automatic conversions between primitive values and corresponding wrapper objects. It makes your code shorter by relieving you of the need to provide explicit wrapping of primitive values and explicit extraction of primitive values. 10. Write a statement to create a Color object equivalent to Color.ORANGE using the rgb method. ANS: Color orange = Color.rgb(255, 165, 0); 11. Why is it often a good idea to group particular elements together in a scene? ANS: This makes it much easier to apply transformations such as rotations and position shifts to an entire group at once.
Java Software Solutions, 9e (Lewis/Loftus) Chapter 4 Writing Classes TRUE/FALSE 1. Java methods can only return primitive types. ANS: F Java methods can also return objects such as String. 2. Formal parameters are those that appear in the method call and actual parameters are those that appear in the method header. ANS: F The question has the two definitions reversed. Formal parameters are those that appear in the method header, actual parameters are the parameters in the method call (those being passed to the method). 3. All Java classes must contain a main method which is the first method executed when the Java class is called on. ANS: F Only the driver program requires a main method. The driver program is the one that is first executed in any Java program (except for Applets), but it may call upon other classes as needed, and these other classes do not need main methods. 4. Java methods can return more than one item if they are modified with the reserved word continue, as in public continue int foo() {...} ANS: F All Java methods return a single item, whether it is a primitive data type an object, or void. The reserved word continue is used to exit the remainder of a loop and test the condition again. 5. The following method header definition will result in a syntax error: public void aMethod(); ANS: T The reason for the syntax error is because it ends with a ; symbol. It instead needs to be followed by {} with 0 or more instructions inside of the brackets. An abstract method will end with a ; but this header does not define an abstract method. 6. A method defined in a class can access the class's instance data without needing to pass them as parameters or declare them as local variables. ANS: T
The instance data are globally available to all of the class's methods and therefore the methods do not need to receive them as parameters or declare them locally. If variables of the same name as instance data were declared locally inside a method then the instance data would be "hidden" in that method because the references would be to the local variables. 7. The interface of a class is based on those data instances and methods that are declared public. ANS: T The interface is how an outside agent interacts with the object. Interaction is only available through those items declared to be public in the class's definition. 8. Defining formal parameters requires including each parameter's type. ANS: T In order for the compiler to check to see if a method call is correct, the compiler needs to know the types for the parameters being passed. Therefore, all formal parameters (those defined in the method header) must include their type. This is one element that makes Java a strongly typed language. 9. Every class definition must include a constructor. ANS: F Java allows classes to be defined without constructors. However, there is a default constructor that is used in such a case. 10. While multiple objects of the same class can exist, in a given program there can only be one version of each class. ANS: T A class is an abstraction; that is, it exists as a definition, but not as a physical instance. Physical instances are created when an object is instantiated using new. Therefore, there can be many objects of type String, but only one String class. 11. A constructor may contain a return statement so long as no value (or expression) is returned. ANS: T Constructors may contain non-value-returning return statements. Doing so is discouraged, but it is legal. 12. An object should be encapsulated in order to guard its data and methods from inappropriate access. ANS: T Encapsulation is the concept that objects should be protected from accidental (or purposeful) misuse. 13. Accessors and mutators provide mechanisms for controlled access to a well-encapsulated class.
ANS: T Accessors provide read access to variables that otherwise would be inaccessible. Mutators provide write access to otherwise inaccessible variables. 14. A GUI control sets up an event but it is the programmer who writes the code for the event handler which executes when an event occurs. ANS: T 15. Regarding the software failure described at the Denver International Airport in the text, it is critical to factor in errors and inefficiencies that alway occur in a complex system. ANS: T A good system is designed using a well-built systems analysis and design methodology that helps reduce the maintenance portion of the system's lifecycle. 16. Because an Image cannot directly be added to a container, it must be displayed using an ImageView object. ANS: T MULTIPLE CHOICE 1. The behavior of an object is defined by the object's a. b. c. d. e.
instance data constructor visibility modifiers methods All of these
ANS: D The methods dictate how the object reacts when it is passed messages. Each message is implemented as a method, and the method is the code that executes when the message is passed. The constructor is one of these methods but all of the methods combined dictate the behavior. The visibility modifiers do impact the object's performance indirectly. 2. The relationship between a class and an object is best described as a. b. c. d. e.
classes are instances of objects objects are instances of classes objects and classes are the same thing classes are programs while objects are variables objects are the instance data of classes
ANS: B Classes are definitions of program entities that represent classes of things/entities in the world. Class definitions include instance data and methods. To use a class, it is instantiated. These instances are known as objects. So, objects are instances of classes. Program code directly interacts with objects, not classes.
3. To define a class that will represent a car, which of the following definition is most appropriate? a. b. c. d. e.
private class car public class car public class Car public class CAR. private class Car
ANS: C Classes should be defined to be public so that they can be accessed by other classes. And following Java naming convention, class names should start with a capital letter and be lower case except for the beginning of each new word, so Car is more appropriate than car or CAR.
4. In order to preserve encapsulation of an object, we would do all of the following except for which one? a. b. c. d. e.
make the instance data private define the methods in the class to access and manipulate the instance data make the methods of the class public make the class final all of these preserve encapsulation
ANS: D Encapsulation means that the class contains both the data and the methods needed to manipulate the data. In order to preserve encapsulation properly, the instance data should not be directly accessible from outside of the classes, so the instance data are made private and methods are defined to access and manipulate the instance data. Further, the methods to access and manipulate the instance data are made public so that other classes can use the object. The reserved word final is used to control inheritance and has nothing to do with encapsulation. 5. If a method does not have a return statement, then a. b. c. d. e.
it will produce a syntax error when compiled it must be a void method it cannot be called from outside the class that defined the method it must be defined to be a public method it must be an int, double, float, or String method
ANS: B All methods are implied to return something and therefore there must be a return statement. However, if the programmer wishes to write a method that does not return anything, and therefore does not need a return statement, then it must be a void method (a method whose header has void as its return type).
6. Which of the following reserved words in Java is used to create an instance of a class? a. b. c. d. e.
class public public or private (can use either) import new
ANS: E
7. Consider a sequence of method invocations as follows: main calls m1, m1 calls m2, m2 calls m3, and then m2 calls m4, m3 calls m5. If m4 has just terminated, what method will resume execution? a. b. c. d. e.
m1 m2 m3 m5 main
ANS: B Once a method terminates, control resumes with the method that called that method. In this case, m2 calls m4 so that when m4 terminates, m2 is resumed. 8. A variable whose scope is restricted to the method where it was declared is known as a(n) a. b. c. d. e.
parameter global variable local variable public instance data private instance data
ANS: C Local variables are those that are "local" to the method in which they have been declared; that is, they are accessible only inside that method. Global variables are those that are accessible from anywhere, while parameters are the variables passed into a method. Instance data can be thought of as global variables for an entire object. 9. A class's constructor usually defines a. b. c. d. e.
how an object is initialized how an object is interfaced the number of instance data in the class the number of methods in the class if the instance data are accessible outside of the object directly
ANS: A The constructor should be used to "construct" the object, that is, to set up the initial values of the instance data. This is not essential, but is typically done. The interface of an object is dictated by the visibility modifiers used on the instance data and methods. 10. Having multiple class methods of the same name where each method has a different number of or type of parameters is known as a. b. c. d. e.
encapsulation information hiding tokenizing importing method overloading
ANS: E When methods share the same name, they are said to be overloaded. The number and type of parameters passed in the message provides the information by which the proper method is called. 11. Instance data for a Java class
a. b. c. d. e.
are limited to primitive types are limited to Strings are limited to objects (e.g., Strings, classes defined by other programmers) may be primitive types or objects but objects must be defined to be private may be primitive types or objects
ANS: E The instance data are the entities that make up the class and may be any type available whether primitive or object, and may be public or private. By using objects as instance data, it permits the class to be built upon other classes. This relationship where a class has instance data that are other classes is known as a has-a relationship. 12. An example of passing a message to a String where the message has a String parameter would occur in which of the following messages? a. b. c. d. e.
length substring equals toUpperCase None of these; it is not possible to pass a String as a parameter to a String
ANS: C The length and toUpperCase messages do not have parameters and substring has two int parameters. For equals, a String must be passed as a parameter so that the String receiving the message can be compared to the String passed as a parameter. 13. Consider a Rational class designed to represent rational numbers as a pair of ints, along with methods reduce (to reduce the rational to simplest form), gcd (to find the greatest common divisor of two ints), as well as methods for addition, subtraction, multiplication, and division. Why should the reduce and gcd methods be declared to be private? a. b. c. d. e.
because they will never be used because they will only be called from methods inside Rational because they will only be called from the constructor of Rational because they do not use any of the Rational instance data This is incorrect; they should be declared as public
ANS: B All items of a class that are declared to be private are only accessible to entities within that class, whether they are instance data or methods. In this case, since these two methods are only called from other methods (including the constructor) of Rational, they are declared private to promote information hiding to a greater degree. Note that answer C is not a correct answer because the reduce method calls the gcd method, so one of the methods is called from a method other than the constructor. 14. Given the method defined here, which of the following method calls is legal? public void foo(int a, int b) a. foo(0, 0.1); b. foo(0/1, 2*3); c. foo(0);
d. foo(); e. foo(1+2, 3*0.1); ANS: B The only legal method call is one that passes twoint parameters. In the case of answer B, 0 / 1 is an int division (equal to 0) and 2 * 3 is an int multiplication. So this is legal. The answers for A and E contain two parameters, but the second of each is a double. The answers for C and D have the wrong number of parameters. 15. Given the method defined here, which of the following method calls is legal? public void doublefoo(double x) a. b. c. d. e.
doublefoo(0); doublefoo(0.555); doublefoo(0.1 + 0.2); foo(0.1, 0.2); all except D are legal
ANS: E In the case of A, the value 0 (an int) is widened to a double. In the case of C, the addition is performed yielding 0.3 and then doublefoo is called. The parameter list in D is illegal since it contains two double parameters instead of 1. 16. In a UML diagram for a class a. b. c. d. e.
classes are represented as rectangles there may be a section containing the name of the class there may be a section containing the attributes of the class there may be a section containing the methods of the class All of these
ANS: E Those four attributes correctly describe a UML representation of a class. 17. The expressions that are passed to a method in an invocation are called a. b. c. d. e.
actual parameters formal parameters formal arguments formals Any of these
ANS: A The formals (formal parameters, formal arguments) are those given in a method's header, where it is declared. The actual parameters (actuals, actual arguments) are the expressions that actually are transmitted to a method in an invocation. 18. What happens if you declare a class constructor to have a void return type? a. b. c. d.
You will most likely receive a syntax error. The program will compile with a warning but you'll get a run-time error. There is nothing wrong with declaring a constructor with a void return type. The class's default constructor will be used instead of the one you're declaring.
e. None of these ANS: A It is a syntax violation to declare a constructor with any type, even void, so you'll receive a syntax error. 19. Which of the following is not a kind of object that is used to create a graphical user interface in JavaFX? a. b. c. d. e.
control event image event handler All of these are objects used to create a GUI in JavaFX
ANS: A An image is not a kind of object used to create a GUI even though it is an object. It can only be displayed with an ImageView JavaFX node. 20. The software failure at the Denver International Airport's baggage handling system is a good example of a. how a large system can be obsolete by the time it is developed b. how designers sometimes have too much faith in the technology they are using c. how failures are often a result of multiple variables caused by a system as a whole in actual operation d. how the use of a centralized computer is unrealistic in today's distributed processing e. All of these ANS: E All of these are good examples of why software fails. 21. Visibility modifiers include a. b. c. d. e.
public, private public, private, protected public, private, protected, final public, protected, final, static public, private, protected, static
ANS: B public, private, protected control the visibility of variables and methods. final controls whether a variable, method, or class can be further changed or overridden; it does not control visibility. static controls whether a variable or method is associated with instances of a class or the class itself. Class Definition Ch 04-1 import java.text.DecimalFormat; public class Student { private String name; private String major; private double gpa;
private int hours; public Student(String newName, String newMajor, double newGPA, int newHours) { name = newName; major = newMajor; gpa = newGPA; hours = newHours; } public String toString() { // xxxx needs to be replaced DecimalFormat df = new DecimalFormat("xxxx"); return name + "\n" + major + "\n" + df.format(gpa) + "\n" + hours } } 22. Refer to Class Definition Ch 04-1: Which of the following patterns should be used in place of "xxxx" when instantiating df so that the gpa to be output is in typical form (like 3.810)? a. b. c. d. e.
"#.###" "#.0" "0.#" "0.000" "0.0##"
ANS: D GPA is traditionally output as a 4 digit value with the decimal point after the first digit. Digits are output no matter if they are 0 or otherwise. So, to get 3.810, with the trailing 0, or to get 0.813 with the leading 0, the format must be "0.000" rather than "#.###". 23. Refer to Class Definition Ch 04-1: Which of the following could be used to instantiate a new Student s1? a. Student s1 = new Student(); b. s1 = new Student(); c. Student s1 = new Student("Jane Doe", "Computer Science", 3.333, 33); d. new Student s1 = ("Jane Doe", "Computer Science", 3.333, 33); e. new Student(s1); ANS: C To instantiate a class, the object is assigned the value returned by calling the constructor preceded by the reserved word new, as in new Student(). The constructor might require parameters, and for Student, the parameters must be two String values, a double, followed by an int. 24. Refer to Class Definition Ch 04-1: Assume that another method has been defined that will compute and return the student's class rank (Freshman, Sophomore, etc). It is defined as: public String getClassRank()
Given that s1 is a student, which of the following would properly be used to get s1's class rank? a. b. c. d. e.
s1 = getClassRank(); s1.toString(); s1.getHours(); s1.getClassRank(); getClassRank(sq);
ANS: D To call a method of an object requires passing that object a message which is the same as the method name, as in object.methodname(parameters). In this situation, the object is s1, the method is getClassRank, and this method expects no parameters. Answers A and E are syntactically illegal while answer B returns information about the Student but not his/her class rank, and there is no getHours method so C is also syntactically illegal. 25. Refer to Class Definition Ch 04-1: Another method that might be desired is one that updates the student's number of credit hours. This method will receive a number of credit hours and add these to the student's current hours. Which of the following methods would accomplish this? a. public int updateHours() { return hours; } b. public void updateHours() { hours++; } c. public updateHours(int moreHours) { hours += moreHours; } d. public void updateHours(int moreHours) { hours += moreHours; } e. getClassRank(sq);public int updateHours(int moreHours) { return hours + moreHours; } ANS: D This method will receive the number of new hours and add this to the current hours. The method in D is the only one to do this appropriately. Answer C is syntactically invalid since it does not list a return type. The answer in E returns the new hours, but does not reset hours appropriately.
PROBLEM 1. Assume method0 calls method1 and method2, method1 calls method3 which calls method4 and method5. Explain the chain of method calls (what order methods are called and from which method). ANS: method0 calls method1 which calls method3 which calls method4, method4 terminates and method3 calls method5, method5 terminates, method3 terminates, method1 terminates, method0 calls method2, method2 terminates, method0 terminates.
2. When reasoning about a car, we use such information as its make and model, year, color, cost (or worth), number of miles, gas mileage, insurance cost, and so forth. Consider a program that will attempt to determine how practical a car might be on a road trip. Which of these types of information might you use in your program as instance data? Provide a justification for your selection. ANS: Because a road trip will include such factors as comfort and cost, we need to have instance data pertaining to the size of the vehicle, its gas mileage and its reliability. Size can be determined by make and model, reliability based on year and number of miles that the car has accrued, and cost based on gas mileage. The following would be a reasonable selection of instance data: model (maybe make as well), year, number of miles, gas mileage. 3. Write a portion of a class named Employee. An employee will have a name, ID number, position, and hourly wage. Define the instance data for this class. ANS: private String name, idnum, position; private double hourlyWages; 4. Explain why it would be a poor decision to make instance data public instead of private. Give an example of why this could result in a problem. ANS: If the instance data are public, then any other class can directly modify any of the instance data, and therefore the values would not be stored as intended. Class Definition Ch04-2 The following is from a class named BaseballPlayer. It contains the following data instances: private String name; private String position; private int numAtBats; private int numSingles; private int numDoubles; private int numTriples; private int numHomeRuns; private double battingAverage; 5. Refer to Class Definition Ch 04-2: Write the constructor which is passed the player's name and position. ANS: Notice that we not only initialize the instance data that were passed as parameters, but also all other data instances. public BaseballPlayer(String newName, String newPosition) { name = newName; position = newPosition;
numAtBats = 0; numSingles = 0; numDoubles = 0; numTriples = 0; numHomeRuns = 0; battingAverage = 0.0; } 6. Refer to Class Definition Ch 04-2: Write a toString method that returns the player's name, position, and batting average. formatted to have one digit to the left of the decimal and three digits to the right of the decimal. Assume DecimalFormat has been imported. ANS: public String toString() { DecimalFormat df = new DecimalFormat("0.000"); return name + "\t" + position + "\t" + df.format(battingAverage); } Class Definition Ch 04-3 Consider a class called Building. This class consists of a number of floors (numberOfFloors) for the building, a current floor for the elevator (current), a requested floor of a person waiting for the elevator (requestedFloor), and methods for constructing the building object, for moving the elevator one floor up, for moving the elevator one floor down, for requesting the elevator and for starting the elevator going. Assume that requestedFloor will be set to 0 if there are currently no requests being made (or the last request has already been fulfilled). 7. Refer to Class Definition Ch 04-3: Write the constructor for this class. ANS: public Building(int numFloors) { numberOfFloors = numFloors; current = 1; requestedFloor = 0; } 8. Refer to Class Definition Ch 04-3: What visibility modifiers would you use for the methods that move the elevator up one floor, move the elevator down one floor, that request the elevator, and that start the elevator moving? ANS: The request for the elevator will be performed from an outside object, so it should be public. It will set requestedFloor to a value, and then start the elevator going up or down. Moving the elevator up or down will be called from the method that starts the elevator. So, starting the elevator, moving the elevator up a floor, and moving the elevator down a floor should all be private as they will only be called from inside the class. Class Definition Ch 04-4
public class Box { double length; double width; double height; Box(double l, double w, double h) { length = l; width = w; height = h; }// Box( ) double volume() { return length * width * height; }// end volume() }// end class Box 9. Refer to Class Definition Ch 04-4: Write the statement to instantiate an Box object, blueBox, with a length of 6, width of 4, and height of 2. ANS: Box blueBox = new Box(6,4,2); 10. Refer to Class Definition Ch 04-4: Write a statement to output the volume of the blue box. ANS: System.out.println("Volume of the blue box is
"+blueBox.volume());
11. Refer to Class Definition Ch 04-4: Add a constructor to class Box for a cube which has only 1 parameter, side. ANS: Box(double s) { length = s; width = s; height = s; }// Box( ) 12. Refer to Class Definition Ch 04-4: Write a statement to instantiate a cube with a length of 3, width of 3, and height of 3. ANS: Box cube = new Box(3);
Java Software Solutions, 9e (Lewis/Loftus) Chapter 4 Writing Classes TRUE/FALSE 1. Java methods can only return primitive types. ANS: F Java methods can also return objects such as String. 2. Formal parameters are those that appear in the method call and actual parameters are those that appear in the method header. ANS: F The question has the two definitions reversed. Formal parameters are those that appear in the method header, actual parameters are the parameters in the method call (those being passed to the method). 3. All Java classes must contain a main method which is the first method executed when the Java class is called on. ANS: F Only the driver program requires a main method. The driver program is the one that is first executed in any Java program (except for Applets), but it may call upon other classes as needed, and these other classes do not need main methods. 4. Java methods can return more than one item if they are modified with the reserved word continue, as in public continue int foo() {...} ANS: F All Java methods return a single item, whether it is a primitive data type an object, or void. The reserved word continue is used to exit the remainder of a loop and test the condition again. 5. The following method header definition will result in a syntax error: public void aMethod(); ANS: T The reason for the syntax error is because it ends with a ; symbol. It instead needs to be followed by {} with 0 or more instructions inside of the brackets. An abstract method will end with a ; but this header does not define an abstract method. 6. A method defined in a class can access the class's instance data without needing to pass them as parameters or declare them as local variables. ANS: T
The instance data are globally available to all of the class's methods and therefore the methods do not need to receive them as parameters or declare them locally. If variables of the same name as instance data were declared locally inside a method then the instance data would be "hidden" in that method because the references would be to the local variables. 7. The interface of a class is based on those data instances and methods that are declared public. ANS: T The interface is how an outside agent interacts with the object. Interaction is only available through those items declared to be public in the class's definition. 8. Defining formal parameters requires including each parameter's type. ANS: T In order for the compiler to check to see if a method call is correct, the compiler needs to know the types for the parameters being passed. Therefore, all formal parameters (those defined in the method header) must include their type. This is one element that makes Java a strongly typed language. 9. Every class definition must include a constructor. ANS: F Java allows classes to be defined without constructors. However, there is a default constructor that is used in such a case. 10. While multiple objects of the same class can exist, in a given program there can only be one version of each class. ANS: T A class is an abstraction; that is, it exists as a definition, but not as a physical instance. Physical instances are created when an object is instantiated using new. Therefore, there can be many objects of type String, but only one String class. 11. A constructor may contain a return statement so long as no value (or expression) is returned. ANS: T Constructors may contain non-value-returning return statements. Doing so is discouraged, but it is legal. 12. An object should be encapsulated in order to guard its data and methods from inappropriate access. ANS: T Encapsulation is the concept that objects should be protected from accidental (or purposeful) misuse. 13. Accessors and mutators provide mechanisms for controlled access to a well-encapsulated class.
ANS: T Accessors provide read access to variables that otherwise would be inaccessible. Mutators provide write access to otherwise inaccessible variables. 14. A GUI control sets up an event but it is the programmer who writes the code for the event handler which executes when an event occurs. ANS: T 15. Regarding the software failure described at the Denver International Airport in the text, it is critical to factor in errors and inefficiencies that alway occur in a complex system. ANS: T A good system is designed using a well-built systems analysis and design methodology that helps reduce the maintenance portion of the system's lifecycle. 16. Because an Image cannot directly be added to a container, it must be displayed using an ImageView object. ANS: T MULTIPLE CHOICE 1. The behavior of an object is defined by the object's a. b. c. d. e.
instance data constructor visibility modifiers methods All of these
ANS: D The methods dictate how the object reacts when it is passed messages. Each message is implemented as a method, and the method is the code that executes when the message is passed. The constructor is one of these methods but all of the methods combined dictate the behavior. The visibility modifiers do impact the object's performance indirectly. 2. The relationship between a class and an object is best described as a. b. c. d. e.
classes are instances of objects objects are instances of classes objects and classes are the same thing classes are programs while objects are variables objects are the instance data of classes
ANS: B Classes are definitions of program entities that represent classes of things/entities in the world. Class definitions include instance data and methods. To use a class, it is instantiated. These instances are known as objects. So, objects are instances of classes. Program code directly interacts with objects, not classes.
3. To define a class that will represent a car, which of the following definition is most appropriate? a. b. c. d. e.
private class car public class car public class Car public class CAR. private class Car
ANS: C Classes should be defined to be public so that they can be accessed by other classes. And following Java naming convention, class names should start with a capital letter and be lower case except for the beginning of each new word, so Car is more appropriate than car or CAR.
4. In order to preserve encapsulation of an object, we would do all of the following except for which one? a. b. c. d. e.
make the instance data private define the methods in the class to access and manipulate the instance data make the methods of the class public make the class final all of these preserve encapsulation
ANS: D Encapsulation means that the class contains both the data and the methods needed to manipulate the data. In order to preserve encapsulation properly, the instance data should not be directly accessible from outside of the classes, so the instance data are made private and methods are defined to access and manipulate the instance data. Further, the methods to access and manipulate the instance data are made public so that other classes can use the object. The reserved word final is used to control inheritance and has nothing to do with encapsulation. 5. If a method does not have a return statement, then a. b. c. d. e.
it will produce a syntax error when compiled it must be a void method it cannot be called from outside the class that defined the method it must be defined to be a public method it must be an int, double, float, or String method
ANS: B All methods are implied to return something and therefore there must be a return statement. However, if the programmer wishes to write a method that does not return anything, and therefore does not need a return statement, then it must be a void method (a method whose header has void as its return type).
6. Which of the following reserved words in Java is used to create an instance of a class? a. b. c. d. e.
class public public or private (can use either) import new
ANS: E
7. Consider a sequence of method invocations as follows: main calls m1, m1 calls m2, m2 calls m3, and then m2 calls m4, m3 calls m5. If m4 has just terminated, what method will resume execution? a. b. c. d. e.
m1 m2 m3 m5 main
ANS: B Once a method terminates, control resumes with the method that called that method. In this case, m2 calls m4 so that when m4 terminates, m2 is resumed. 8. A variable whose scope is restricted to the method where it was declared is known as a(n) a. b. c. d. e.
parameter global variable local variable public instance data private instance data
ANS: C Local variables are those that are "local" to the method in which they have been declared; that is, they are accessible only inside that method. Global variables are those that are accessible from anywhere, while parameters are the variables passed into a method. Instance data can be thought of as global variables for an entire object. 9. A class's constructor usually defines a. b. c. d. e.
how an object is initialized how an object is interfaced the number of instance data in the class the number of methods in the class if the instance data are accessible outside of the object directly
ANS: A The constructor should be used to "construct" the object, that is, to set up the initial values of the instance data. This is not essential, but is typically done. The interface of an object is dictated by the visibility modifiers used on the instance data and methods. 10. Having multiple class methods of the same name where each method has a different number of or type of parameters is known as a. b. c. d. e.
encapsulation information hiding tokenizing importing method overloading
ANS: E When methods share the same name, they are said to be overloaded. The number and type of parameters passed in the message provides the information by which the proper method is called. 11. Instance data for a Java class
a. b. c. d. e.
are limited to primitive types are limited to Strings are limited to objects (e.g., Strings, classes defined by other programmers) may be primitive types or objects but objects must be defined to be private may be primitive types or objects
ANS: E The instance data are the entities that make up the class and may be any type available whether primitive or object, and may be public or private. By using objects as instance data, it permits the class to be built upon other classes. This relationship where a class has instance data that are other classes is known as a has-a relationship. 12. An example of passing a message to a String where the message has a String parameter would occur in which of the following messages? a. b. c. d. e.
length substring equals toUpperCase None of these; it is not possible to pass a String as a parameter to a String
ANS: C The length and toUpperCase messages do not have parameters and substring has two int parameters. For equals, a String must be passed as a parameter so that the String receiving the message can be compared to the String passed as a parameter. 13. Consider a Rational class designed to represent rational numbers as a pair of ints, along with methods reduce (to reduce the rational to simplest form), gcd (to find the greatest common divisor of two ints), as well as methods for addition, subtraction, multiplication, and division. Why should the reduce and gcd methods be declared to be private? a. b. c. d. e.
because they will never be used because they will only be called from methods inside Rational because they will only be called from the constructor of Rational because they do not use any of the Rational instance data This is incorrect; they should be declared as public
ANS: B All items of a class that are declared to be private are only accessible to entities within that class, whether they are instance data or methods. In this case, since these two methods are only called from other methods (including the constructor) of Rational, they are declared private to promote information hiding to a greater degree. Note that answer C is not a correct answer because the reduce method calls the gcd method, so one of the methods is called from a method other than the constructor. 14. Given the method defined here, which of the following method calls is legal? public void foo(int a, int b) a. foo(0, 0.1); b. foo(0/1, 2*3); c. foo(0);
d. foo(); e. foo(1+2, 3*0.1); ANS: B The only legal method call is one that passes twoint parameters. In the case of answer B, 0 / 1 is an int division (equal to 0) and 2 * 3 is an int multiplication. So this is legal. The answers for A and E contain two parameters, but the second of each is a double. The answers for C and D have the wrong number of parameters. 15. Given the method defined here, which of the following method calls is legal? public void doublefoo(double x) a. b. c. d. e.
doublefoo(0); doublefoo(0.555); doublefoo(0.1 + 0.2); foo(0.1, 0.2); all except D are legal
ANS: E In the case of A, the value 0 (an int) is widened to a double. In the case of C, the addition is performed yielding 0.3 and then doublefoo is called. The parameter list in D is illegal since it contains two double parameters instead of 1. 16. In a UML diagram for a class a. b. c. d. e.
classes are represented as rectangles there may be a section containing the name of the class there may be a section containing the attributes of the class there may be a section containing the methods of the class All of these
ANS: E Those four attributes correctly describe a UML representation of a class. 17. The expressions that are passed to a method in an invocation are called a. b. c. d. e.
actual parameters formal parameters formal arguments formals Any of these
ANS: A The formals (formal parameters, formal arguments) are those given in a method's header, where it is declared. The actual parameters (actuals, actual arguments) are the expressions that actually are transmitted to a method in an invocation. 18. What happens if you declare a class constructor to have a void return type? a. b. c. d.
You will most likely receive a syntax error. The program will compile with a warning but you'll get a run-time error. There is nothing wrong with declaring a constructor with a void return type. The class's default constructor will be used instead of the one you're declaring.
e. None of these ANS: A It is a syntax violation to declare a constructor with any type, even void, so you'll receive a syntax error. 19. Which of the following is not a kind of object that is used to create a graphical user interface in JavaFX? a. b. c. d. e.
control event image event handler All of these are objects used to create a GUI in JavaFX
ANS: A An image is not a kind of object used to create a GUI even though it is an object. It can only be displayed with an ImageView JavaFX node. 20. The software failure at the Denver International Airport's baggage handling system is a good example of a. how a large system can be obsolete by the time it is developed b. how designers sometimes have too much faith in the technology they are using c. how failures are often a result of multiple variables caused by a system as a whole in actual operation d. how the use of a centralized computer is unrealistic in today's distributed processing e. All of these ANS: E All of these are good examples of why software fails. 21. Visibility modifiers include a. b. c. d. e.
public, private public, private, protected public, private, protected, final public, protected, final, static public, private, protected, static
ANS: B public, private, protected control the visibility of variables and methods. final controls whether a variable, method, or class can be further changed or overridden; it does not control visibility. static controls whether a variable or method is associated with instances of a class or the class itself. Class Definition Ch 04-1 import java.text.DecimalFormat; public class Student { private String name; private String major; private double gpa;
private int hours; public Student(String newName, String newMajor, double newGPA, int newHours) { name = newName; major = newMajor; gpa = newGPA; hours = newHours; } public String toString() { // xxxx needs to be replaced DecimalFormat df = new DecimalFormat("xxxx"); return name + "\n" + major + "\n" + df.format(gpa) + "\n" + hours } } 22. Refer to Class Definition Ch 04-1: Which of the following patterns should be used in place of "xxxx" when instantiating df so that the gpa to be output is in typical form (like 3.810)? a. b. c. d. e.
"#.###" "#.0" "0.#" "0.000" "0.0##"
ANS: D GPA is traditionally output as a 4 digit value with the decimal point after the first digit. Digits are output no matter if they are 0 or otherwise. So, to get 3.810, with the trailing 0, or to get 0.813 with the leading 0, the format must be "0.000" rather than "#.###". 23. Refer to Class Definition Ch 04-1: Which of the following could be used to instantiate a new Student s1? a. Student s1 = new Student(); b. s1 = new Student(); c. Student s1 = new Student("Jane Doe", "Computer Science", 3.333, 33); d. new Student s1 = ("Jane Doe", "Computer Science", 3.333, 33); e. new Student(s1); ANS: C To instantiate a class, the object is assigned the value returned by calling the constructor preceded by the reserved word new, as in new Student(). The constructor might require parameters, and for Student, the parameters must be two String values, a double, followed by an int. 24. Refer to Class Definition Ch 04-1: Assume that another method has been defined that will compute and return the student's class rank (Freshman, Sophomore, etc). It is defined as: public String getClassRank() Given that s1 is a student, which of the following would properly be used to get s1's class rank?
a. b. c. d. e.
s1 = getClassRank(); s1.toString(); s1.getHours(); s1.getClassRank(); getClassRank(sq);
ANS: D To call a method of an object requires passing that object a message which is the same as the method name, as in object.methodname(parameters). In this situation, the object is s1, the method is getClassRank, and this method expects no parameters. Answers A and E are syntactically illegal while answer B returns information about the Student but not his/her class rank, and there is no getHours method so C is also syntactically illegal. 25. Refer to Class Definition Ch 04-1: Another method that might be desired is one that updates the student's number of credit hours. This method will receive a number of credit hours and add these to the student's current hours. Which of the following methods would accomplish this? a. public int updateHours() { return hours; } b. public void updateHours() { hours++; } c. public updateHours(int moreHours) { hours += moreHours; } d. public void updateHours(int moreHours) { hours += moreHours; } e. getClassRank(sq);public int updateHours(int moreHours) { return hours + moreHours; } ANS: D This method will receive the number of new hours and add this to the current hours. The method in D is the only one to do this appropriately. Answer C is syntactically invalid since it does not list a return type. The answer in E returns the new hours, but does not reset hours appropriately.
PROBLEM 1. Assume method0 calls method1 and method2, method1 calls method3 which calls method4 and method5. Explain the chain of method calls (what order methods are called and from which method). ANS: method0 calls method1 which calls method3 which calls method4, method4 terminates and method3 calls method5, method5 terminates, method3 terminates, method1 terminates, method0 calls method2, method2 terminates, method0 terminates. 2. When reasoning about a car, we use such information as its make and model, year, color, cost (or worth), number of miles, gas mileage, insurance cost, and so forth. Consider a program that will attempt to determine how practical a car might be on a road trip. Which of these types of information might you use in your program as instance data? Provide a justification for your selection.
ANS: Because a road trip will include such factors as comfort and cost, we need to have instance data pertaining to the size of the vehicle, its gas mileage and its reliability. Size can be determined by make and model, reliability based on year and number of miles that the car has accrued, and cost based on gas mileage. The following would be a reasonable selection of instance data: model (maybe make as well), year, number of miles, gas mileage. 3. Write a portion of a class named Employee. An employee will have a name, ID number, position, and hourly wage. Define the instance data for this class. ANS: private String name, idnum, position; private double hourlyWages; 4. Explain why it would be a poor decision to make instance data public instead of private. Give an example of why this could result in a problem. ANS: If the instance data are public, then any other class can directly modify any of the instance data, and therefore the values would not be stored as intended. Class Definition Ch04-2 The following is from a class named BaseballPlayer. It contains the following data instances: private String name; private String position; private int numAtBats; private int numSingles; private int numDoubles; private int numTriples; private int numHomeRuns; private double battingAverage; 5. Refer to Class Definition Ch 04-2: Write the constructor which is passed the player's name and position. ANS: Notice that we not only initialize the instance data that were passed as parameters, but also all other data instances. public BaseballPlayer(String newName, String newPosition) { name = newName; position = newPosition; numAtBats = 0; numSingles = 0; numDoubles = 0; numTriples = 0;
numHomeRuns = 0; battingAverage = 0.0; } 6. Refer to Class Definition Ch 04-2: Write a toString method that returns the player's name, position, and batting average. formatted to have one digit to the left of the decimal and three digits to the right of the decimal. Assume DecimalFormat has been imported. ANS: public String toString() { DecimalFormat df = new DecimalFormat("0.000"); return name + "\t" + position + "\t" + df.format(battingAverage); } Class Definition Ch 04-3 Consider a class called Building. This class consists of a number of floors (numberOfFloors) for the building, a current floor for the elevator (current), a requested floor of a person waiting for the elevator (requestedFloor), and methods for constructing the building object, for moving the elevator one floor up, for moving the elevator one floor down, for requesting the elevator and for starting the elevator going. Assume that requestedFloor will be set to 0 if there are currently no requests being made (or the last request has already been fulfilled). 7. Refer to Class Definition Ch 04-3: Write the constructor for this class. ANS: public Building(int numFloors) { numberOfFloors = numFloors; current = 1; requestedFloor = 0; } 8. Refer to Class Definition Ch 04-3: What visibility modifiers would you use for the methods that move the elevator up one floor, move the elevator down one floor, that request the elevator, and that start the elevator moving? ANS: The request for the elevator will be performed from an outside object, so it should be public. It will set requestedFloor to a value, and then start the elevator going up or down. Moving the elevator up or down will be called from the method that starts the elevator. So, starting the elevator, moving the elevator up a floor, and moving the elevator down a floor should all be private as they will only be called from inside the class. Class Definition Ch 04-4 public class Box { double length; double width;
double height; Box(double l, double w, double h) { length = l; width = w; height = h; }// Box( ) double volume() { return length * width * height; }// end volume() }// end class Box 9. Refer to Class Definition Ch 04-4: Write the statement to instantiate an Box object, blueBox, with a length of 6, width of 4, and height of 2. ANS: Box blueBox = new Box(6,4,2); 10. Refer to Class Definition Ch 04-4: Write a statement to output the volume of the blue box. ANS: System.out.println("Volume of the blue box is
"+blueBox.volume());
11. Refer to Class Definition Ch 04-4: Add a constructor to class Box for a cube which has only 1 parameter, side. ANS: Box(double s) { length = s; width = s; height = s; }// Box( ) 12. Refer to Class Definition Ch 04-4: Write a statement to instantiate a cube with a length of 3, width of 3, and height of 3. ANS: Box cube = new Box(3);
Java Software Solutions, 9e (Lewis/Loftus) Chapter 5 Conditionals and Loops TRUE/FALSE 1. As in the other members of the C family of languages (C, C++, C#), Java interprets a zero value as false and a non-zero value as true. ANS: F Although the C family does, indeed, interpret zero and non-zero values in this manner, Java requires that the reserved constants true and false be used or that there be a logical evaluation using the relational and/or logical operators. 2. In Java, selection statements consist only of if and if-else statements. ANS: F This list omits switch statements. 3. In Java, the symbol "=" and the symbol "==" are used synonymously (interchangeably). ANS: F "=" is used for assignment statements while "==" is used to test equality. 4. The statement {} is a legal block. ANS: T A block consists of {, followed by zero or more Java statements, followed by }. So it is acceptable to have no statements between the brackets. Situations where this is necessary occur in Java, particularly when implementing methods of abstract classes, something you will study later. 5. The statement: if (a >= b) a++; else b--; will do the same thing as the statement: if (a < b) b--; else a++;. ANS: T We can reverse the if clause and else clause if we reverse the condition. The opposite condition of (a >= b) is (a < b) so this works out logically. Note that if we used the condition (a <= b) then the resulting statement would not do the same thing as the original if a >= b. 6. An if statement may or may not have an else clause, but an else clause must be part of an if statement.
ANS: T Java allows for either if or if-else statements. But else is only used as part of an if statement. 7. In order to compare int, float and double variables, you can use <, >, ==, !=, <=, >=, but to compare char and String variables, you must use compareTo(), equals()and equalsIgnoreCase(). ANS: F You can also directly compare char variables using <, >, ==, !=, <=, >=, but you must use compareTo(), equals() and equalsIgnoreCase() for any String comparisons. 8. Assume that boolean done = false, int x = 10, int y = 11, String s = "Help" and String t = "Goodbye". Then the expression (!done && x <= y) is true. ANS: T Since done is false, !done is true. Since 10 < 11, x <= y is true. Therefore, the entire expression is true. 9. Assume that boolean done = false, int x = 10, int y = 11, String s = "Help" and String t = "Goodbye". Then the expression (s.concat(t).length() < y) is true. ANS: F Concatenating s and t gives a String that is 11 characters long and 11 < 11 is false. 10. Assume that boolean done = false, int x = 10, int y = 11, String s = "Help" and String t = "Goodbye". Then the expression (done || s.compareTo(t) < 0) is true. ANS: F Both done is false and s.compareTo(t) < 0 is false since s does not come before t alphabetically, so the entire expression is false. 11. If you create an ArrayList without specifying the type of element, the ArrayList will store Object references which means you can put any type of object in the list. ANS: T 12. Regarding the Software Failure: The operators were warned that, although the Therac-25 had many safety precautions, it might be possible to accidentally overdose a patient. ANS: F Operators were told that there were so many safety precautions that it would be "virtually impossible" to overdose a patient.
MULTIPLE CHOICE 1. The idea that program instructions execute in order (linearly) unless otherwise specified through a conditional statement is known as a. b. c. d. e.
boolean execution conditional statements try and catch sequentiality flow of control
ANS: E The "flow of control" describes the order of execution of instructions. It defaults to being linear (or sequential) but is altered by using control statements like conditionals and loops. 2. Of the following if statements, which one correctly executes three instructions if the condition is true? a. if (x < 0) a = b * 2; y = x; z = a - y; b. { if (x < 0) a = b * 2; y = x; z = a - y; } c. if { (x < 0) a = b * 2; y = x; z = a - y ; } d. if (x < 0) { a = b * 2; y = x; z = a - y; } e. B, C, and D are all correct but not A ANS: D In order to have three instructions execute in the if clause when the condition is true, the three statements must be placed in a block following the condition. This is the syntax used in D. In A, there is no block. In B, the block is placed around the entire if statement such that the if clause is only a = b * 2; and the other two statements are not part of the if statement, but follow it. The syntax in C is illegal resulting in a syntax error. Don't forget that the structure of your code (how it lines up) is immaterial to the compiler.
3. Which of the sets of statements below will add 1 to x if x is positive and subtract 1 from x if x is negative but leave x alone if x is 0? a. if (x > 0) x++; else x--; b. if (x > 0) x++; else if (x < 0) x--; c. if (x > 0) x++; if (x < 0) x--; else x = 0; d. if (x == 0) x = 0; else x++; x--; e. x++; x--; ANS: B In B, if x is positive, x++ is performed, else if x is negative x-- is performed and otherwise, nothing happens, or x is unaffected. In A, C, D and E, the logic is incorrect. In A, x-- is done if x is not positive, thus if x is 0, x becomes -1 which is the wrong answer. In C, if x is positive, then x++ is performed. In either case, the next statement is executed and if x is not negative, the else clause is performed setting x to 0. So if x is positive, it becomes 0 after this set of code. In D, x++ and x-are both performed if x is not 0. And in E, this code does not attempt to determine if x is positive or negative, it just adds one and then subtracts one from x, leaving x where it started. 4. Consider the following code that will assign a letter grade of 'A', 'B', 'C', 'D', or 'F' depending on a student's test score. if (score >= 90) grade = 'A'; if (score >= 80) grade = 'B'; if (score >= 70) grade = 'C'; if (score >= 60) grade = 'D'; else grade = 'F'; a. b. c. d. e.
This code will work correctly in all cases. This code will work correctly only if the grade is greater than or equal to 60. This code will work correctly only if the grade is less than 60. This code will work correctly only if the grade is less than 70. This code will not work correctly under any circumstances.
ANS: D The problem with this code is that it consists of three if statements followed by one if-else statement, rather than a nested if-else statement. So the logic is improper. If the student's grade falls into the 'A' category, then all 4 conditions are true and the student winds up with a 'D'. If the student's grade falls into the 'B' category, then the first condition is false, but the next three are true and the student winds up with a 'D'. If the student's grade falls into the 'D' category, then the only condition that is true is the one that tests for 'D' and so the grade is assigned correctly. If the student's grade falls into the 'F' category, then none of the conditions are true and an 'F' is assigned correctly. So, only if the grade is less than 70 does the code work correctly.
5. Assume that count is 0, total is 20 and max is 1. The following statement will do which of the following? if (count != 0 && total / count > max) max = total / count; a. b. c. d.
The condition short circuits and the assignment statement is not executed. The condition short circuits and the assignment statement is executed without problem. The condition does not short circuit causing a division by zero error. The condition short circuits so that there is no division by zero error when evaluating the condition, but the assignment statement causes a division by zero error. e. The condition will not compile because it uses improper syntax. ANS: A Since count is 0, (count != 0) is false. Because the left-hand side of an && condition is false, the condition is short circuited, and so the right-hand side is not evaluated. Thus, a potential division by zero error is avoided. Because the condition is false, the statement max = total / count is not executed, again avoiding a potential division by zero error. 6. What is wrong, logically, with the following code? if (x > 10) System.out.println("Large"); else if (x > 6 && x <= 10) System.out.println("Medium"); else if (x > 3 && x <= 6) System.out.println("Small"); else System.out.println("Very small"); a. There is no logical error, but there is no need to have x <= 10 in the second conditional or x <= 6 in the third conditional. b. There is no logical error, but there is no need to have x > 6 in the second conditional or x > 3 in the third conditional. c. The logical error is that no matter what value x is, Very small is always printed out. d. The logical error is that no matter what value x is, Large is always printed out. e. There is nothing wrong with the logic at all. ANS: A Because this is a nested if-else statement, if (x>10)is true, then the first println statement is executed and the rest of the statement is skipped. If (x>10)is not true, then the first else clause is executed and the next if condition is tested. At this point, (x>10)is known to be false and therefore (x<=10)must be true, so there is no need to check this inequality. Similarly, if (x>6)is false, then the second else clause is executed and the third if condition is tested. However, (x<=6)must be true, so there is no need to check this inequality. 7. Consider the following outline of a nested if-else structure which has more if clauses than else clauses. Which of the statements below is true regarding this structure? if (condition1) if (condition2) statement1; else statement2;
a. Syntactically it is invalid to have more if clauses than else clauses b. statement2 will only execute if condition1 is false and condition2 is false c. statement2 will only execute if condition1 is true and condition2 is false d. statement2 will only execute if condition1 is false, it does not matter what condition2 is e. statement2 will never execute ANS: C The else clause must be matched to the most recent if statement. Therefore, the else goes with the if statement that tests condition2, not the if statement that tests condition1. So, if condition1 is true and condition2 is false, then statement2 will execute. 8. Assume that x and y are int variables with x = 5, y = 3, and a and d are char variables with a = 'a' and d = 'A', and examine the following conditions: Condition 1: Condition 2: Condition 3: Condition 4: a. b. c. d. e.
(x < y && x > 0) (a != d || x != 5) !(true && false) (x > y || a == 'A' || d != 'A')
all 4 conditions are true Only Condition 2 is true Condition 2 and Condition 4 are true only Conditions 2, 3,4 are all true, Conditions 1 is not all 4 conditions are false
ANS: D Condition 1 is not true because x < y is false, making the entire condition false. Since a != d is true, Condition 2 is true even though x != 5 is false. Condition 3 is true because (true && false) is false, but !false is true. Condition 4 is true because x > y is true, making the entire condition true. Therefore, Conditions 2, 3,4 are true while Condition 1 is false. 9. What does the break statement do? a. b. c. d. e.
ends a program transfers control out of the current control structure such as a loop or switch statement ends the current line of output, returning the cursor denotes the end of a switch statement indicated the end of a line when using System.out.print
ANS: B This is the exit statement that allows the programmer to exit a control structure from inside of that control structure. 10. If a break occurs within the innermost loop of a nested loop that is three levels deep a. just the innermost loop will be "broken" b. all loops are "broken" and execution continues from after the end of the loop c. all but the outermost loops are "broken" and execution continues from the next iteration of the outermost loop d. a syntax error is generated unless there are break or continue statements at each loop level
e. None of these are true ANS: A The innermost loop is broken, and execution continues from just after the end of that loop. 11. Which of the following are true about check boxes? a. b. c. d. e.
They may be checked or unchecked. You can allow more than one check box to be checked by the user at a given time. Check boxes are Java components. You can control whether they will be visible or not. All of these are true about check boxes
ANS: E 12. Every iterator a. b. c. d. e.
has a hasNext() method has a hasFirst()method has a hasNextInt()method has a isEmpty()method None of these
ANS: A Every iterator has a hasNext() method that is true if there are iteration elements that have yet to be processed. Every iterator also has a next() method that delivers the next element for processing. 13. If x is an int where x = 1, what will x be after the following loop terminates? while (x < 100) x *= 2; a. b. c. d. e.
2 64 100 128 None of these; this is an infinite loop
ANS: D With x = 1, the loop condition is true and the statement executes, doubling x, which is now 2. Since the loop condition is still true, the statement executes again, doubling x to 4. The condition remains true for the next 4 iterations, where x becomes 8, 16, 32 and 64. Since x < 100 is still true when x = 64, the loop iterates again and x becomes 2*64 = 128. Now, x < 100 is no longer true and the loop terminates with x = 128. 14. If x is an int where x = 0, what will x be after the following loop terminates? while (x < 100) x *= 2; a. b. c. d. e.
2 64 100 128 None of these; this is an infinite loop
ANS: E Since x starts at 0, x *= 2; results in 0 * 2, or x = 0. Since x remains 0, x <100 remains true, and the loop repeats. x continues to be 0 and so the condition never changes to false, and thus the loop never terminates. 15. How many times will the following loop iterate? int x = 10; while (x > 0) { System.out.println(x); x--; } a. b. c. d. e.
0 once 9 times 10 times 11 times
ANS: D Since the condition is tested before the loop body executes, the loop will not execute once x == 0. So, the loop iterates for x = 10, x = 9, ..., x = 1, or 10 times. 16. Which type of GUI control would be best to use if you wanted the user to select one date from a list of three possible dates to take an exam? a. b. c. d. e.
check boxes because they are used for mutually exclusive options radio buttons because they are used for mutually exclusive options either check boxes or radio buttons because either are used for mutually exclusive options neither check boxes nor radio buttons can be used for mutually exclusive options There is no way to force a user to select only one option from a list; this must be done with a text input box.
ANS: B Code Segment Ch 05-1 if (a > 0) if (b < 0) x = x + 5; else if (a > 5) x = x + 4; else x = x + 3; else x = x + 2; 17. Refer to Code Segment Ch 05-1. If x is currently 0, a = 5 and b = 5, what will x become after the statement shown is executed? a. 0 b. 2 c. 3
d. 4 e. 5 ANS: C Since a > 0 is true, the next condition is checked. Since b < 0 is false, the else clause for this condition is executed. Since a > 5 is false the else clause for this condition is executed, which is x = x + 3. Therefore, 3 is added to x, so it is now 3. 18. Refer to Code Segment Ch 05-1. If x is currently 0, a = 0 and b = -5, what will x become after the statement shown is executed? a. b. c. d. e.
0 2 3 4 5
ANS: B Since a > 0 is not true, the else clause for this condition is executed which is x = x + 2 x is now 2. 19. Refer to Code Segment Ch 05-1. If x is currently 0, a = 1 and b = -1, what will x become after the statement shown is executed? a. b. c. d. e.
0 2 3 4 5
ANS: E Since a > 0 is true, the if clause for this condition is executed which is another if statement. Its condition, b < 0 is true so its if clause is executed which is x = x + 5, so now x is 5.
20. As introduced in the Software Failure, the terminology "risk analysis" means a. how willing you are to risk the loss of several key programmers working on your project b. how much you are willing to risk that a particular piece of software you are developing still contains an error or errors c. how willing you are to risk that your software will fail once implemented d. how willing you are to risk that the machines on which your software will run will not work e. None of these ANS: B The terminology "risk analysis" pertains explicitly to the risks a developer is willing to take that a piece of software developed will still contain errors at the time of implementation. PROBLEM 1. Rewrite the following set of if statements using a nested if-else structure.
if (score >= 90) grade = 'A'; if (score >= 80 && score < 90) grade = 'B'; if (score >= 70 && score < 80) grade = 'C'; if (score >= 60 && score < 70) grade = 'D'; if (score < 60) grade = 'F'; ANS: if (score >= 90) grade = 'A'; else if (score >= 80) grade = 'B'; else if (score >= 70) grade = 'C'; else if (score >= 60) grade = 'D'; else grade = 'F'; 2. A truth table shows, for the various true or false values of boolean variables, what the result of a boolean condition is. Fill in the following truth table. Assume that a, b and c are boolean variables. a false false false false true true true true
b false false true true false false true true
c false true false true false true false true
a && (!b
|| c)
b false false true true false false true true
c false true false true false true false true
a && (!b false false false false true true false true
|| c)
ANS: a false false false false true true true true
3. A truth table shows, for the various true or false values of boolean variables, what the result of a boolean condition is. Fill in the following truth table. Assume that a, b and c are boolean variables. a false false false false true true true true ANS:
b false false true true false false true true
c false true false true false true false true
!(a && b) ||
!(a && c)
a false false false false true true true true
b false false true true false false true true
c false true false true false true false true
!(a && b) ||
!(a && c)
true true true true true true true false
4. Explain what is meant by short circuiting and provide an example of short circuiting a condition with && and provide an example of short circuiting a condition with ||. ANS: Short circuiting is when a boolean expression does not have to be completely evaluated because the final answer is determined with just a partial evaluation. This can occur in an expression with && if one part of the expression evaluates to false, and in an expression with || if one part of the expression evaluates to true. Examples: 1. (x != 0) && (sum / x > 100) can be short circuited if x != 0 is false, preventing a division by zero error. 2. (a.equals("yes") || a.equals("no")) can be short circuited if a is equal to "yes" so that the computer does not waste time in testing a.equals("no"). 5. The following code has a syntax error immediately before the word else. What is the error and why does it arise? Fix the code so that this statement is a legal if-else statement. if (x < 0); x++; else x--; ANS: The error is "else without if" and it arises because of the ; after the condition but before x++. The Java compiler determines that the if clause is in fact ; (no statement) and that x++; is a statement that follows the if statement. Therefore, since x++; is not part of the if statement, the else is felt to be an else without an if, and that is why the error arises. The statement should be: if (x < 0) x++; else x--; 6. String s1 is said to overlap String s2 if all of the characters in s1 also appear in s2. Write a set of code that will set the boolean variable overlap to true if s1 overlaps s2 and false otherwise. Assume both s1 and s2 have already been input. ANS: boolean overlap = true; int j = 0; while (overlap && j < s1.length()) { boolean found = false; int k = 0; while (!found && k < s2.length()) if (s2.charAt(k) == s1.charAt(j))
found = true; else k++; if (!found) overlap = false; j++; }
Java Software Solutions, 9e (Lewis/Loftus) Chapter 5 Conditionals and Loops TRUE/FALSE 1. As in the other members of the C family of languages (C, C++, C#), Java interprets a zero value as false and a non-zero value as true. ANS: F Although the C family does, indeed, interpret zero and non-zero values in this manner, Java requires that the reserved constants true and false be used or that there be a logical evaluation using the relational and/or logical operators. 2. In Java, selection statements consist only of if and if-else statements. ANS: F This list omits switch statements. 3. In Java, the symbol "=" and the symbol "==" are used synonymously (interchangeably). ANS: F "=" is used for assignment statements while "==" is used to test equality. 4. The statement {} is a legal block. ANS: T A block consists of {, followed by zero or more Java statements, followed by }. So it is acceptable to have no statements between the brackets. Situations where this is necessary occur in Java, particularly when implementing methods of abstract classes, something you will study later. 5. The statement: if (a >= b) a++; else b--; will do the same thing as the statement: if (a < b) b--; else a++;. ANS: T We can reverse the if clause and else clause if we reverse the condition. The opposite condition of (a >= b) is (a < b) so this works out logically. Note that if we used the condition (a <= b) then the resulting statement would not do the same thing as the original if a >= b. 6. An if statement may or may not have an else clause, but an else clause must be part of an if statement.
ANS: T Java allows for either if or if-else statements. But else is only used as part of an if statement. 7. In order to compare int, float and double variables, you can use <, >, ==, !=, <=, >=, but to compare char and String variables, you must use compareTo(), equals()and equalsIgnoreCase(). ANS: F You can also directly compare char variables using <, >, ==, !=, <=, >=, but you must use compareTo(), equals() and equalsIgnoreCase() for any String comparisons. 8. Assume that boolean done = false, int x = 10, int y = 11, String s = "Help" and String t = "Goodbye". Then the expression (!done && x <= y) is true. ANS: T Since done is false, !done is true. Since 10 < 11, x <= y is true. Therefore, the entire expression is true. 9. Assume that boolean done = false, int x = 10, int y = 11, String s = "Help" and String t = "Goodbye". Then the expression (s.concat(t).length() < y) is true. ANS: F Concatenating s and t gives a String that is 11 characters long and 11 < 11 is false. 10. Assume that boolean done = false, int x = 10, int y = 11, String s = "Help" and String t = "Goodbye". Then the expression (done || s.compareTo(t) < 0) is true. ANS: F Both done is false and s.compareTo(t) < 0 is false since s does not come before t alphabetically, so the entire expression is false. 11. If you create an ArrayList without specifying the type of element, the ArrayList will store Object references which means you can put any type of object in the list. ANS: T 12. Regarding the Software Failure: The operators were warned that, although the Therac-25 had many safety precautions, it might be possible to accidentally overdose a patient. ANS: F Operators were told that there were so many safety precautions that it would be "virtually impossible" to overdose a patient.
MULTIPLE CHOICE 1. The idea that program instructions execute in order (linearly) unless otherwise specified through a conditional statement is known as a. b. c. d. e.
boolean execution conditional statements try and catch sequentiality flow of control
ANS: E The "flow of control" describes the order of execution of instructions. It defaults to being linear (or sequential) but is altered by using control statements like conditionals and loops. 2. Of the following if statements, which one correctly executes three instructions if the condition is true? a. if (x < 0) a = b * 2; y = x; z = a - y; b. { if (x < 0) a = b * 2; y = x; z = a - y; } c. if { (x < 0) a = b * 2; y = x; z = a - y ; } d. if (x < 0) { a = b * 2; y = x; z = a - y; } e. B, C, and D are all correct but not A ANS: D In order to have three instructions execute in the if clause when the condition is true, the three statements must be placed in a block following the condition. This is the syntax used in D. In A, there is no block. In B, the block is placed around the entire if statement such that the if clause is only a = b * 2; and the other two statements are not part of the if statement, but follow it. The syntax in C is illegal resulting in a syntax error. Don't forget that the structure of your code (how it lines up) is immaterial to the compiler. 3. Which of the sets of statements below will add 1 to x if x is positive and subtract 1 from x if x is negative but leave x alone if x is 0?
a. if (x > 0) x++; else x--; b. if (x > 0) x++; else if (x < 0) x--; c. if (x > 0) x++; if (x < 0) x--; else x = 0; d. if (x == 0) x = 0; else x++; x--; e. x++; x--; ANS: B In B, if x is positive, x++ is performed, else if x is negative x-- is performed and otherwise, nothing happens, or x is unaffected. In A, C, D and E, the logic is incorrect. In A, x-- is done if x is not positive, thus if x is 0, x becomes -1 which is the wrong answer. In C, if x is positive, then x++ is performed. In either case, the next statement is executed and if x is not negative, the else clause is performed setting x to 0. So if x is positive, it becomes 0 after this set of code. In D, x++ and x-are both performed if x is not 0. And in E, this code does not attempt to determine if x is positive or negative, it just adds one and then subtracts one from x, leaving x where it started. 4. Consider the following code that will assign a letter grade of 'A', 'B', 'C', 'D', or 'F' depending on a student's test score. if (score >= 90) grade = 'A'; if (score >= 80) grade = 'B'; if (score >= 70) grade = 'C'; if (score >= 60) grade = 'D'; else grade = 'F'; a. b. c. d. e.
This code will work correctly in all cases. This code will work correctly only if the grade is greater than or equal to 60. This code will work correctly only if the grade is less than 60. This code will work correctly only if the grade is less than 70. This code will not work correctly under any circumstances.
ANS: D The problem with this code is that it consists of three if statements followed by one if-else statement, rather than a nested if-else statement. So the logic is improper. If the student's grade falls into the 'A' category, then all 4 conditions are true and the student winds up with a 'D'. If the student's grade falls into the 'B' category, then the first condition is false, but the next three are true and the student winds up with a 'D'. If the student's grade falls into the 'D' category, then the only condition that is true is the one that tests for 'D' and so the grade is assigned correctly. If the student's grade falls into the 'F' category, then none of the conditions are true and an 'F' is assigned correctly. So, only if the grade is less than 70 does the code work correctly. 5. Assume that count is 0, total is 20 and max is 1. The following statement will do which of the following? if (count != 0 && total / count > max)
max = total / count; a. b. c. d.
The condition short circuits and the assignment statement is not executed. The condition short circuits and the assignment statement is executed without problem. The condition does not short circuit causing a division by zero error. The condition short circuits so that there is no division by zero error when evaluating the condition, but the assignment statement causes a division by zero error. e. The condition will not compile because it uses improper syntax. ANS: A Since count is 0, (count != 0) is false. Because the left-hand side of an && condition is false, the condition is short circuited, and so the right-hand side is not evaluated. Thus, a potential division by zero error is avoided. Because the condition is false, the statement max = total / count is not executed, again avoiding a potential division by zero error. 6. What is wrong, logically, with the following code? if (x > 10) System.out.println("Large"); else if (x > 6 && x <= 10) System.out.println("Medium"); else if (x > 3 && x <= 6) System.out.println("Small"); else System.out.println("Very small"); a. There is no logical error, but there is no need to have x <= 10 in the second conditional or x <= 6 in the third conditional. b. There is no logical error, but there is no need to have x > 6 in the second conditional or x > 3 in the third conditional. c. The logical error is that no matter what value x is, Very small is always printed out. d. The logical error is that no matter what value x is, Large is always printed out. e. There is nothing wrong with the logic at all. ANS: A Because this is a nested if-else statement, if (x>10)is true, then the first println statement is executed and the rest of the statement is skipped. If (x>10)is not true, then the first else clause is executed and the next if condition is tested. At this point, (x>10)is known to be false and therefore (x<=10)must be true, so there is no need to check this inequality. Similarly, if (x>6)is false, then the second else clause is executed and the third if condition is tested. However, (x<=6)must be true, so there is no need to check this inequality. 7. Consider the following outline of a nested if-else structure which has more if clauses than else clauses. Which of the statements below is true regarding this structure? if (condition1) if (condition2) statement1; else statement2; a. Syntactically it is invalid to have more if clauses than else clauses b. statement2 will only execute if condition1 is false and condition2 is false
c. statement2 will only execute if condition1 is true and condition2 is false d. statement2 will only execute if condition1 is false, it does not matter what condition2 is e. statement2 will never execute ANS: C The else clause must be matched to the most recent if statement. Therefore, the else goes with the if statement that tests condition2, not the if statement that tests condition1. So, if condition1 is true and condition2 is false, then statement2 will execute. 8. Assume that x and y are int variables with x = 5, y = 3, and a and d are char variables with a = 'a' and d = 'A', and examine the following conditions: Condition 1: Condition 2: Condition 3: Condition 4: a. b. c. d. e.
(x < y && x > 0) (a != d || x != 5) !(true && false) (x > y || a == 'A' || d != 'A')
all 4 conditions are true Only Condition 2 is true Condition 2 and Condition 4 are true only Conditions 2, 3,4 are all true, Conditions 1 is not all 4 conditions are false
ANS: D Condition 1 is not true because x < y is false, making the entire condition false. Since a != d is true, Condition 2 is true even though x != 5 is false. Condition 3 is true because (true && false) is false, but !false is true. Condition 4 is true because x > y is true, making the entire condition true. Therefore, Conditions 2, 3,4 are true while Condition 1 is false. 9. What does the break statement do? a. b. c. d. e.
ends a program transfers control out of the current control structure such as a loop or switch statement ends the current line of output, returning the cursor denotes the end of a switch statement indicated the end of a line when using System.out.print
ANS: B This is the exit statement that allows the programmer to exit a control structure from inside of that control structure. 10. If a break occurs within the innermost loop of a nested loop that is three levels deep a. just the innermost loop will be "broken" b. all loops are "broken" and execution continues from after the end of the loop c. all but the outermost loops are "broken" and execution continues from the next iteration of the outermost loop d. a syntax error is generated unless there are break or continue statements at each loop level e. None of these are true ANS: A The innermost loop is broken, and execution continues from just after the end of that loop.
11. Which of the following are true about check boxes? a. b. c. d. e.
They may be checked or unchecked. You can allow more than one check box to be checked by the user at a given time. Check boxes are Java components. You can control whether they will be visible or not. All of these are true about check boxes
ANS: E 12. Every iterator a. b. c. d. e.
has a hasNext() method has a hasFirst()method has a hasNextInt()method has a isEmpty()method None of these
ANS: A Every iterator has a hasNext() method that is true if there are iteration elements that have yet to be processed. Every iterator also has a next() method that delivers the next element for processing. 13. If x is an int where x = 1, what will x be after the following loop terminates? while (x < 100) x *= 2; a. b. c. d. e.
2 64 100 128 None of these; this is an infinite loop
ANS: D With x = 1, the loop condition is true and the statement executes, doubling x, which is now 2. Since the loop condition is still true, the statement executes again, doubling x to 4. The condition remains true for the next 4 iterations, where x becomes 8, 16, 32 and 64. Since x < 100 is still true when x = 64, the loop iterates again and x becomes 2*64 = 128. Now, x < 100 is no longer true and the loop terminates with x = 128. 14. If x is an int where x = 0, what will x be after the following loop terminates? while (x < 100) x *= 2; a. b. c. d. e.
2 64 100 128 None of these; this is an infinite loop
ANS: E Since x starts at 0, x *= 2; results in 0 * 2, or x = 0. Since x remains 0, x <100 remains true, and the loop repeats. x continues to be 0 and so the condition never changes to false, and thus the loop never terminates.
15. How many times will the following loop iterate? int x = 10; while (x > 0) { System.out.println(x); x--; } a. b. c. d. e.
0 once 9 times 10 times 11 times
ANS: D Since the condition is tested before the loop body executes, the loop will not execute once x == 0. So, the loop iterates for x = 10, x = 9, ..., x = 1, or 10 times. 16. Which type of GUI control would be best to use if you wanted the user to select one date from a list of three possible dates to take an exam? a. b. c. d. e.
check boxes because they are used for mutually exclusive options radio buttons because they are used for mutually exclusive options either check boxes or radio buttons because either are used for mutually exclusive options neither check boxes nor radio buttons can be used for mutually exclusive options There is no way to force a user to select only one option from a list; this must be done with a text input box.
ANS: B Code Segment Ch 05-1 if (a > 0) if (b < 0) x = x + 5; else if (a > 5) x = x + 4; else x = x + 3; else x = x + 2; 17. Refer to Code Segment Ch 05-1. If x is currently 0, a = 5 and b = 5, what will x become after the statement shown is executed? a. b. c. d. e.
0 2 3 4 5
ANS: C
Since a > 0 is true, the next condition is checked. Since b < 0 is false, the else clause for this condition is executed. Since a > 5 is false the else clause for this condition is executed, which is x = x + 3. Therefore, 3 is added to x, so it is now 3. 18. Refer to Code Segment Ch 05-1. If x is currently 0, a = 0 and b = -5, what will x become after the statement shown is executed? a. b. c. d. e.
0 2 3 4 5
ANS: B Since a > 0 is not true, the else clause for this condition is executed which is x = x + 2 x is now 2. 19. Refer to Code Segment Ch 05-1. If x is currently 0, a = 1 and b = -1, what will x become after the statement shown is executed? a. b. c. d. e.
0 2 3 4 5
ANS: E Since a > 0 is true, the if clause for this condition is executed which is another if statement. Its condition, b < 0 is true so its if clause is executed which is x = x + 5, so now x is 5.
20. As introduced in the Software Failure, the terminology "risk analysis" means a. how willing you are to risk the loss of several key programmers working on your project b. how much you are willing to risk that a particular piece of software you are developing still contains an error or errors c. how willing you are to risk that your software will fail once implemented d. how willing you are to risk that the machines on which your software will run will not work e. None of these ANS: B The terminology "risk analysis" pertains explicitly to the risks a developer is willing to take that a piece of software developed will still contain errors at the time of implementation. PROBLEM 1. Rewrite the following set of if statements using a nested if-else structure. if (score >= 90) grade = 'A'; if (score >= 80 && score < 90) grade = 'B'; if (score >= 70 && score < 80) grade = 'C'; if (score >= 60 && score < 70) grade = 'D';
if (score < 60) grade = 'F'; ANS: if (score >= 90) grade = 'A'; else if (score >= 80) grade = 'B'; else if (score >= 70) grade = 'C'; else if (score >= 60) grade = 'D'; else grade = 'F'; 2. A truth table shows, for the various true or false values of boolean variables, what the result of a boolean condition is. Fill in the following truth table. Assume that a, b and c are boolean variables. a false false false false true true true true
b false false true true false false true true
c false true false true false true false true
a && (!b
|| c)
b false false true true false false true true
c false true false true false true false true
a && (!b false false false false true true false true
|| c)
ANS: a false false false false true true true true
3. A truth table shows, for the various true or false values of boolean variables, what the result of a boolean condition is. Fill in the following truth table. Assume that a, b and c are boolean variables. a false false false false true true true true
b false false true true false false true true
c false true false true false true false true
!(a && b) ||
!(a && c)
b false false true
c false true false
!(a && b) ||
!(a && c)
ANS: a false false false
true true true
false true true true true
true false false true true
true false true false true
true true true true false
4. Explain what is meant by short circuiting and provide an example of short circuiting a condition with && and provide an example of short circuiting a condition with ||. ANS: Short circuiting is when a boolean expression does not have to be completely evaluated because the final answer is determined with just a partial evaluation. This can occur in an expression with && if one part of the expression evaluates to false, and in an expression with || if one part of the expression evaluates to true. Examples: 1. (x != 0) && (sum / x > 100) can be short circuited if x != 0 is false, preventing a division by zero error. 2. (a.equals("yes") || a.equals("no")) can be short circuited if a is equal to "yes" so that the computer does not waste time in testing a.equals("no"). 5. The following code has a syntax error immediately before the word else. What is the error and why does it arise? Fix the code so that this statement is a legal if-else statement. if (x < 0); x++; else x--; ANS: The error is "else without if" and it arises because of the ; after the condition but before x++. The Java compiler determines that the if clause is in fact ; (no statement) and that x++; is a statement that follows the if statement. Therefore, since x++; is not part of the if statement, the else is felt to be an else without an if, and that is why the error arises. The statement should be: if (x < 0) x++; else x--; 6. String s1 is said to overlap String s2 if all of the characters in s1 also appear in s2. Write a set of code that will set the boolean variable overlap to true if s1 overlaps s2 and false otherwise. Assume both s1 and s2 have already been input. ANS: boolean overlap = true; int j = 0; while (overlap && j < s1.length()) { boolean found = false; int k = 0; while (!found && k < s2.length()) if (s2.charAt(k) == s1.charAt(j)) found = true; else k++; if (!found) overlap = false; j++;
}
Java Software Solutions, 9e (Lewis/Loftus) Chapter 6 More Conditionals and Loops TRUE/FALSE 1. A switch statement must have a default clause. ANS: F The default clause is optional. 2. Each switch statement must terminate with a break statement. ANS: F They often do but if the break statement is not present, the flow of control continues into the next case. 3. Control in a switch statement jumps to the first matching case. ANS: T The switch expression is evaluated and control jumps to the first matching case, then continues from there. 4. The following for loop is an infinite loop:: for(int j = 0; j < 1000;) i++; ANS: T This loop initializes j to 0 and compares it to 1000, but does not alter j after each loop iteration. In reality, the loop will terminate with a run-time error eventually once i becomes too large to store in memory, but logically, this is an infinite loop. 5. It is possible to convert any type of loop (while, do, for) into any other. ANS: T All loop statements have equivalent expressive power. 6. The following loop is syntactically valid: for(int j = 0; j < 1000; j++) j--; ANS: T The Java compiler does not care that you are incrementing j in the loop but decrementing j in the loop body. Logically, this loop makes no sense because j will continuously be incremented and decremented so that it never reaches 1000, but there is nothing wrong with the loop syntactically.
7. In Java, it is possible to create an infinite loop out of while and do loops but not for loops. ANS: F
It is true that while and do loops can be infinite loops, but it is also true that Java for loops can be infinite loops. This is not true in some other programming languages where for loops have a set starting and ending point, but Java for loops are far more flexible than most other language's for loops. 8. A conditional operator is virtually the same as a switch statement. ANS: F The conditional operator is more like an if-else statement. 9. A for statement is normally used when you do not know how many times the loop should be executed. ANS: F A for statement is normally used when you do know how many times the loop should be executed. 10. A loop can be used in a GUI to draw concentric circles. ANS: T MULTIPLE CHOICE 1. You might choose to use a switch statement instead of nested if-else statements if a. the variable being tested might equal one of several hundred integer values b. the variable being tested might equal one of a few integer values c. there are two or more integer variables being tested, each one of which could be one of several hundred values d. there are two or more integer variables being tested, each one of which could be one of a few values e. None of these; you would never choose a switch statement instead of nested if-else statements under any circumstances. ANS: B The switch statement can only be used if there is a single variable being tested and it is an integer type (an int or a char in Java). Further, because you have to enumerate each possible value being tested, the switch statement only makes sense if the number of values being tested is a small number. 2. If a switch statement contains no break statements at all, a. a syntax error will occur b. each of the case clauses will be executed every time the switch statement is encountered
c. this is equivalent to having the switch statement always take the default clause, if one is present d. this is not a syntax error but nothing within the switch statement will ever be executed e. None of these ANS: E Although writing such a switch statement is unusual, it is entirely legal. The normal rules for the switch statement execution apply. The matching case clause being executed after the switch statement is evaluated and, following that, all subsequent clauses are executed, in order, since there are no break statements to terminate execution. 3. A continue statement a. b. c. d. e.
may be used within a while or a do-while loop but not a for loop is identical to a break statement within Java loops may be used within any Java loop statement may be used within a for loop but not within a while or a do-while loop None of these
ANS: C Although use of continue statements should be avoided, if possible, they may be used within any of Java's three types of loops. 4. How can the following statement be rewritten using a conditional operator? if(x <0) y = x; else y = 0; a. b. c. d. e.
y = (x < 0) ? x : 0; x = (x < 0) ? y : 0; (x < 0) ? y = x : y = 0; y = (x < 0); y = if(x < 0) x : 0;
ANS: A The conditional operator of Java tests a condition, (x < 0) in this case, and if true, returns the value after the ? (x in this case) and if false, returns the value after the : (0) in this case). The original if statement is to assign y to x if (x < 0) and 0 otherwise. This will be accomplished by assigning y to be x or 0 based on (x < 0), as shown in A. In B, x is assigned the value of y or 0 which is backward. In C, the conditional operator is syntactically invalid. In D, y would be set to either true or false depending on (x < 0), and the statement in E is syntactically invalid. 5. Given the following code, where x = 0, what is the resulting value of x after the for loop terminates? for(int i = 0; i < 5; i++) x += i; a. b. c. d. e.
0 4 5 10 15
ANS: D Each pass through the for loop results with the current value of the loop index, i, being added to x. The first time through the loop, i = 0 so x = x + 0 = 0. The second time through the loop i = 1 so x = x + 1 = 1. The third time through the loop i = 2 so x = x + 2 = 3. The fourth time through the loop i = 3 so x = x + 3 = 6. The fifth and final time through the loop i = 4 so x = x + 4 = 10. 6. The do loop differs from the while loop in that a. the while loop will always execute the body of the loop at least once b. the do loop will always execute the body of the loop at least once c. the do loop will continue to loop while the condition in its while statement is false and the while loop will continue to loop while the condition in its while statement is true d. the while loop will continue to loop while the condition in its while statement is false and the do loop will continue to loop while the condition in its while statement is true e. None of these; there is no difference between the two types of loops ANS: B Because the do loop does not test the condition until after the body of the loop executes, the body will always execute at least one time, but the while loop tests the condition first, and so if the condition is false the first time, the body does not execute even one time. 7. How many times will the following loop iterate? int x = 10; do { System.out.println(x); x--; } while(x > 0); a. b. c. d. e.
0 times 1 time 9 times 10 times 11 times
ANS: E The variable x starts at 10. Each pass through the loop, x is decremented and the loop finally exits once x is no longer greater than 0, which in this case means once x becomes 0. So the loop body executes for x = 10, x = 9, x = 8, and so forth down to x = 0. This is 11 times.
8. How many times will the following nested loop structure execute the innermost statement (x++;)? for(int j = 0; j < 100; j++) for(int k = 100; k > 0; k--) x++; a. b. c. d.
100 200 10,000 20,100
e. 1,000,000 ANS: C The outer loop iterates 100 times. Each time it iterates, the inner loop, and the x++; statement, execute 100 times. Therefore, the statement x++; executes 100*100 = 10,000 times. 9. Given that s is a String, what does the following loop do? for(int j = s.length(); j > 0; j--) System.out.print(s.charAt(j-1); a. b. c. d. e.
It prints s out backwards It prints s out forwards It prints s out backwards after skipping the last character It prints s out backwards but does not print the first character It yields a run-time error because there is no character at s.charAt(j-1) for j = 0
ANS: A The variable j counts down from the length of the String to 1, each time printing out the character at position j-1. The character at length-1 is the first character printed and this is the last character of the String. It continues until it reaches j = 1, and prints out the character at position j-1, or the 0th character, so it prints the entire String backwards. 10. What does the break statement do? a. It ends a program. b. It transfers control out of the current control structure such as a loop or switch statement. c. It ends the current line of output, returning the cursor. d. It denotes the end of a switch statement. e. It indicates the end of a line when using System.out.print. ANS: B This is the exit statement that allows the programmer to exit a control structure from inside of that control structure. 11. If a break occurs within the innermost loop of a nested loop that is three levels deep, a. just the innermost loop will be "broken" b. all loops are "broken" and execution continues from after the end of the loop c. all but the outermost loops are "broken" and execution continues from the next iteration of the outermost loop d. a syntax error is generated unless there are break or continue statements at each loop level e. None of these are true ANS: A The innermost loop is broken, and execution continues from just after the end of that loop. 12. Which of the following statements are true about Java loops? a. All three loop types are functionally equivalent. b. while loops and do loops are essentially the same, but while loops always execute at least once.
c. If you know the number of times that a loop is to be performed, the best type of loop to use is a while loop. d. Loops may be replaced by an appropriate combination of if-else and switch statements. e. None of these ANS: A In Java, as in most languages, the looping statements are all essentially equivalent (and almost interchangeable). Their principal difference(s) relate to when the controlling condition is evaluated and whether there is syntax for incrementation/update. 13. How many times will the System.out.println("*"); statement execute inside of the following nested for loops? for(j = 0; j < 10; j++) for(k = 10; k > j; k--) System.out.println("*"); a. b. c. d. e.
50 100 55 10 20
ANS: C The first iteration of the outer loop has j = 0, so the inner loop iterates from 10 down to 1, or 10 times. The next iteration of the outer loop has j = 1, so the inner loop iterates from 10 down to 2, or 9 times. This continues until the outer loop has j = 9, in which case the inner loop iterates for k = 10 only, or 1 time. Thus, the System.out.println("*"); statement executes a total of 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 = 55 times. 14. Which of the following would rotate an Ellipse named lipse 30 degrees counterclockwise? a. b. c. d. e.
lipse.setRotate(30); lipse.setRotate(370); lipse.setRotate(-30); Ellipse.lipse.setRotate(30); Ellipse.lipse.setRotate(-10*3);
ANS: C Code Example Ch 06-1 In the following example, x is an int: switch (x) { case 3 : x += 1; case 4 : x += 2; case 5 : x += 3; case 6 : x++; case 7 : x += 2; case 8 : x--; case 9 : x++ }
15. Refer to Code Example Ch 06-1: If x is equal to 5, what will the value of x be after the switch statement executes? a. b. c. d. e.
8 6 11 5 10
ANS: C Since there are no break statements, the flow falls through any cases following the one that is true. The first case to be true is 5 since x is 5 prior to the switch statement. This changes x to 8, then to 9, then to 11, then to 10, and then finally back to 11. 16. Refer to Code Example Ch 06-1: If x is equal to 3, what will the value of x be after the switch statement executes? a. b. c. d. e.
5 6 11 10 12
ANS: E Since there are no break statements, the flow falls through any cases following the one that is true. The first case to be true is 3 since x is 3 prior to the switch statement. This changes x to 4, then to 6, then to 9, then to 10, then to 12, then to 11, and then finally back to 12. PROBLEM 1. Rewrite the following nested if-else statements using an equivalent switch statement. if (letter == 'A' || letter == 'a') System.out.println("Excellent"); else if (letter == 'B' || letter == 'b') System.out.println("You can do better"); else if (letter == 'C' || letter == 'c') System.out.println("Try harder"); else if (letter == 'D' || letter == 'd') System.out.println("Try much harder"); else System.out.println("Try another major! "); ANS: switch (letter) { case 'A', 'a' : System.out.println("Excellent"); break; case 'B', 'b' : System.out.println("You can do better"); break; case 'C', 'c' : System.out.println("Try harder"); break; case 'D', 'd' : System.out.println("Try much harder"); break; default : System.out.println("Try another major! "); }
2. Given the following tax table information, write Java code to assign the double taxRate appropriately, given the double pay. Select the selection statement (if, if-else, switch) that makes the most sense. If pay is more than 100,000, tax rate is 40% If pay is more than 60,000 and less than or equal to 100,000, tax rate is 30% If pay is more than 30,000 and less than or equal to 60,000, tax rate is 20% If pay is more than 15,000 and less than or equal to 30,000, tax rate is 10% If pay is more than 5,000 and less than or equal to 15,000, tax rate is 5% If pay is less than or equal to 5,000, tax rate is 0% ANS: Use a nested if-else structure as it requires the least amount of code. A switch statement is not possible because pay is a double and the switch statement can only be used for int types. if (pay > 100000) taxRate = 0.40; else if (pay > 60000) taxRate = 0.30; else if (pay > 30000) taxRate = 0.20; else if (pay > 15000) taxRate = 0.10; else if (pay > 5000) taxRate = 0.05; else taxRate = 0.0; 3. Write a declaration that initializes an int variable named num1 to 100 if the boolean variable score is true and to 50 otherwise, using the conditional operator. ANS: int num1 = (score) ? 100 : 50; 4. Rewrite the following if-else statement using a conditional operator. if (x > y) z = x; else z = y; ANS: z = (x > y) ? x : y; 5. Write a do loop to obtain a list of scores from a teacher. The teacher should end input by entering the sentinel value, 999. The program should output the average of the scores. ANS: Scanner scan = new Scanner(System.in); int score, count, sum = 0; do { sum += score; System.out.print("Enter a score or 999 to quit): "); score = scan.nextInt();
count++; } while (score != 999) average = sum / (count - 1); System.out.println(average); 6. Describe a situation where you should use a do loop and a situation where you should use a while loop. ANS: The do loop is used if you want to execute the loop body at least one time. This is useful for data verification (asking the user for a value, and only if the user has entered an improper value does your code repeat and try again). A while loop does not necessarily execute if the loop condition is not initially true. This might be useful if you want to control entrance to a loop such as only trying to sum up a list of values if the user actually has values to sum up. 7. The following for loop is odd in that the loop increment value changes during iterations of the loop. Determine the number of times the loop iterates and the final value of j after the loop terminates. int k = 0; for (j = 0; j < 20; j += k) k++; ANS: Six times with j = 21. Explanation: The first iteration has j = 0, k is then incremented in the loop body to 1 and j is incremented after the loop body executes to be j + k = 0 + 1 = 1. For the second iteration, k is incremented to 2 and j is incremented to j + k = 1 + 2 = 3. For the third iteration, k is incremented to 3 and j is incremented to 3 + 3 = 6. For the fourth iteration, k is incremented to 4 and j is incremented to 6 + 4 = 10. For the fifth iteration, k is incremented to 5 and j is incremented to 10 + 5 = 15. For the sixth iteration, k is incremented to 6 and j is incremented to 15 + 6 = 21. Now, since (j < 20) is no longer true, the loop terminates. 8. Write code that outputs all of the int values between 1 and 100 with five values per line, and each of those five values spaced out equally. Use a single for loop to solve this problem. ANS: for (int j = 1; j <= 100; j++) { System.out.print(j + "\t"); if (j % 5 == 0) System.out.println( ); } 9. Write the code to display an ImageView named the_view at half its original size. ANS: the_view.setScaleX(0.5); the_view.setScaleY(0.5);
Java Software Solutions, 9e (Lewis/Loftus) Chapter 6 More Conditionals and Loops TRUE/FALSE 1. A switch statement must have a default clause. ANS: F The default clause is optional. 2. Each switch statement must terminate with a break statement. ANS: F They often do but if the break statement is not present, the flow of control continues into the next case. 3. Control in a switch statement jumps to the first matching case. ANS: T The switch expression is evaluated and control jumps to the first matching case, then continues from there. 4. The following for loop is an infinite loop:: for(int j = 0; j < 1000;) i++; ANS: T This loop initializes j to 0 and compares it to 1000, but does not alter j after each loop iteration. In reality, the loop will terminate with a run-time error eventually once i becomes too large to store in memory, but logically, this is an infinite loop. 5. It is possible to convert any type of loop (while, do, for) into any other. ANS: T All loop statements have equivalent expressive power. 6. The following loop is syntactically valid: for(int j = 0; j < 1000; j++) j--; ANS: T The Java compiler does not care that you are incrementing j in the loop but decrementing j in the loop body. Logically, this loop makes no sense because j will continuously be incremented and decremented so that it never reaches 1000, but there is nothing wrong with the loop syntactically.
7. In Java, it is possible to create an infinite loop out of while and do loops but not for loops. ANS: F
It is true that while and do loops can be infinite loops, but it is also true that Java for loops can be infinite loops. This is not true in some other programming languages where for loops have a set starting and ending point, but Java for loops are far more flexible than most other language's for loops. 8. A conditional operator is virtually the same as a switch statement. ANS: F The conditional operator is more like an if-else statement. 9. A for statement is normally used when you do not know how many times the loop should be executed. ANS: F A for statement is normally used when you do know how many times the loop should be executed. 10. A loop can be used in a GUI to draw concentric circles. ANS: T MULTIPLE CHOICE 1. You might choose to use a switch statement instead of nested if-else statements if a. the variable being tested might equal one of several hundred integer values b. the variable being tested might equal one of a few integer values c. there are two or more integer variables being tested, each one of which could be one of several hundred values d. there are two or more integer variables being tested, each one of which could be one of a few values e. None of these; you would never choose a switch statement instead of nested if-else statements under any circumstances. ANS: B The switch statement can only be used if there is a single variable being tested and it is an integer type (an int or a char in Java). Further, because you have to enumerate each possible value being tested, the switch statement only makes sense if the number of values being tested is a small number. 2. If a switch statement contains no break statements at all, a. a syntax error will occur b. each of the case clauses will be executed every time the switch statement is encountered
c. this is equivalent to having the switch statement always take the default clause, if one is present d. this is not a syntax error but nothing within the switch statement will ever be executed e. None of these ANS: E Although writing such a switch statement is unusual, it is entirely legal. The normal rules for the switch statement execution apply. The matching case clause being executed after the switch statement is evaluated and, following that, all subsequent clauses are executed, in order, since there are no break statements to terminate execution. 3. A continue statement a. b. c. d. e.
may be used within a while or a do-while loop but not a for loop is identical to a break statement within Java loops may be used within any Java loop statement may be used within a for loop but not within a while or a do-while loop None of these
ANS: C Although use of continue statements should be avoided, if possible, they may be used within any of Java's three types of loops. 4. How can the following statement be rewritten using a conditional operator? if(x <0) y = x; else y = 0; a. b. c. d. e.
y = (x < 0) ? x : 0; x = (x < 0) ? y : 0; (x < 0) ? y = x : y = 0; y = (x < 0); y = if(x < 0) x : 0;
ANS: A The conditional operator of Java tests a condition, (x < 0) in this case, and if true, returns the value after the ? (x in this case) and if false, returns the value after the : (0) in this case). The original if statement is to assign y to x if (x < 0) and 0 otherwise. This will be accomplished by assigning y to be x or 0 based on (x < 0), as shown in A. In B, x is assigned the value of y or 0 which is backward. In C, the conditional operator is syntactically invalid. In D, y would be set to either true or false depending on (x < 0), and the statement in E is syntactically invalid. 5. Given the following code, where x = 0, what is the resulting value of x after the for loop terminates? for(int i = 0; i < 5; i++) x += i; a. b. c. d. e.
0 4 5 10 15
ANS: D
Each pass through the for loop results with the current value of the loop index, i, being added to x. The first time through the loop, i = 0 so x = x + 0 = 0. The second time through the loop i = 1 so x = x + 1 = 1. The third time through the loop i = 2 so x = x + 2 = 3. The fourth time through the loop i = 3 so x = x + 3 = 6. The fifth and final time through the loop i = 4 so x = x + 4 = 10. 6. The do loop differs from the while loop in that a. the while loop will always execute the body of the loop at least once b. the do loop will always execute the body of the loop at least once c. the do loop will continue to loop while the condition in its while statement is false and the while loop will continue to loop while the condition in its while statement is true d. the while loop will continue to loop while the condition in its while statement is false and the do loop will continue to loop while the condition in its while statement is true e. None of these; there is no difference between the two types of loops ANS: B Because the do loop does not test the condition until after the body of the loop executes, the body will always execute at least one time, but the while loop tests the condition first, and so if the condition is false the first time, the body does not execute even one time. 7. How many times will the following loop iterate? int x = 10; do { System.out.println(x); x--; } while(x > 0); a. b. c. d. e.
0 times 1 time 9 times 10 times 11 times
ANS: E The variable x starts at 10. Each pass through the loop, x is decremented and the loop finally exits once x is no longer greater than 0, which in this case means once x becomes 0. So the loop body executes for x = 10, x = 9, x = 8, and so forth down to x = 0. This is 11 times.
8. How many times will the following nested loop structure execute the innermost statement (x++;)? for(int j = 0; j < 100; j++) for(int k = 100; k > 0; k--) x++; a. b. c. d. e.
100 200 10,000 20,100 1,000,000
ANS: C The outer loop iterates 100 times. Each time it iterates, the inner loop, and the x++; statement, execute 100 times. Therefore, the statement x++; executes 100*100 = 10,000 times. 9. Given that s is a String, what does the following loop do? for(int j = s.length(); j > 0; j--) System.out.print(s.charAt(j-1); a. b. c. d. e.
It prints s out backwards It prints s out forwards It prints s out backwards after skipping the last character It prints s out backwards but does not print the first character It yields a run-time error because there is no character at s.charAt(j-1) for j = 0
ANS: A The variable j counts down from the length of the String to 1, each time printing out the character at position j-1. The character at length-1 is the first character printed and this is the last character of the String. It continues until it reaches j = 1, and prints out the character at position j-1, or the 0th character, so it prints the entire String backwards. 10. What does the break statement do? a. It ends a program. b. It transfers control out of the current control structure such as a loop or switch statement. c. It ends the current line of output, returning the cursor. d. It denotes the end of a switch statement. e. It indicates the end of a line when using System.out.print. ANS: B This is the exit statement that allows the programmer to exit a control structure from inside of that control structure. 11. If a break occurs within the innermost loop of a nested loop that is three levels deep, a. just the innermost loop will be "broken" b. all loops are "broken" and execution continues from after the end of the loop c. all but the outermost loops are "broken" and execution continues from the next iteration of the outermost loop d. a syntax error is generated unless there are break or continue statements at each loop level e. None of these are true ANS: A The innermost loop is broken, and execution continues from just after the end of that loop. 12. Which of the following statements are true about Java loops? a. All three loop types are functionally equivalent. b. while loops and do loops are essentially the same, but while loops always execute at least once. c. If you know the number of times that a loop is to be performed, the best type of loop to use is a while loop.
d. Loops may be replaced by an appropriate combination of if-else and switch statements. e. None of these ANS: A In Java, as in most languages, the looping statements are all essentially equivalent (and almost interchangeable). Their principal difference(s) relate to when the controlling condition is evaluated and whether there is syntax for incrementation/update. 13. How many times will the System.out.println("*"); statement execute inside of the following nested for loops? for(j = 0; j < 10; j++) for(k = 10; k > j; k--) System.out.println("*"); a. b. c. d. e.
50 100 55 10 20
ANS: C The first iteration of the outer loop has j = 0, so the inner loop iterates from 10 down to 1, or 10 times. The next iteration of the outer loop has j = 1, so the inner loop iterates from 10 down to 2, or 9 times. This continues until the outer loop has j = 9, in which case the inner loop iterates for k = 10 only, or 1 time. Thus, the System.out.println("*"); statement executes a total of 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 = 55 times. 14. Which of the following would rotate an Ellipse named lipse 30 degrees counterclockwise? a. b. c. d. e.
lipse.setRotate(30); lipse.setRotate(370); lipse.setRotate(-30); Ellipse.lipse.setRotate(30); Ellipse.lipse.setRotate(-10*3);
ANS: C Code Example Ch 06-1 In the following example, x is an int: switch (x) { case 3 : x += 1; case 4 : x += 2; case 5 : x += 3; case 6 : x++; case 7 : x += 2; case 8 : x--; case 9 : x++ }
15. Refer to Code Example Ch 06-1: If x is equal to 5, what will the value of x be after the switch statement executes? a. b. c. d. e.
8 6 11 5 10
ANS: C Since there are no break statements, the flow falls through any cases following the one that is true. The first case to be true is 5 since x is 5 prior to the switch statement. This changes x to 8, then to 9, then to 11, then to 10, and then finally back to 11. 16. Refer to Code Example Ch 06-1: If x is equal to 3, what will the value of x be after the switch statement executes? a. b. c. d. e.
5 6 11 10 12
ANS: E Since there are no break statements, the flow falls through any cases following the one that is true. The first case to be true is 3 since x is 3 prior to the switch statement. This changes x to 4, then to 6, then to 9, then to 10, then to 12, then to 11, and then finally back to 12. PROBLEM 1. Rewrite the following nested if-else statements using an equivalent switch statement. if (letter == 'A' || letter == 'a') System.out.println("Excellent"); else if (letter == 'B' || letter == 'b') System.out.println("You can do better"); else if (letter == 'C' || letter == 'c') System.out.println("Try harder"); else if (letter == 'D' || letter == 'd') System.out.println("Try much harder"); else System.out.println("Try another major! "); ANS: switch (letter) { case 'A', 'a' : System.out.println("Excellent"); break; case 'B', 'b' : System.out.println("You can do better"); break; case 'C', 'c' : System.out.println("Try harder"); break; case 'D', 'd' : System.out.println("Try much harder"); break; default : System.out.println("Try another major! "); }
2. Given the following tax table information, write Java code to assign the double taxRate appropriately, given the double pay. Select the selection statement (if, if-else, switch) that makes the most sense. If pay is more than 100,000, tax rate is 40% If pay is more than 60,000 and less than or equal to 100,000, tax rate is 30% If pay is more than 30,000 and less than or equal to 60,000, tax rate is 20% If pay is more than 15,000 and less than or equal to 30,000, tax rate is 10% If pay is more than 5,000 and less than or equal to 15,000, tax rate is 5% If pay is less than or equal to 5,000, tax rate is 0% ANS: Use a nested if-else structure as it requires the least amount of code. A switch statement is not possible because pay is a double and the switch statement can only be used for int types. if (pay > 100000) taxRate = 0.40; else if (pay > 60000) taxRate = 0.30; else if (pay > 30000) taxRate = 0.20; else if (pay > 15000) taxRate = 0.10; else if (pay > 5000) taxRate = 0.05; else taxRate = 0.0; 3. Write a declaration that initializes an int variable named num1 to 100 if the boolean variable score is true and to 50 otherwise, using the conditional operator. ANS: int num1 = (score) ? 100 : 50; 4. Rewrite the following if-else statement using a conditional operator. if (x > y) z = x; else z = y; ANS: z = (x > y) ? x : y; 5. Write a do loop to obtain a list of scores from a teacher. The teacher should end input by entering the sentinel value, 999. The program should output the average of the scores. ANS: Scanner scan = new Scanner(System.in); int score, count, sum = 0; do { sum += score; System.out.print("Enter a score or 999 to quit): "); score = scan.nextInt();
count++; } while (score != 999) average = sum / (count - 1); System.out.println(average); 6. Describe a situation where you should use a do loop and a situation where you should use a while loop. ANS: The do loop is used if you want to execute the loop body at least one time. This is useful for data verification (asking the user for a value, and only if the user has entered an improper value does your code repeat and try again). A while loop does not necessarily execute if the loop condition is not initially true. This might be useful if you want to control entrance to a loop such as only trying to sum up a list of values if the user actually has values to sum up. 7. The following for loop is odd in that the loop increment value changes during iterations of the loop. Determine the number of times the loop iterates and the final value of j after the loop terminates. int k = 0; for (j = 0; j < 20; j += k) k++; ANS: Six times with j = 21. Explanation: The first iteration has j = 0, k is then incremented in the loop body to 1 and j is incremented after the loop body executes to be j + k = 0 + 1 = 1. For the second iteration, k is incremented to 2 and j is incremented to j + k = 1 + 2 = 3. For the third iteration, k is incremented to 3 and j is incremented to 3 + 3 = 6. For the fourth iteration, k is incremented to 4 and j is incremented to 6 + 4 = 10. For the fifth iteration, k is incremented to 5 and j is incremented to 10 + 5 = 15. For the sixth iteration, k is incremented to 6 and j is incremented to 15 + 6 = 21. Now, since (j < 20) is no longer true, the loop terminates. 8. Write code that outputs all of the int values between 1 and 100 with five values per line, and each of those five values spaced out equally. Use a single for loop to solve this problem. ANS: for (int j = 1; j <= 100; j++) { System.out.print(j + "\t"); if (j % 5 == 0) System.out.println( ); } 9. Write the code to display an ImageView named the_view at half its original size. ANS: the_view.setScaleX(0.5); the_view.setScaleY(0.5);
Java Software Solutions, 9e (Lewis/Loftus) Chapter 7 Object-Oriented Design TRUE/FALSE 1. The most important decisions regarding the development of a system are made during the implementation phase while code is actively being written. ANS: F All of the important decisions should be made during earlier phases of development, particularly during the design phase. By the time the implementation phase is reached, the entire system design should be available and this phase should only entail translating the design into code. 2. Unlike the String class where you must pass a message to an object (instance) of the class, in order to use the Math class, you pass messages directly to the class name, as in Math.sqrt(). ANS: T The Math class uses methods known as static methods (or class methods) which are invoked by passing a message directly to the class name itself rather than to an object of the class. 3. Assume that the class Bird has a static method fly(). If b is a Bird, then to invoke fly, you could do Bird.fly();. ANS: T Static methods are invoked through the class and not an object of the class. This is because the static method is shared among all instances. So, Bird.fly(); will invoke fly. It should be noted that fly can also be invoked through b, so b.fly(); will also work. 4. Interface classes cannot be extended but classes that implement interfaces can be extended. ANS: F Any class can be extended whether it is an interface, implements an interface, or neither. The only exception to this is if the class is explicitly modified with the word final in which case it cannot be extended. 5. If classes C1 and C2 both implement an interface Cint, which has a method, whichIsIt, and if C1 c = new C1(); is performed at one point of the program, then a later instruction c.whichIsIt(); will invoke the whichIsIt method defined in C1. ANS: F Because C1 and C2 implement the same interface, they both implement whichIsIt. The variable c is known as a polymorphic variable, meaning that it can change from being an C1 to a C2. So, the message c.whichIsIt(); may invoke C1's whichIsIt or C2's whichIsIt. There is no way to tell until runtime. 6. Any class can implement an interface, but no classes can implement more than a single interface.
ANS: F Classes can implement any number of interfaces, 0, 1, or more. 7. All objects implement Comparable. ANS: F Comparable is an interface, and the class must define the CompareTo method and explicitly state that it implements Comparable to be considered an implementation of Comparable. Most classes do not implement Comparable. 8. Formal parameters are those that appear in the method call and actual parameters are those that appear in the method header. ANS: F The question has the two definitions reversed. Formal parameters are those that appear in the method header, actual parameters are the parameters in the method call (those being passed to the method). 9. It is not possible to test out any single method or class of a system until the entire system has been developed, and so all testing is postponed until after the implementation phase. ANS: F While it is true that testing occurs after implementation, some testing can take place during implementation. In Java, it is possible to test out single methods or classes by creating stubs of other methods and classes that are simple placeholders. For instance, if one method calls another method and the second method is not yet written, a stub of the second method can be written that simply returns a value that would normally be expected so that the first method can be tested. 10. In black-box testing, the tester should already know something about how the program is implemented so that he/she can more carefully identify what portion(s) of the software may lead to errors. ANS: F In black-box testing, the tester should know nothing about how the software is implemented. In essence, the software is a black-box which has an input and an output and the mechanisms of the program are opaque. If the tester does know something about how the program works, then the tester's test cases might be biased. If the tester knows how the program works, then testing is known as glass-box testing. 11. The versions of an overloaded method are distinguished by the number, type, and order of their parameters. ANS: T 12. The graphical effect caused when a shape seems to resize as the mouse is dragged is known as rubberbanding.
ANS: T MULTIPLE CHOICE 1. During program development, software requirements specify a. b. c. d. e.
how the program will accomplish the task what task the program must perform how to divide the task into subtasks how to test the program when it is done All of these
ANS: B The specification phase is to understand the problem at hand so that the programmer can determine what needs to be done to solve the problem. The other efforts listed above are part of the design phase (A, C) and testing phase (D). 2. Once we have implemented the solution, we are not done with the problem because a. b. c. d.
the solution may not be the best or most efficient the solution may have errors and need testing and fixing before we are done the solution may, at a later date, need revising to handle new specifications the solution may, at a later date, need revising because of new programming language features e. All of these ANS: E A program should not be considered as a finished product until we are reasonably assured that it is efficient and error-free. Further, it is common that programs require modification in the future because of a change to specifications or a change to the language or computer running the program. 3. Of the various phases in software development, which of the following is usually the lengthiest? a. b. c. d. e.
specification design implementation testing maintenance
ANS: E The maintenance phase exists for as long as the software is in use. Software requires modification (such as new requirements like new features or I/O specifications) and so the maintenance phase is ongoing whereas the other phases end once the software has been released and is in use. 4. The activities of the development cycle are generally thought to a. b. c. d. e.
be strictly linear be rigidly ordered overlap have optional steps both A and B are true
ANS: C Phases often need revisiting resulting in a development cycle where the development activities overlap. 5. The idea of having programmers and developers meet in order to critique a software design or implementation is known as a. b. c. d. e.
an interview a walkthrough prototyping aggregation evolutionary development
ANS: B Such meetings are very useful so that the various members can analyze the solution to that point in time and offer suggestions to enhance the design and implementation. This is called a walkthrough because it involves going step-by-step through the proposed or implemented design. 6. Modifying a program in order to eliminate deficiencies is done in the __________ phase of the development cycle. a. b. c. d. e.
design implementation testing use maintenance
ANS: B While testing is used to find errors, deficiencies are more commonly identified by the users of the system once the system has been released. After such deficiencies have been identified, it is up to the software maintenance group to eliminate them in future versions of the software. 7. It is easier to correct errors found in a program if a. b. c. d. e.
they are identified early in the development cycle they are identified during testing they are identified during program use they are identified during maintenance All of the above are equally true; errors are easily corrected at any of these stages
ANS: A Errors introduced early in the development cycle often cause tremendous problems if not caught early on. Therefore, errors found in testing, use or maintenance phases may be too embedded in the systems' design to be easily corrected. But if found early on, the errors can be completely eliminated. 8. In general, spending more time in development to ensure better software will a. b. c. d. e.
shorten testing time slightly reduce maintenance efforts slightly increase maintenance efforts greatly reduce maintenance efforts not alter the time it takes for any other stage
ANS: D Spending more time in development promises better software, which in turn leads to less maintenance effort. 9. It is important to dissect a problem into manageable pieces before trying to solve the problem because a. most problems are too complex to be solved as a single, large activity b. most problems are solved by multiple people and it is easy to assign each piece to a separate person c. it is easier to integrate small pieces of a program into one program than it is to integrate one big chunk of code into one program d. the first solution may not solve the problem correctly e. all of these ANS: A Any interesting problem will be too complex to solve easily as a single activity. By decomposing the problem, we can build small solutions to each piece and then integrate the pieces. Answer D is true, but is not the reason why we break a problem down into pieces. 10. The goal of testing is to a. b. c. d. e.
ensure that the software has no errors find syntax errors find logical and run-time errors evaluate how well the software meets the original requirements give out-of-work programmers something to do
ANS: C Testing is required because all software will have errors. Complex systems especially need testing before they can be released. The types of errors sought are logical errors and run-time errors. All syntax errors will have been identified and fixed during implementation. 11. In which phase of program development would you expect the programmer(s) to create the pseudocode? a. b. c. d. e.
software requirements software design software implementation software testing this could occur at any time
ANS: B Pseudocode is a description of an algorithm written in an English-like way rather than in a specific programming language. This is part of the program's design. In the implementation phase, the programmer(s) translate(s) the pseudocode into the programming language being used. 12. In which phase of program development would you expect the programmer(s) to determine the classes and objects needed? a. software requirements b. software design c. software implementation
d. software testing e. this could occur at any time ANS: B Determining which classes and objects to use or create is part of the design. 13. If a programmer follows the four phases of program development as intended, which of the four phases should require the least amount of creativity? a. b. c. d. e.
software requirements software design software implementation software testing all four levels require equal creativity
ANS: C Once the implementation phase has been reached, the algorithm should have already been specified, so the only effort involved in the implementation phase is of translating from the design (which is probably in an English-like pseudocode) to the programming language, and entering the code through an editor. The requirements and design phases require understanding the problem and coming up with a solution respectively, requiring creativity, and the testing phase will require diagnostic abilities usually forcing the programmer(s) to be creative in how the errors are found and fixed. 14. Having multiple class methods of the same name where each method has a different number of or type of parameters is known as a. b. c. d. e.
encapsulation information hiding tokenizing importing method overloading
ANS: E When methods share the same name, they are said to be overloaded. The number and type of parameters passed in the message provides the information by which the proper method is called. 15. Which of the following would not be considered an algorithm? a. b. c. d. e.
a recipe a computer program pseudocode a shopping list travel directions
ANS: D An algorithm is a step-by-step description of how to solve a problem, written at some level of specificity. The recipe and probably the pseudocode are written at a "high level" whereas a program and perhaps travel directions are written in more detail. A shopping list is not a step-by-step description, so it would not qualify as an algorithm. 16. In order to create a constant, you would use which of the following Java words? a. private b. static
c. int d. final e. class ANS: D The reserved word final indicates that this is the final value that will be stored in this variable, thus making it unchangeable, or constant. While constants can be of type int, constants can be of any other type as well. It is the final reserved word that makes the value unchangeable.
17. Which of the following methods is a static method? The class in which the method is defined is given inside the parentheses following the method name. a. b. c. d. e.
equals(String) toUpperCase(String) sqrt(Math) format(DecimalFormat) None of these
ANS: C The Math class defines all of its methods to be static. Invoking Math methods is done by using Math rather than a variable of type Math. The other methods above are not static. 18. In order to implement Comparable in a class, what method(s) must be defined in that class? a. b. c. d. e.
equals compares both lessThan and greaterThan compareTo both compares and equals
ANS: D The Comparable class requires the definition of a compareTo method that will compare two objects and determine if one is equal to the other, or if one is less than or greater than the other and respond with a negative int, 0 or a positive int. Since compareTo responds with 0 if the two objects are equal, there is no need to also define an equals method. 19. Static methods cannot a. b. c. d. e.
reference instance data reference non-static instance data reference other objects invoke other static methods invoke other non-static methods
ANS: B A static method is a method that is part of the class itself, not an instantiated object, and therefore the static method is shared among all instantiated objects of the class. Since the static method is shared, it cannot access non-static instance data because all non-static instance data are specific to instantiated objects. A static method can access static instance data because, like the method, the instance data is shared among all objects of the class. A static method can also access parameters passed to it. 20. An object that refers to part of itself within its own methods can use which of the following reserved words to denote this relationship?
a. b. c. d. e.
inner i private this static
ANS: D The reserved word this is used so that an object can refer to itself. For instance, if an object has an instance data x, then this.x refers to the object's value x. While this is not necessary, it can be useful if a local variable or parameter is named the same as an instance data. The reserved word this is also used to refer to the class as a whole, for instance, if the class is going to implement an interface class rather than import an implementation of an interface class. 21. An example of an aggregation relationship is a. b. c. d. e.
parent and child animal and dog teacher and computer phone and fax machine All of these
ANS: C An aggregate relationship describes how one object accomplishes a task by using another object. In the above list, the teacher uses the computer. The relationship in A is one of lineage (possibly ownership), the relationship in B is an "is-a" relationship as a dog is a child class of animal, and the relationship in D is one of similarity since phone and fax machine might be thought of as sibling classes, related to each other in that they are both children of a more general communication class. 22. Abstract methods are used when defining a. b. c. d. e.
interface classes derived classes classes that have no constructor arrays classes that have no methods
ANS: A An interface is a class that has defined some of its components, but leaves other components (methods) for you to implement. So, these components (methods) are referred to as abstract and defined in the interface class as abstract. Code Description Ch 07-1 Consider a class called ChessPiece. This class has two instance data, String type and int player. The variable type will store "King", "Queen", "Bishop", etc. and the int player will store 0 or 1 depending on whose piece it is. We wish to implement Comparable for the ChessPiece class. Assume that, the current ChessPiece is compared to a ChessPiece passed as a parameter. Pieces are ordered as follows: "Pawn" is a lesser piece to a "Knight" a "Bishop" and "Knight" are equivalent for this example both "Bishop" and "Knight" are lesser pieces to a "Rook"
a "Rook" is a lesser piece to a "Queen" a "Queen" is a lesser piece to a "King". 23. Refer to Code Description Ch 07-1: Which of the following method headers would properly define the method needed to make this class Comparable? (cp designates ChessPiece) a. b. c. d. e.
public boolean comparable(Object cp) public int comparable(Object cp) public int compareTo(Object cp) public int compareTo() public boolean compareTo(Object cp)
ANS: C To implementComparable, you must implement a method called compareTo which returns an int. Further, since this class will compare this ChessPiece to another, we would expect the other ChessPiece to be passed in as a parameter. 24. Refer to Code Description Ch 07-1: Which of the following pieces of logic could be used in the method that implements Comparable? Assume that ChessPiece has a method called returnType which returns the type of the given piece. a. b. c. d. e.
if (this.type < a.returnType()) return -1; if (this.type = = a.returnType()) return 0; if (this.type.equals(a.returnType()) return 0; if (a.returnType().equals("King")) return -1; if (a.returnType().equals("Pawn")) return 1;
ANS: C If the type of this piece and of a are the same type, then they are considered equal and the method should return 0 to indicate this. Note that this does not cover the case where this piece is a "Knight" and a is a "Bishop", so additional code would be required for the "equal to" case. The answer in B is not correct because it compares two Strings to see if they are the same String, not the same value. The logic in D and E are incorrect because neither of these takes into account what the current piece is, only what the parameter's type is. In D, if a is a "King", it will be greater than this piece if this piece is not a "King", but will be equal if this piece is a "King" and similarly in E, it does not consider if this piece is a "Pawn" or not. Finally, A would give a syntax error because two Strings cannot be compared using the < operator.
PROBLEM 1. Provide a reason why an instance data would be declared static. ANS: If an instance data is to be shared among all objects of the class, the instance data would be static. As an example, an instance data that counts the number of times something has happened across all objects of the class would be made static. If we are writing a chess game and have a ChessPiece class that includes a method called movePiece, we would want to know how many moves a player has made, but not necessarily how many times a single piece has been moved. So, all of the ChessPieces share a numberOfTimesMoved instance data that is incremented by any ChessPiece whenever it is moved.
2. Provide a reason why a method would be declared static. ANS: A method is declared static if it might be used, not by the current object, but by any objects of the class. That is, the method does not require access to any single object's instance data. Consider a class called Point that consists of an x and y coordinate. To determine the distance between two Points, we could make a static computeDistance method. It is passed two Points as parameters and computes the distance. 3. Explain the difference between implementing an interface and a derived class. ANS: Implementing an interface means that you are adding to your class any mechanisms defined in an abstract class. Your class essentially is expanded to contain those items defined in the interface class but you have to implement any of those items that are abstract. The appeal is that other objects might call upon your class to use the interface methods without knowing anything else about your class. The derived class is similar in that you are gaining items previously defined, although in this case, those items are defined in the parent class (as long as those items are protected or public) and you do not have to implement any of them unless you want to redefine them. One difference between the two is that the interface cannot be instantiated directly. Another difference is that your class "inherits" abstract methods from the interface class as opposed to implemented methods from a super class. 4. Define an interface class that contains two int constants, X = 5 and Y = 10 and one int method called useXY which receives no parameters. Call your interface class XYClass. ANS: public interface XYClass { public final int X = 5; public final int Y = 10; public int useXY(); } 5. Assume a class Foo implements Comparable. Without knowing anything else about the Foo class, write an equals method that returns true if the Foo parameter passed to this Foo is equal to this Foo as determined by using the implementation of Comparable. ANS: public boolean equals(Foo a) { if(compareTo(a)) = = 0) return true; else return false;
} Code Description Ch 07-1 Consider a class called ChessPiece. This class has two instance data, String type and int player. The variable type will store "King", "Queen", "Bishop", etc. and the int player will store 0 or 1 depending on whose piece it is. We wish to implement Comparable for the ChessPiece class. Assume that, the current ChessPiece is compared to a ChessPiece passed as a parameter. Pieces are ordered as follows: "Pawn" is a lesser piece to a "Knight" a "Bishop" and "Knight" are equivalent for this example both "Bishop" and "Knight" are lesser pieces to a "Rook" a "Rook" is a lesser piece to a "Queen" a "Queen" is a lesser piece to a "King". 6. Refer to Code Description Ch 07-1: To implement Comparable for the ChessPiece class, the current ChessPiece's type is compared to a ChessPiece passed as a parameter. The method should return 0 if the types are equal, -1 if this piece's type is a lesser piece than the parameter's type, and 1 if this piece's type is a greater piece than the parameter's type. Create this code. ANS: public int compareTo(ChessPiece a) { if (this.type.equals(a.returnType())|| (this.type.equals("Knight")&&a.returnType().equals("Bishop")) ||(this.type.equals("Bishop")&&a.returnType().equals("Knight"))) return 0; else if (this.type.equals("King")) return 1; else if (a.returnType().equals("King")) return-1; else if (this.type.equals("Queen")) return 1; else if (a.returnType().equals("Queen")) return -1; else if (this.type.equals("Rook")) return 1; else if (a.returnType().equals("Rook")) return -1; else if (this.type.equals("Knight")||(this.type.equals("Bishop")) return 1; else if (a.returnType().equals("Knight")||(a.returnType().equals("Bishop")) return -1; } 7. Refer to Code Description Ch 07-1: Write a static method that is passed two ChessPieces and determines if the two pieces are owned by the same player. It should return true or false.
ANS: public static boolean samePlayer(ChessPiece p1, ChessPiece p2) { return (p1.returnPlayer( ) = = p2.returnPlayer( )); } 8. In what way is black-box testing better than glass-box testing? In what way is glass-box testing better than black-box testing? ANS: Black-box testing is superior because the tester knows nothing of the software and so will test the software without preconceived ideas of where errors might exist. The tester is testing the software blindly, much as a user will use the software–without intimate knowledge of how the software works. The result should be that if errors exist that a user might stumble across, the tester should find them. While black-box testing of software has the advantage that the tester operates much like the users are expected to, the disadvantage is that it is a blind test, but there are times when knowledge of how the software functions could be useful. If programmers suspect that some awkward or difficult implementation may be buggy, then spending more time testing that portion of the software is advantageous. This form of testing requires knowledge of how the software works. So, both blackbox and glass-box testing have their own advantages and disadvantages. 9. Write code that outputs all of the int values between 1 and 100 with five values per line, and each of those five values spaced out equally. Use a single for loop to solve this problem. ANS: for (int j = 1; j <= 100; j++) { System.out.print(j + "\t"); if (j % 5 == 0) System.out.println( ); }
Java Software Solutions, 9e (Lewis/Loftus) Chapter 7 Object-Oriented Design TRUE/FALSE 1. The most important decisions regarding the development of a system are made during the implementation phase while code is actively being written. ANS: F All of the important decisions should be made during earlier phases of development, particularly during the design phase. By the time the implementation phase is reached, the entire system design should be available and this phase should only entail translating the design into code. 2. Unlike the String class where you must pass a message to an object (instance) of the class, in order to use the Math class, you pass messages directly to the class name, as in Math.sqrt(). ANS: T The Math class uses methods known as static methods (or class methods) which are invoked by passing a message directly to the class name itself rather than to an object of the class. 3. Assume that the class Bird has a static method fly(). If b is a Bird, then to invoke fly, you could do Bird.fly();. ANS: T Static methods are invoked through the class and not an object of the class. This is because the static method is shared among all instances. So, Bird.fly(); will invoke fly. It should be noted that fly can also be invoked through b, so b.fly(); will also work. 4. Interface classes cannot be extended but classes that implement interfaces can be extended. ANS: F Any class can be extended whether it is an interface, implements an interface, or neither. The only exception to this is if the class is explicitly modified with the word final in which case it cannot be extended. 5. If classes C1 and C2 both implement an interface Cint, which has a method, whichIsIt, and if C1 c = new C1(); is performed at one point of the program, then a later instruction c.whichIsIt(); will invoke the whichIsIt method defined in C1. ANS: F Because C1 and C2 implement the same interface, they both implement whichIsIt. The variable c is known as a polymorphic variable, meaning that it can change from being an C1 to a C2. So, the message c.whichIsIt(); may invoke C1's whichIsIt or C2's whichIsIt. There is no way to tell until runtime. 6. Any class can implement an interface, but no classes can implement more than a single interface.
ANS: F Classes can implement any number of interfaces, 0, 1, or more. 7. All objects implement Comparable. ANS: F Comparable is an interface, and the class must define the CompareTo method and explicitly state that it implements Comparable to be considered an implementation of Comparable. Most classes do not implement Comparable. 8. Formal parameters are those that appear in the method call and actual parameters are those that appear in the method header. ANS: F The question has the two definitions reversed. Formal parameters are those that appear in the method header, actual parameters are the parameters in the method call (those being passed to the method). 9. It is not possible to test out any single method or class of a system until the entire system has been developed, and so all testing is postponed until after the implementation phase. ANS: F While it is true that testing occurs after implementation, some testing can take place during implementation. In Java, it is possible to test out single methods or classes by creating stubs of other methods and classes that are simple placeholders. For instance, if one method calls another method and the second method is not yet written, a stub of the second method can be written that simply returns a value that would normally be expected so that the first method can be tested. 10. In black-box testing, the tester should already know something about how the program is implemented so that he/she can more carefully identify what portion(s) of the software may lead to errors. ANS: F In black-box testing, the tester should know nothing about how the software is implemented. In essence, the software is a black-box which has an input and an output and the mechanisms of the program are opaque. If the tester does know something about how the program works, then the tester's test cases might be biased. If the tester knows how the program works, then testing is known as glass-box testing. 11. The versions of an overloaded method are distinguished by the number, type, and order of their parameters. ANS: T 12. The graphical effect caused when a shape seems to resize as the mouse is dragged is known as rubberbanding.
ANS: T MULTIPLE CHOICE 1. During program development, software requirements specify a. b. c. d. e.
how the program will accomplish the task what task the program must perform how to divide the task into subtasks how to test the program when it is done All of these
ANS: B The specification phase is to understand the problem at hand so that the programmer can determine what needs to be done to solve the problem. The other efforts listed above are part of the design phase (A, C) and testing phase (D). 2. Once we have implemented the solution, we are not done with the problem because a. b. c. d.
the solution may not be the best or most efficient the solution may have errors and need testing and fixing before we are done the solution may, at a later date, need revising to handle new specifications the solution may, at a later date, need revising because of new programming language features e. All of these ANS: E A program should not be considered as a finished product until we are reasonably assured that it is efficient and error-free. Further, it is common that programs require modification in the future because of a change to specifications or a change to the language or computer running the program. 3. Of the various phases in software development, which of the following is usually the lengthiest? a. b. c. d. e.
specification design implementation testing maintenance
ANS: E The maintenance phase exists for as long as the software is in use. Software requires modification (such as new requirements like new features or I/O specifications) and so the maintenance phase is ongoing whereas the other phases end once the software has been released and is in use. 4. The activities of the development cycle are generally thought to a. b. c. d. e.
be strictly linear be rigidly ordered overlap have optional steps both A and B are true
ANS: C Phases often need revisiting resulting in a development cycle where the development activities overlap. 5. The idea of having programmers and developers meet in order to critique a software design or implementation is known as a. b. c. d. e.
an interview a walkthrough prototyping aggregation evolutionary development
ANS: B Such meetings are very useful so that the various members can analyze the solution to that point in time and offer suggestions to enhance the design and implementation. This is called a walkthrough because it involves going step-by-step through the proposed or implemented design. 6. Modifying a program in order to eliminate deficiencies is done in the __________ phase of the development cycle. a. b. c. d. e.
design implementation testing use maintenance
ANS: B While testing is used to find errors, deficiencies are more commonly identified by the users of the system once the system has been released. After such deficiencies have been identified, it is up to the software maintenance group to eliminate them in future versions of the software. 7. It is easier to correct errors found in a program if a. b. c. d. e.
they are identified early in the development cycle they are identified during testing they are identified during program use they are identified during maintenance All of the above are equally true; errors are easily corrected at any of these stages
ANS: A Errors introduced early in the development cycle often cause tremendous problems if not caught early on. Therefore, errors found in testing, use or maintenance phases may be too embedded in the systems' design to be easily corrected. But if found early on, the errors can be completely eliminated. 8. In general, spending more time in development to ensure better software will a. b. c. d. e.
shorten testing time slightly reduce maintenance efforts slightly increase maintenance efforts greatly reduce maintenance efforts not alter the time it takes for any other stage
ANS: D Spending more time in development promises better software, which in turn leads to less maintenance effort. 9. It is important to dissect a problem into manageable pieces before trying to solve the problem because a. most problems are too complex to be solved as a single, large activity b. most problems are solved by multiple people and it is easy to assign each piece to a separate person c. it is easier to integrate small pieces of a program into one program than it is to integrate one big chunk of code into one program d. the first solution may not solve the problem correctly e. all of these ANS: A Any interesting problem will be too complex to solve easily as a single activity. By decomposing the problem, we can build small solutions to each piece and then integrate the pieces. Answer D is true, but is not the reason why we break a problem down into pieces. 10. The goal of testing is to a. b. c. d. e.
ensure that the software has no errors find syntax errors find logical and run-time errors evaluate how well the software meets the original requirements give out-of-work programmers something to do
ANS: C Testing is required because all software will have errors. Complex systems especially need testing before they can be released. The types of errors sought are logical errors and run-time errors. All syntax errors will have been identified and fixed during implementation. 11. In which phase of program development would you expect the programmer(s) to create the pseudocode? a. b. c. d. e.
software requirements software design software implementation software testing this could occur at any time
ANS: B Pseudocode is a description of an algorithm written in an English-like way rather than in a specific programming language. This is part of the program's design. In the implementation phase, the programmer(s) translate(s) the pseudocode into the programming language being used. 12. In which phase of program development would you expect the programmer(s) to determine the classes and objects needed? a. software requirements b. software design c. software implementation
d. software testing e. this could occur at any time ANS: B Determining which classes and objects to use or create is part of the design. 13. If a programmer follows the four phases of program development as intended, which of the four phases should require the least amount of creativity? a. b. c. d. e.
software requirements software design software implementation software testing all four levels require equal creativity
ANS: C Once the implementation phase has been reached, the algorithm should have already been specified, so the only effort involved in the implementation phase is of translating from the design (which is probably in an English-like pseudocode) to the programming language, and entering the code through an editor. The requirements and design phases require understanding the problem and coming up with a solution respectively, requiring creativity, and the testing phase will require diagnostic abilities usually forcing the programmer(s) to be creative in how the errors are found and fixed. 14. Having multiple class methods of the same name where each method has a different number of or type of parameters is known as a. b. c. d. e.
encapsulation information hiding tokenizing importing method overloading
ANS: E When methods share the same name, they are said to be overloaded. The number and type of parameters passed in the message provides the information by which the proper method is called. 15. Which of the following would not be considered an algorithm? a. b. c. d. e.
a recipe a computer program pseudocode a shopping list travel directions
ANS: D An algorithm is a step-by-step description of how to solve a problem, written at some level of specificity. The recipe and probably the pseudocode are written at a "high level" whereas a program and perhaps travel directions are written in more detail. A shopping list is not a step-by-step description, so it would not qualify as an algorithm. 16. In order to create a constant, you would use which of the following Java words? a. private b. static
c. int d. final e. class ANS: D The reserved word final indicates that this is the final value that will be stored in this variable, thus making it unchangeable, or constant. While constants can be of type int, constants can be of any other type as well. It is the final reserved word that makes the value unchangeable.
17. Which of the following methods is a static method? The class in which the method is defined is given inside the parentheses following the method name. a. b. c. d. e.
equals(String) toUpperCase(String) sqrt(Math) format(DecimalFormat) None of these
ANS: C The Math class defines all of its methods to be static. Invoking Math methods is done by using Math rather than a variable of type Math. The other methods above are not static. 18. In order to implement Comparable in a class, what method(s) must be defined in that class? a. b. c. d. e.
equals compares both lessThan and greaterThan compareTo both compares and equals
ANS: D The Comparable class requires the definition of a compareTo method that will compare two objects and determine if one is equal to the other, or if one is less than or greater than the other and respond with a negative int, 0 or a positive int. Since compareTo responds with 0 if the two objects are equal, there is no need to also define an equals method. 19. Static methods cannot a. b. c. d. e.
reference instance data reference non-static instance data reference other objects invoke other static methods invoke other non-static methods
ANS: B A static method is a method that is part of the class itself, not an instantiated object, and therefore the static method is shared among all instantiated objects of the class. Since the static method is shared, it cannot access non-static instance data because all non-static instance data are specific to instantiated objects. A static method can access static instance data because, like the method, the instance data is shared among all objects of the class. A static method can also access parameters passed to it. 20. An object that refers to part of itself within its own methods can use which of the following reserved words to denote this relationship?
a. b. c. d. e.
inner i private this static
ANS: D The reserved word this is used so that an object can refer to itself. For instance, if an object has an instance data x, then this.x refers to the object's value x. While this is not necessary, it can be useful if a local variable or parameter is named the same as an instance data. The reserved word this is also used to refer to the class as a whole, for instance, if the class is going to implement an interface class rather than import an implementation of an interface class. 21. An example of an aggregation relationship is a. b. c. d. e.
parent and child animal and dog teacher and computer phone and fax machine All of these
ANS: C An aggregate relationship describes how one object accomplishes a task by using another object. In the above list, the teacher uses the computer. The relationship in A is one of lineage (possibly ownership), the relationship in B is an "is-a" relationship as a dog is a child class of animal, and the relationship in D is one of similarity since phone and fax machine might be thought of as sibling classes, related to each other in that they are both children of a more general communication class. 22. Abstract methods are used when defining a. b. c. d. e.
interface classes derived classes classes that have no constructor arrays classes that have no methods
ANS: A An interface is a class that has defined some of its components, but leaves other components (methods) for you to implement. So, these components (methods) are referred to as abstract and defined in the interface class as abstract. Code Description Ch 07-1 Consider a class called ChessPiece. This class has two instance data, String type and int player. The variable type will store "King", "Queen", "Bishop", etc. and the int player will store 0 or 1 depending on whose piece it is. We wish to implement Comparable for the ChessPiece class. Assume that, the current ChessPiece is compared to a ChessPiece passed as a parameter. Pieces are ordered as follows: "Pawn" is a lesser piece to a "Knight" a "Bishop" and "Knight" are equivalent for this example both "Bishop" and "Knight" are lesser pieces to a "Rook"
a "Rook" is a lesser piece to a "Queen" a "Queen" is a lesser piece to a "King". 23. Refer to Code Description Ch 07-1: Which of the following method headers would properly define the method needed to make this class Comparable? (cp designates ChessPiece) a. b. c. d. e.
public boolean comparable(Object cp) public int comparable(Object cp) public int compareTo(Object cp) public int compareTo() public boolean compareTo(Object cp)
ANS: C To implementComparable, you must implement a method called compareTo which returns an int. Further, since this class will compare this ChessPiece to another, we would expect the other ChessPiece to be passed in as a parameter. 24. Refer to Code Description Ch 07-1: Which of the following pieces of logic could be used in the method that implements Comparable? Assume that ChessPiece has a method called returnType which returns the type of the given piece. a. b. c. d. e.
if (this.type < a.returnType()) return -1; if (this.type = = a.returnType()) return 0; if (this.type.equals(a.returnType()) return 0; if (a.returnType().equals("King")) return -1; if (a.returnType().equals("Pawn")) return 1;
ANS: C If the type of this piece and of a are the same type, then they are considered equal and the method should return 0 to indicate this. Note that this does not cover the case where this piece is a "Knight" and a is a "Bishop", so additional code would be required for the "equal to" case. The answer in B is not correct because it compares two Strings to see if they are the same String, not the same value. The logic in D and E are incorrect because neither of these takes into account what the current piece is, only what the parameter's type is. In D, if a is a "King", it will be greater than this piece if this piece is not a "King", but will be equal if this piece is a "King" and similarly in E, it does not consider if this piece is a "Pawn" or not. Finally, A would give a syntax error because two Strings cannot be compared using the < operator.
PROBLEM 1. Provide a reason why an instance data would be declared static. ANS: If an instance data is to be shared among all objects of the class, the instance data would be static. As an example, an instance data that counts the number of times something has happened across all objects of the class would be made static. If we are writing a chess game and have a ChessPiece class that includes a method called movePiece, we would want to know how many moves a player has made, but not necessarily how many times a single piece has been moved. So, all of the ChessPieces share a numberOfTimesMoved instance data that is incremented by any ChessPiece whenever it is moved.
2. Provide a reason why a method would be declared static. ANS: A method is declared static if it might be used, not by the current object, but by any objects of the class. That is, the method does not require access to any single object's instance data. Consider a class called Point that consists of an x and y coordinate. To determine the distance between two Points, we could make a static computeDistance method. It is passed two Points as parameters and computes the distance. 3. Explain the difference between implementing an interface and a derived class. ANS: Implementing an interface means that you are adding to your class any mechanisms defined in an abstract class. Your class essentially is expanded to contain those items defined in the interface class but you have to implement any of those items that are abstract. The appeal is that other objects might call upon your class to use the interface methods without knowing anything else about your class. The derived class is similar in that you are gaining items previously defined, although in this case, those items are defined in the parent class (as long as those items are protected or public) and you do not have to implement any of them unless you want to redefine them. One difference between the two is that the interface cannot be instantiated directly. Another difference is that your class "inherits" abstract methods from the interface class as opposed to implemented methods from a super class. 4. Define an interface class that contains two int constants, X = 5 and Y = 10 and one int method called useXY which receives no parameters. Call your interface class XYClass. ANS: public interface XYClass { public final int X = 5; public final int Y = 10; public int useXY(); } 5. Assume a class Foo implements Comparable. Without knowing anything else about the Foo class, write an equals method that returns true if the Foo parameter passed to this Foo is equal to this Foo as determined by using the implementation of Comparable. ANS: public boolean equals(Foo a) { if(compareTo(a)) = = 0) return true; else return false;
} Code Description Ch 07-1 Consider a class called ChessPiece. This class has two instance data, String type and int player. The variable type will store "King", "Queen", "Bishop", etc. and the int player will store 0 or 1 depending on whose piece it is. We wish to implement Comparable for the ChessPiece class. Assume that, the current ChessPiece is compared to a ChessPiece passed as a parameter. Pieces are ordered as follows: "Pawn" is a lesser piece to a "Knight" a "Bishop" and "Knight" are equivalent for this example both "Bishop" and "Knight" are lesser pieces to a "Rook" a "Rook" is a lesser piece to a "Queen" a "Queen" is a lesser piece to a "King". 6. Refer to Code Description Ch 07-1: To implement Comparable for the ChessPiece class, the current ChessPiece's type is compared to a ChessPiece passed as a parameter. The method should return 0 if the types are equal, -1 if this piece's type is a lesser piece than the parameter's type, and 1 if this piece's type is a greater piece than the parameter's type. Create this code. ANS: public int compareTo(ChessPiece a) { if (this.type.equals(a.returnType())|| (this.type.equals("Knight")&&a.returnType().equals("Bishop")) ||(this.type.equals("Bishop")&&a.returnType().equals("Knight"))) return 0; else if (this.type.equals("King")) return 1; else if (a.returnType().equals("King")) return-1; else if (this.type.equals("Queen")) return 1; else if (a.returnType().equals("Queen")) return -1; else if (this.type.equals("Rook")) return 1; else if (a.returnType().equals("Rook")) return -1; else if (this.type.equals("Knight")||(this.type.equals("Bishop")) return 1; else if (a.returnType().equals("Knight")||(a.returnType().equals("Bishop")) return -1; } 7. Refer to Code Description Ch 07-1: Write a static method that is passed two ChessPieces and determines if the two pieces are owned by the same player. It should return true or false.
ANS: public static boolean samePlayer(ChessPiece p1, ChessPiece p2) { return (p1.returnPlayer( ) = = p2.returnPlayer( )); } 8. In what way is black-box testing better than glass-box testing? In what way is glass-box testing better than black-box testing? ANS: Black-box testing is superior because the tester knows nothing of the software and so will test the software without preconceived ideas of where errors might exist. The tester is testing the software blindly, much as a user will use the software–without intimate knowledge of how the software works. The result should be that if errors exist that a user might stumble across, the tester should find them. While black-box testing of software has the advantage that the tester operates much like the users are expected to, the disadvantage is that it is a blind test, but there are times when knowledge of how the software functions could be useful. If programmers suspect that some awkward or difficult implementation may be buggy, then spending more time testing that portion of the software is advantageous. This form of testing requires knowledge of how the software works. So, both black-box and glass-box testing have their own advantages and disadvantages. 9. Write code that outputs all of the int values between 1 and 100 with five values per line, and each of those five values spaced out equally. Use a single for loop to solve this problem. ANS: for (int j = 1; j <= 100; j++) { System.out.print(j + "\t"); if (j % 5 == 0) System.out.println( ); }
Java Software Solutions, 9e (Lewis/Loftus) Chapter 8 Arrays TRUE/FALSE 1. Arrays have a built-in toString method that returns all the elements in the array as one String with \n inserted between each element. ANS: F Arrays are objects and so they inherit from the Object class. The Object class does have a toString method. However, Object's toString method does not return the value(s) stored in the Object but rather the value of the reference variable. So, toString used on an array will not return the values stored in the array, but instead a meaningless set of characters. 2. A command-line argument is data that is included on the command line when the interpreter is invoked to execute the program. ANS: T 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. 3. Java arrays can store primitive types and Strings but cannot store any type of Object other than Strings. ANS: F Java arrays can store references to any type of class. 4. A Java main method uses the parameter (String[] variable) so that a user can run the program and supply command-line parameters. Since the parameter is a String array, however, the user does not have to supply any parameters. ANS: T The main method requires the parameter in case a programmer wishes to permit the user to supply command-line parameters. Anything entered at the command line after the Java command will then be accepted as the command line parameter. If it is several words separated by spaces, then each word is stored as a separate String array element. For instance, "java foo.class hi there" would store "hi" in variable[0] and "there" in variable[1] for possible use by the program. 5. An array index cannot be a float, double, boolean, or String. ANS: T An array index must be an int type or a value that can be widened to an int so char, byte, and short are also permissable.
6. Given the following statement, where CD is a previously defined class, then mycollection[5] is a CD object. CD[] mycollection = new CD[200]; ANS: T The variable mycollection has been declared as an array of CD objects, so mycollection[5] is the 6th CD in the the array, and since a CD is an object, mycollection[5] is a CD object. 7. It is possible to sort an array of int, float, double or String, but not an array of an Object class. ANS: F It is possible to sort any type of array as long as the type has some mechanism to compare two elements and determine their proper ordering (less than, equal, greater than). 8. In Java an array can only store one type of data. ANS: T Arrays are known as homogeneous types. This means that the type of value stored in the array must be the same for every element. The type is determined by the declaration. 9. In a two-dimensional array, both dimensions must have the same number of elements, as in my_array[10][10]. ANS: F In Java, the dimensions can have any number of positive elements, so it is possible to have a twodimensional array such as my_array[5][10]. 10. An array, when instantiated, is fixed in size but an ArrayList can dynamically change in size when new elements are added to it. ANS: T A drawback of an array is its fixed size. Once instantiated, it is fixed in size and so, if a program tries to add more elements than the size of the array, it results in an Exception being thrown. The ArrayList is a class that uses an array and automatically creates a larger array, copying the old array into the new array so that the ArrayList can be larger as needed. While this gets around the problem of a thrown Exception, it does lead to poorer performance because of having to copy from one array to another every time the ArrayList size is increased. 11. Just as arrays can only have a fixed number of elements, set at the time the array is declared, a parameter list also can only have a fixed number of elements, set at the time a method is declared. ANS: F Java provides special notation for variable length parameter lists. The ellipsis (...) is used to specify a variable length parameter list. 12. A ragged array is a multidimensional array whose initial indices don't all start at zero.
ANS: F A ragged array is a multidimensional array whose lengths are not all equal. The initial index of all arrays in Java must start at zero. 13. So long as one is only accessing the elements of an ArrayList, its efficiency is about the same as that of an array. It's only when one begins to insert or remove elements towards the front portion of an ArrayList that its efficiency deteriorates. ANS: T ArrayLists are implemented as arrays, so, as long as one is only accessing elements of an ArrayList the efficiency is about the same as for an array. But, when insertions or deletions towards the front portion of an ArrayList occur, that is when a significant amount of element copying must take place, thus decreasing its efficiency.
MULTIPLE CHOICE 1. Which of the following is a legal way to declare and instantiate an array of ten Strings? a. b. c. d. e.
String s = new String(10); String[10] s = new String; String[] s = new String[10]; String s = new String[10]; String[] s = new String; e
ANS: C Declaring an array is done by type[] variable. Instantiating the array is done by variable = new type[dimension] where dimension is the size of the array. 2. In Java, arrays are a. b. c. d.
primitive data types objects interfaces primitive data types if the type stored in the array is a primitive data type and objects if the type stored in the array is an object e. Strings ANS: B In Java, arrays are implemented as objects. The variable is a reference variable to the block of memory that stores the entire array. However, arrays are accessed using the notation name[index] rather than by message passing. Code Example Ch 08-1 Assume an int array, values, that is filled to capacity with the following values:
| 18
9 |
|
4
|
12
|
2
|
6
|
8
|
3. Refer to Code Example Ch 08-1: What is returned by values[3]? a. b. c. d. e.
9 12 2 6 3
ANS: C Java array indices, like those in most languages, start at 0, so values[3] is really the fourth array element, which is 2. 4. Refer to Code Example Ch 08-1: What is returned by values.length? a. b. c. d. e.
0 5 6 7 18
ANS: D The length operator for an array returns the size of the array. The Code Example shows that that values stores 7 elements and since it is full, the size of values is 7. 5. Refer to Code Example Ch 08-1: Which of the following loops would adequately add 1 to each element stored in values? a. b. c. d. e.
for (j=1; j<values.length; j++) values[j]++; for (j=0; j<values.length; j++) values[j]++; for (j=0; j<=values.length; j++) values[j]++; for (j=0; j<values.length-1; j++) values[j]++; for (j=1; j<values.length-1; j++) values[j]++;
ANS: B The first array element is values[0], so the for loop must start at 0, not 1. There are values.length elements in the array where the last element is at values.length-1, so the for loop must stop before reaching values.length. This is the case in B. In D, the for loop stops one before values.length since < is being used to test the condition instead of <=.
6. Refer to Code Example Ch 08-1: What will the following statement do? System.out.println(values[7]); a. b. c. d. e.
output 7 output 18 output nothing cause an ArrayOutOfBoundsException to be thrown cause a syntax error
ANS: D The array has 7 values, but these are indexed values[0] to values[6]. Since values[7] is beyond the bounds of the array, values[7]causes an ArrayOutOfBoundsException to be thrown.
7. The "off-by-one" error associated with arrays arises because a. the first array index is 0 and programmers may start at index 1 or may use a loop that goes one index too far b. the last array index is at length+1 and loops may only iterate to length, missing one c. the last array index is at length-1 and loops may go one too far d. programmers write a loop that goes from 0 to length-1 whereas the array actually goes from 1 to length e. None of these; the "off-by-one" error has nothing to do with arrays ANS: A An array is initialized as new type[x] where x is the size of the array. However, the array has legal indices of 0 to x-1 and so, programmers are often off-by-one because programmers will write code to try to access indices 1 to x. 8. Assume list is an array of int values, temp is some previously initialized value, and c is an int initialized to 0. What does the following code do? for (int j = 0; j < list.length; j++) if (list[j] < temp) c++; a. b. c. d. e.
It finds the smallest value and stores it in temp. It finds the largest value and stores it in temp. It counts the number of elements equal to the smallest value in list It counts the number of elements in list that are less than temp. It sorts the values in list to be in ascending order.
ANS: D The statement if (list[j]<temp) c++; compares each element in list to temp and adds one to c only if the element is less than temp, so it counts the number of elements in list less than temp, storing this result in c. Code Example Ch 08-2 Assume you have an int array, candy, which stores the number of candy bars sold by a group of children where candy[j] is the number of candy bars sold by child j. Assume there are 12 children in all. 9. Refer to Code Example Ch 08-2: What does the following code do? Scanner scan = Scanner.create(System.in); int value1 = scan.nextInt(); int value2 = scan.nextInt(); bars[value1] += value2; a. b. c. d. e.
It adds one to the number of bars sold by child value1 and child value2. It adds one to the number of bars sold by child value1. It adds value1 to the number of bars sold by child value2. It adds value2 to the number of bars sold by child value1. It inputs a new value for the number of bars sold by both child value1 and child value2.
ANS: D
bars[value1] is the number of bars sold by child value1, and += value2 adds to this value the amount input for value2. 10. Refer to Code Example Ch 08-2: Which of the following could be used to compute the total number of bars sold by the children? a. b. c. d. e.
for (int j=0; j<12; j++) sum += candy[j]; for (int j=0; j<12; j++) candy[j] = sum; for (int j=0; j<12; j++) sum = candy[j]; for (int j=0; j<12; j++) sum += [j]; for (int j=0; j<12; j++) [j] += sum;
ANS: A The code in A iterates through all 12 elements of candy, adding each value to sum. The answer in B sets all 12 elements of candy equal to sum, the answer in C sets sum to be each element of candy, resulting in sum = candy[11] and D and E have syntactically invalid code. 11. Refer to Code Example Ch 08-2: What does the following method do? public int question15() { int value1 = 0; int value2 = 0; for (int j = 0; j < 12; j++) if (candy[j] > value1) { value1 = candy[j]; value2 = j; } return value2; } a. b. c. d. e.
It returns the total number of candy bars sold. It returns the total number of children who sold zero candy bars. It returns the total number of children who sold more than zero candy bars. It returns the number of candy bars sold by the child who sold the most candy bars. It returns the index of the child who sold the most candy bars.
ANS: E The loop iterates through all 12 array elements. If a particular value of candy is found to be larger than value1, then this new value is remembered in value1 along with the index of where it was found in value2. As the loop continues, if a new candy value is found to be greater than the current value1, then it is remembered instead, so the loop finds the maximum number of candy bars sold in value1 and the child's index who sold the most in value2. Since value2 is returned, the code returns the index of the child who sold the most. 12. Given the following array declaration and instantiation, what is true about array arr? int[] arr = new int[5]; a. b. c. d.
It stores 5 elements with legal indices between 1 and 5. It stores 5 elements with legal indices between 0 and 4. It stores 4 elements with legal indices between 1 and 4. It stores 6 elements with legal indices between 0 and 5.
e. It stores 5 elements with legal indices between 0 and 5. ANS: B Arrays are instantiated with an int value representing their size, or the number of elements that they can store. So, arr can store 5 elements. Further, all arrays start at index 0 and go to index size1, so arr has legal indices of 0 through 4. 13. If any int array, a, is passed as a parameter to a method, which of the following would adequately define the parameter list for the method header? a. b. c. d. e.
(int[]) (int a[]) (int[] a) (int a) (a[])
ANS: C The parameter is defined much as the variable is originally declared, as type parameter name. Here, the type is int[] and the parameter is a. 14. If int[] x = new int[15]; and the statement x[-1] = 0; is executed, then which of the following Exceptions is thrown? a. b. c. d. e.
IndexOutOfBoundsException ArrayIndexOutOfBoundsException NegativeArraySizeException NullPointException ArithmeticException
ANS: B The array index is out of bounds as the array index can only be between 0 and 14. -1 is an illegal index because it is out of bounds. One might expect the answer to be C, but the NegativeArraySizeException is thrown if an array is being declared with a negative number of elements as in int[] x = new int[-5]; 15. Given the following declarations, which of the following variables are arrays? int[] a, b; int c, d[]; a. b. c. d. e.
a a and b a and d a, b, and d a, b, c, and d
ANS: D The first declaration declares both a and b to be int arrays. The second declaration declares c and d to be ints but in the case of d, an int array. So, a, b, and d are all int arrays. 16. If a and b are both int arrays, then a = b will a. create an alias b. copy all elements of a into b
c. copy the zero element of b into the zero element of a d. return true if each corresponding element of b is equal to each corresponding element of a (that is, if a[0]is equal to b[0], a[1] is equal to b[1]and so forth) and return false otherwise e. return true if a and b are aliases and return false otherwise ANS: A The = is an assignment operator. If the two variables are primitives, than the left-hand variable gets a copy of the right-hand variable. However, since a and b are arrays, the reference variable a is set to the reference variable b, resulting in both a and b referencing the same array in memory, or they are now aliases of each other. 17. Given the following code and assuming list is an int array that stores positive int values only. Which of the following tasks is accomplished by this code? int foo = 0; for (int j =0 ; j < list.length; j++) if (list[j] > foo) foo = list[j]; a. b. c. d. e.
It stores the smallest value of list in foo. It stores the largest value of list in foo. It stores every value of list, one at a time, in list until the loop terminates. It counts the number of elements in list that are greater than foo. It counts the number of elements in list that are less than foo.
ANS: B The condition in the if statement tests to see if the current element of list is greater than foo. If so, it replaces foo. The end result is that every element in list is tested and foo stores the largest element up to that point, so eventually, foo will be the largest value in the array list. 18. If x is a char and values is an int array, then values[x] a. causes a syntax error b. causes an Exception to be thrown c. casts x as an int based on x's position in the alphabet (that is, if x is an 'a' it uses 0 and if x is a 'z' it uses 25) d. casts x as an int based on x's ASCII value (that is, if x is an 'a' it uses 97 and if x is a 'z' it uses 122) e. casts x as an int based on the digit that is stored in x (that is, if x is a '3' it uses 3) but throws an Exception if x does not store a digit ANS: D An array index must be an int value, so normally values[x] would cause a syntax error if x were not an int, but the Java compiler will automatically cast x to be an int if it can be cast. Characters are cast as ints by converting the char value to its equivalent ASCII value. So, if x is 'a', it is cast as the int 97 instead and so values[x] accesses values[97]. 19. What does the following statement do? int[] list = {5, 10, 15, 20}; a. It adds 4 int values to the array list. b. It initializes list to have 20 int values.
c. It initializes list to have 4 int values. d. It declares list but does not initialize it. e. It causes a syntax error because it does not include new int[4] prior to the list of values. ANS: C An array does not have to be instantiated with the new reserved word if it is instantiated with the list of values it is to store. So, list = {5, 10, 15, 20}; causes list to become an array of 4 int values with the values of 5, 10, 15, 20 already initialized. Note that the array is automatically an array of 4 values, so list[n] for any value of n other than 0, 1, 2 or 3 would result in a thrown Exception. 20. Which of the following would initialize a String array names to store the three Strings "Huey", "Duey" and "Louie"? a. b. c. d. e.
String names = {"Huey", "Duey", "Louie"}; String[] names = {"Huey", "Duey", "Louie"}; String[] names = new String{"Huey", "Duey", "Louie"}; String names[3] = {"Huey", "Duey", "Louie"}; String names; names[0] = "Huey"; names[1] = "Duey"; names[2] = "Louie";
ANS: B An array does not have to be instantiated with the reserved word new if it is instantiated with the list of values it is to store. So, names = {"Huey", "Duey", "Louie"}; will create a String array of 3 elements with the three values already initialized. Of the other answers, A does not specify that names is a String array, C should not have the reserved word new, D should not have [3] after names and omits [] after String, and E does not instantiate the array as String[3], and thus , all four of these other answers are syntactically invalid. 21. Which of the following would declare a three-dimensional array called threeD? a. b. c. d. e.
int[3] threeD; int[ , , ] threeD; int[][][] threeD; int [[[]]] threeD; int[] threeD[3];
ANS: C In Java, you can only declare one-dimensional arrays. To create a two-dimensional array, you must declare it as an array of arrays. A three-dimensional array is an array of an array of an array. The proper notation is to declare the type of array using multiple [] brackets in succession, as in int[][] for a two-dimensional array or int[][][] for a three-dimensional array. 22. A polygon object in Java is a. b. c. d. e.
a shape defined as a collection of x, y points a shape defined as a collection of lines a shape defined as a collection of polylines an array of shapes two lines connected by one common point
ANS: A
A polygon object is constructed as a series of points where the shape consists of lines that connect these points. So the shape is defined by the points themselves, denoted through two equal lengthed int arrays and the number of points in the shape.
23. A polyline object in Java is a. b. c. d. e.
an object a shape defined as a collection of lines a shape defined as a collection of polygons an array of shapes a shape defined aa s collection of line segments, defined by their endpoints
ANS: E A polyline is a collection of line segments, defined by their endpoints, sequentially connected to one another.
PROBLEM 1. Write a method to compute the average of an int array and return the value as a double. The int array and the number of elements in the array are both passed as parameters to the method in that order. ANS: public double computeAverage(int[] list, int n) { int sum = 0; for (int j = 0; j < n; j++) sum += list[j]; return (double) ((n > 0) ? sum / n : 0); } 2. The length operator can be used to control a for loop that iterates through each element of an array, as in for (int j = 0; j < list.length; j++) However, this is not necessarily safe. Why not? ANS: It is not necessarily the case that every element in the array has a value stored there. So, list[j] might be an array element that has no value even though j < list.length. So, list.length can only be used safely in an array that is full. 3. Write a method to compute and return the value of max and min where max is the largest element of an int array and min is the smallest element of the int array. The method is passed the int array and an int value that denotes the number of elements in the array. You may assume that the int array has at least 1 element in it. ANS: public int computeDifference(int[] values, int n) {
int min = values[0]; int max = values[0]; for (int j=1;j<n; j++) { if (values[j] < min) min = values[j]; if (values[j] > max) max = values[j]; } return max - min; } 4. The class Name consists of 4 instance data, String title, String first, String middle, and String last. The class has a constructor that is passed all 4 String values and initializes the class appropriately. It has 4 methods and each returns one of the four instance data, called returnTitle(), returnFirst(), returnMiddle and returnLast(). Name[] addressBook = new Name[100]; is performed. Write a method that is passed 4 String parameters corresponding to the title, first, middle, and last of Name, and finds this Name in addressBook and returns the index of where this Name was found, or -1 if the Name was not found. Assume that addressBook stores n entries (n is an int). ANS: public int findName(String title, String first, String middle, String last) { for (int j=0; j<n; j++) if (title.equals(addressBook[j].getTitle() && first.equals(addressBook[j].getFirst() && middle.equals(addressBook[j].getMiddle() && last.equals(addressBook[j].getLast()) return j; return -1; } 5. Write a method that takes an array of Strings as a parameter and the number of elements currently stored in the array, and returns a single String that is the concatenation of all Strings in the array. ANS: public String arrayConcatenator(String[] list, int number) { String allElements = ""; for (int j=0; j<number; j++) allElements += list[j]; return allElements; } 6. Write a method to output all elements of a two-dimensional array of int values as a table of rows and columns. Use "\t" to get elements to line up properly. The method is passed the two-dimensional array and two int values that denote the number of both dimensions (rows followed by columns). ANS:
public void printTable(int[][] matrix, int rows, int columns) { for (int j=0; j<rows; j++) { for (int k=0; k<columns; k++) System.out.print(matrix[j][k] + "\t"); System.out.println(); } } 7. Assume Movie is a class whose objects represents movies. Assume a constructor of the Movie class that accepts two parameters: the name of the movie and the number of minutes the movie runs. Write a declaration for a variable named comedies that is an array of 20 comedy movies. Then write a new statement that sets the third movie in the comedies array to "Club Paradise" that runs 96 minutes. ANS: Movie[] comedies = new Movie[20]; comedies[2] = new Movie("Club Paradise", 96); 8. A two-dimensional array named sales holds the weekly sales for employees in a jewelry store for a year. Write code that prints out a single value that represents the range of sales held in the array. It prints out the value of the highest sales amount minus the value of the lowest amount. Each sales amount is represented as an integer. ANS: int highest = sales[0][0]; int lowest = highest; for (int row = 0; row < sales.length; row++) for (int col = 0; col < sales[row].length; col++) { if (sales[row][col] < lowest) lowest = sales[row][col]; if (sales[row][col] > highest) highest = sales[row][col]; } System.out.println(highest - lowest); 9. How can you tell if a user has double clicked the mouse button? ANS: To see if a user has double clicked the mouse button, you call the getClickCount method of the MouseEvent object passed to the event handler method.
Java Software Solutions, 9e (Lewis/Loftus) Chapter 8 Arrays TRUE/FALSE 1. Arrays have a built-in toString method that returns all the elements in the array as one String with \n inserted between each element. ANS: F Arrays are objects and so they inherit from the Object class. The Object class does have a toString method. However, Object's toString method does not return the value(s) stored in the Object but rather the value of the reference variable. So, toString used on an array will not return the values stored in the array, but instead a meaningless set of characters. 2. A command-line argument is data that is included on the command line when the interpreter is invoked to execute the program. ANS: T 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. 3. Java arrays can store primitive types and Strings but cannot store any type of Object other than Strings. ANS: F Java arrays can store references to any type of class. 4. A Java main method uses the parameter (String[] variable) so that a user can run the program and supply command-line parameters. Since the parameter is a String array, however, the user does not have to supply any parameters. ANS: T The main method requires the parameter in case a programmer wishes to permit the user to supply command-line parameters. Anything entered at the command line after the Java command will then be accepted as the command line parameter. If it is several words separated by spaces, then each word is stored as a separate String array element. For instance, "java foo.class hi there" would store "hi" in variable[0] and "there" in variable[1] for possible use by the program. 5. An array index cannot be a float, double, boolean, or String. ANS: T An array index must be an int type or a value that can be widened to an int so char, byte, and short are also permissable.
6. Given the following statement, where CD is a previously defined class, then mycollection[5] is a CD object. CD[] mycollection = new CD[200]; ANS: T The variable mycollection has been declared as an array of CD objects, so mycollection[5] is the 6th CD in the the array, and since a CD is an object, mycollection[5] is a CD object. 7. It is possible to sort an array of int, float, double or String, but not an array of an Object class. ANS: F It is possible to sort any type of array as long as the type has some mechanism to compare two elements and determine their proper ordering (less than, equal, greater than). 8. In Java an array can only store one type of data. ANS: T Arrays are known as homogeneous types. This means that the type of value stored in the array must be the same for every element. The type is determined by the declaration. 9. In a two-dimensional array, both dimensions must have the same number of elements, as in my_array[10][10]. ANS: F In Java, the dimensions can have any number of positive elements, so it is possible to have a two-dimensional array such as my_array[5][10]. 10. An array, when instantiated, is fixed in size but an ArrayList can dynamically change in size when new elements are added to it. ANS: T A drawback of an array is its fixed size. Once instantiated, it is fixed in size and so, if a program tries to add more elements than the size of the array, it results in an Exception being thrown. The ArrayList is a class that uses an array and automatically creates a larger array, copying the old array into the new array so that the ArrayList can be larger as needed. While this gets around the problem of a thrown Exception, it does lead to poorer performance because of having to copy from one array to another every time the ArrayList size is increased. 11. Just as arrays can only have a fixed number of elements, set at the time the array is declared, a parameter list also can only have a fixed number of elements, set at the time a method is declared. ANS: F Java provides special notation for variable length parameter lists. The ellipsis (...) is used to specify a variable length parameter list. 12. A ragged array is a multidimensional array whose initial indices don't all start at zero.
ANS: F A ragged array is a multidimensional array whose lengths are not all equal. The initial index of all arrays in Java must start at zero. 13. So long as one is only accessing the elements of an ArrayList, its efficiency is about the same as that of an array. It's only when one begins to insert or remove elements towards the front portion of an ArrayList that its efficiency deteriorates. ANS: T ArrayLists are implemented as arrays, so, as long as one is only accessing elements of an ArrayList the efficiency is about the same as for an array. But, when insertions or deletions towards the front portion of an ArrayList occur, that is when a significant amount of element copying must take place, thus decreasing its efficiency.
MULTIPLE CHOICE 1. Which of the following is a legal way to declare and instantiate an array of ten Strings? a. b. c. d. e.
String s = new String(10); String[10] s = new String; String[] s = new String[10]; String s = new String[10]; String[] s = new String; e
ANS: C Declaring an array is done by type[] variable. Instantiating the array is done by variable = new type[dimension] where dimension is the size of the array. 2. In Java, arrays are a. b. c. d.
primitive data types objects interfaces primitive data types if the type stored in the array is a primitive data type and objects if the type stored in the array is an object e. Strings ANS: B In Java, arrays are implemented as objects. The variable is a reference variable to the block of memory that stores the entire array. However, arrays are accessed using the notation name[index] rather than by message passing. Code Example Ch 08-1 Assume an int array, values, that is filled to capacity with the following values:
| 18
9 |
|
4
|
12
|
2
|
6
|
8
|
3. Refer to Code Example Ch 08-1: What is returned by values[3]? a. b. c. d. e.
9 12 2 6 3
ANS: C Java array indices, like those in most languages, start at 0, so values[3] is really the fourth array element, which is 2. 4. Refer to Code Example Ch 08-1: What is returned by values.length? a. b. c. d. e.
0 5 6 7 18
ANS: D The length operator for an array returns the size of the array. The Code Example shows that that values stores 7 elements and since it is full, the size of values is 7. 5. Refer to Code Example Ch 08-1: Which of the following loops would adequately add 1 to each element stored in values? a. b. c. d. e.
for (j=1; j<values.length; j++) values[j]++; for (j=0; j<values.length; j++) values[j]++; for (j=0; j<=values.length; j++) values[j]++; for (j=0; j<values.length-1; j++) values[j]++; for (j=1; j<values.length-1; j++) values[j]++;
ANS: B The first array element is values[0], so the for loop must start at 0, not 1. There are values.length elements in the array where the last element is at values.length-1, so the for loop must stop before reaching values.length. This is the case in B. In D, the for loop stops one before values.length since < is being used to test the condition instead of <=.
6. Refer to Code Example Ch 08-1: What will the following statement do? System.out.println(values[7]); a. b. c. d. e.
output 7 output 18 output nothing cause an ArrayOutOfBoundsException to be thrown cause a syntax error
ANS: D The array has 7 values, but these are indexed values[0] to values[6]. Since values[7] is beyond the bounds of the array, values[7]causes an ArrayOutOfBoundsException to be thrown.
7. The "off-by-one" error associated with arrays arises because a. the first array index is 0 and programmers may start at index 1 or may use a loop that goes one index too far b. the last array index is at length+1 and loops may only iterate to length, missing one c. the last array index is at length-1 and loops may go one too far d. programmers write a loop that goes from 0 to length-1 whereas the array actually goes from 1 to length e. None of these; the "off-by-one" error has nothing to do with arrays ANS: A An array is initialized as new type[x] where x is the size of the array. However, the array has legal indices of 0 to x-1 and so, programmers are often off-by-one because programmers will write code to try to access indices 1 to x. 8. Assume list is an array of int values, temp is some previously initialized value, and c is an int initialized to 0. What does the following code do? for (int j = 0; j < list.length; j++) if (list[j] < temp) c++; a. b. c. d. e.
It finds the smallest value and stores it in temp. It finds the largest value and stores it in temp. It counts the number of elements equal to the smallest value in list It counts the number of elements in list that are less than temp. It sorts the values in list to be in ascending order.
ANS: D The statement if (list[j]<temp) c++; compares each element in list to temp and adds one to c only if the element is less than temp, so it counts the number of elements in list less than temp, storing this result in c. Code Example Ch 08-2 Assume you have an int array, candy, which stores the number of candy bars sold by a group of children where candy[j] is the number of candy bars sold by child j. Assume there are 12 children in all. 9. Refer to Code Example Ch 08-2: What does the following code do? Scanner scan = Scanner.create(System.in); int value1 = scan.nextInt(); int value2 = scan.nextInt(); bars[value1] += value2; a. b. c. d. e.
It adds one to the number of bars sold by child value1 and child value2. It adds one to the number of bars sold by child value1. It adds value1 to the number of bars sold by child value2. It adds value2 to the number of bars sold by child value1. It inputs a new value for the number of bars sold by both child value1 and child value2.
ANS: D
bars[value1] is the number of bars sold by child value1, and += value2 adds to this value the amount input for value2. 10. Refer to Code Example Ch 08-2: Which of the following could be used to compute the total number of bars sold by the children? a. b. c. d. e.
for (int j=0; j<12; j++) sum += candy[j]; for (int j=0; j<12; j++) candy[j] = sum; for (int j=0; j<12; j++) sum = candy[j]; for (int j=0; j<12; j++) sum += [j]; for (int j=0; j<12; j++) [j] += sum;
ANS: A The code in A iterates through all 12 elements of candy, adding each value to sum. The answer in B sets all 12 elements of candy equal to sum, the answer in C sets sum to be each element of candy, resulting in sum = candy[11] and D and E have syntactically invalid code. 11. Refer to Code Example Ch 08-2: What does the following method do? public int question15() { int value1 = 0; int value2 = 0; for (int j = 0; j < 12; j++) if (candy[j] > value1) { value1 = candy[j]; value2 = j; } return value2; } a. b. c. d. e.
It returns the total number of candy bars sold. It returns the total number of children who sold zero candy bars. It returns the total number of children who sold more than zero candy bars. It returns the number of candy bars sold by the child who sold the most candy bars. It returns the index of the child who sold the most candy bars.
ANS: E The loop iterates through all 12 array elements. If a particular value of candy is found to be larger than value1, then this new value is remembered in value1 along with the index of where it was found in value2. As the loop continues, if a new candy value is found to be greater than the current value1, then it is remembered instead, so the loop finds the maximum number of candy bars sold in value1 and the child's index who sold the most in value2. Since value2 is returned, the code returns the index of the child who sold the most. 12. Given the following array declaration and instantiation, what is true about array arr? int[] arr = new int[5]; a. b. c. d.
It stores 5 elements with legal indices between 1 and 5. It stores 5 elements with legal indices between 0 and 4. It stores 4 elements with legal indices between 1 and 4. It stores 6 elements with legal indices between 0 and 5.
e. It stores 5 elements with legal indices between 0 and 5. ANS: B Arrays are instantiated with an int value representing their size, or the number of elements that they can store. So, arr can store 5 elements. Further, all arrays start at index 0 and go to index size-1, so arr has legal indices of 0 through 4. 13. If any int array, a, is passed as a parameter to a method, which of the following would adequately define the parameter list for the method header? a. b. c. d. e.
(int[]) (int a[]) (int[] a) (int a) (a[])
ANS: C The parameter is defined much as the variable is originally declared, as type parameter name. Here, the type is int[] and the parameter is a. 14. If int[] x = new int[15]; and the statement x[-1] = 0; is executed, then which of the following Exceptions is thrown? a. b. c. d. e.
IndexOutOfBoundsException ArrayIndexOutOfBoundsException NegativeArraySizeException NullPointException ArithmeticException
ANS: B The array index is out of bounds as the array index can only be between 0 and 14. -1 is an illegal index because it is out of bounds. One might expect the answer to be C, but the NegativeArraySizeException is thrown if an array is being declared with a negative number of elements as in int[] x = new int[-5]; 15. Given the following declarations, which of the following variables are arrays? int[] a, b; int c, d[]; a. b. c. d. e.
a a and b a and d a, b, and d a, b, c, and d
ANS: D The first declaration declares both a and b to be int arrays. The second declaration declares c and d to be ints but in the case of d, an int array. So, a, b, and d are all int arrays. 16. If a and b are both int arrays, then a = b will a. create an alias b. copy all elements of a into b
c. copy the zero element of b into the zero element of a d. return true if each corresponding element of b is equal to each corresponding element of a (that is, if a[0]is equal to b[0], a[1] is equal to b[1]and so forth) and return false otherwise e. return true if a and b are aliases and return false otherwise ANS: A The = is an assignment operator. If the two variables are primitives, than the left-hand variable gets a copy of the right-hand variable. However, since a and b are arrays, the reference variable a is set to the reference variable b, resulting in both a and b referencing the same array in memory, or they are now aliases of each other. 17. Given the following code and assuming list is an int array that stores positive int values only. Which of the following tasks is accomplished by this code? int foo = 0; for (int j =0 ; j < list.length; j++) if (list[j] > foo) foo = list[j]; a. b. c. d. e.
It stores the smallest value of list in foo. It stores the largest value of list in foo. It stores every value of list, one at a time, in list until the loop terminates. It counts the number of elements in list that are greater than foo. It counts the number of elements in list that are less than foo.
ANS: B The condition in the if statement tests to see if the current element of list is greater than foo. If so, it replaces foo. The end result is that every element in list is tested and foo stores the largest element up to that point, so eventually, foo will be the largest value in the array list. 18. If x is a char and values is an int array, then values[x] a. causes a syntax error b. causes an Exception to be thrown c. casts x as an int based on x's position in the alphabet (that is, if x is an 'a' it uses 0 and if x is a 'z' it uses 25) d. casts x as an int based on x's ASCII value (that is, if x is an 'a' it uses 97 and if x is a 'z' it uses 122) e. casts x as an int based on the digit that is stored in x (that is, if x is a '3' it uses 3) but throws an Exception if x does not store a digit ANS: D An array index must be an int value, so normally values[x] would cause a syntax error if x were not an int, but the Java compiler will automatically cast x to be an int if it can be cast. Characters are cast as ints by converting the char value to its equivalent ASCII value. So, if x is 'a', it is cast as the int 97 instead and so values[x] accesses values[97]. 19. What does the following statement do? int[] list = {5, 10, 15, 20}; a. It adds 4 int values to the array list. b. It initializes list to have 20 int values.
c. It initializes list to have 4 int values. d. It declares list but does not initialize it. e. It causes a syntax error because it does not include new int[4] prior to the list of values. ANS: C An array does not have to be instantiated with the new reserved word if it is instantiated with the list of values it is to store. So, list = {5, 10, 15, 20}; causes list to become an array of 4 int values with the values of 5, 10, 15, 20 already initialized. Note that the array is automatically an array of 4 values, so list[n] for any value of n other than 0, 1, 2 or 3 would result in a thrown Exception. 20. Which of the following would initialize a String array names to store the three Strings "Huey", "Duey" and "Louie"? a. b. c. d. e.
String names = {"Huey", "Duey", "Louie"}; String[] names = {"Huey", "Duey", "Louie"}; String[] names = new String{"Huey", "Duey", "Louie"}; String names[3] = {"Huey", "Duey", "Louie"}; String names; names[0] = "Huey"; names[1] = "Duey"; names[2] = "Louie";
ANS: B An array does not have to be instantiated with the reserved word new if it is instantiated with the list of values it is to store. So, names = {"Huey", "Duey", "Louie"}; will create a String array of 3 elements with the three values already initialized. Of the other answers, A does not specify that names is a String array, C should not have the reserved word new, D should not have [3] after names and omits [] after String, and E does not instantiate the array as String[3], and thus , all four of these other answers are syntactically invalid. 21. Which of the following would declare a three-dimensional array called threeD? a. b. c. d. e.
int[3] threeD; int[ , , ] threeD; int[][][] threeD; int [[[]]] threeD; int[] threeD[3];
ANS: C In Java, you can only declare one-dimensional arrays. To create a two-dimensional array, you must declare it as an array of arrays. A three-dimensional array is an array of an array of an array. The proper notation is to declare the type of array using multiple [] brackets in succession, as in int[][] for a two-dimensional array or int[][][] for a three-dimensional array. 22. A polygon object in Java is a. b. c. d. e.
a shape defined as a collection of x, y points a shape defined as a collection of lines a shape defined as a collection of polylines an array of shapes two lines connected by one common point
ANS: A
A polygon object is constructed as a series of points where the shape consists of lines that connect these points. So the shape is defined by the points themselves, denoted through two equal lengthed int arrays and the number of points in the shape.
23. A polyline object in Java is a. b. c. d. e.
an object a shape defined as a collection of lines a shape defined as a collection of polygons an array of shapes a shape defined aa s collection of line segments, defined by their endpoints
ANS: E A polyline is a collection of line segments, defined by their endpoints, sequentially connected to one another.
PROBLEM 1. Write a method to compute the average of an int array and return the value as a double. The int array and the number of elements in the array are both passed as parameters to the method in that order. ANS: public double computeAverage(int[] list, int n) { int sum = 0; for (int j = 0; j < n; j++) sum += list[j]; return (double) ((n > 0) ? sum / n : 0); } 2. The length operator can be used to control a for loop that iterates through each element of an array, as in for (int j = 0; j < list.length; j++) However, this is not necessarily safe. Why not? ANS: It is not necessarily the case that every element in the array has a value stored there. So, list[j] might be an array element that has no value even though j < list.length. So, list.length can only be used safely in an array that is full. 3. Write a method to compute and return the value of max and min where max is the largest element of an int array and min is the smallest element of the int array. The method is passed the int array and an int value that denotes the number of elements in the array. You may assume that the int array has at least 1 element in it. ANS: public int computeDifference(int[] values, int n) {
int min = values[0]; int max = values[0]; for (int j=1;j<n; j++) { if (values[j] < min) min = values[j]; if (values[j] > max) max = values[j]; } return max - min; } 4. The class Name consists of 4 instance data, String title, String first, String middle, and String last. The class has a constructor that is passed all 4 String values and initializes the class appropriately. It has 4 methods and each returns one of the four instance data, called returnTitle(), returnFirst(), returnMiddle and returnLast(). Name[] addressBook = new Name[100]; is performed. Write a method that is passed 4 String parameters corresponding to the title, first, middle, and last of Name, and finds this Name in addressBook and returns the index of where this Name was found, or -1 if the Name was not found. Assume that addressBook stores n entries (n is an int). ANS: public int findName(String title, String first, String middle, String last) { for (int j=0; j<n; j++) if (title.equals(addressBook[j].getTitle() && first.equals(addressBook[j].getFirst() && middle.equals(addressBook[j].getMiddle() && last.equals(addressBook[j].getLast()) return j; return -1; } 5. Write a method that takes an array of Strings as a parameter and the number of elements currently stored in the array, and returns a single String that is the concatenation of all Strings in the array. ANS: public String arrayConcatenator(String[] list, int number) { String allElements = ""; for (int j=0; j<number; j++) allElements += list[j]; return allElements; } 6. Write a method to output all elements of a two-dimensional array of int values as a table of rows and columns. Use "\t" to get elements to line up properly. The method is passed the two-dimensional array and two int values that denote the number of both dimensions (rows followed by columns). ANS:
public void printTable(int[][] matrix, int rows, int columns) { for (int j=0; j<rows; j++) { for (int k=0; k<columns; k++) System.out.print(matrix[j][k] + "\t"); System.out.println(); } } 7. Assume Movie is a class whose objects represents movies. Assume a constructor of the Movie class that accepts two parameters: the name of the movie and the number of minutes the movie runs. Write a declaration for a variable named comedies that is an array of 20 comedy movies. Then write a new statement that sets the third movie in the comedies array to "Club Paradise" that runs 96 minutes. ANS: Movie[] comedies = new Movie[20]; comedies[2] = new Movie("Club Paradise", 96); 8. A two-dimensional array named sales holds the weekly sales for employees in a jewelry store for a year. Write code that prints out a single value that represents the range of sales held in the array. It prints out the value of the highest sales amount minus the value of the lowest amount. Each sales amount is represented as an integer. ANS: int highest = sales[0][0]; int lowest = highest; for (int row = 0; row < sales.length; row++) for (int col = 0; col < sales[row].length; col++) { if (sales[row][col] < lowest) lowest = sales[row][col]; if (sales[row][col] > highest) highest = sales[row][col]; } System.out.println(highest - lowest); 9. How can you tell if a user has double clicked the mouse button? ANS: To see if a user has double clicked the mouse button, you call the getClickCount method of the MouseEvent object passed to the event handler method.
Java Software Solutions, 9e (Lewis/Loftus) Chapter 9 Inheritance TRUE/FALSE 1. Interface classes cannot be extended but classes that implement interfaces can be extended. ANS: F Any class can be extended whether it is an interface, implements an interface, or neither. The only exception to this is if the class is explicitly modified with the word final in which case it cannot be extended. 2. A derived class has access to all of the methods of the parent class, but only to the protected or public instance data of the parent class. ANS: F Since methods can also be declared as private, any private methods are not accessible by a derived class. So, derived classes only have access to the protected and public methods and instance data of the parent class. 3. If class AParentClass has a protected instance data x, and AChildClass is a derived class of AParentClass, then AChildClass can access x but cannot redefine x to be a different type. ANS: T A derived class can redefine any of the instance data or methods of the parent class. The parent class's version is now hidden, but can be accessed through the use of super, as in super.x. Example Code Ch 09-1 Consider the following class hierarchy:
4. Refer to Example Code Ch 09-1: A is a derived class of X. ANS: F
While A is a descendant of class X, it is not a derived class. Instead, X is a derived class of Y and Y is a derived class of X. A ultimately inherits items from X as long as those items were not overridden by Y. 5. Refer to Example Code Ch 09-1: Y is a derived class of Z. ANS: F Y and Z are known as siblings because they are children of the same parent, but Y and Z may have nothing in common other than what they both inherit from X. 6. Refer to Example Code Ch 09-1: If A, B, Y and Z all contain the same instance data d1, then d1 should be declared in X and inherited into Y, Z, A and B. ANS: T Anything in common between A, B, Y and Z should be declared in X to properly identify that it is a class trait common amongst them. That is, common elements should be defined as high up in the hierarchy as possible. If all descendants of X have the trait (instance data) d1, then it is part of X too. Example Code Ch 09-2 Assume that Poodle is a derived class of Dog and that Dog d = new Dog(...) and Poodle p = new Poodle(...) where the ... are the necessary parameters for the two classes. 7. Refer to Example Code Ch 09-2: The assignment statement d = p; is legal even though d is not a Poodle. ANS: F Since Poodle extends Dog, Dog is a wider class (Poodle is more specific, and therefore narrower). An assignment statement can assign a narrower item into a wider variable (since p is narrower, it can be assigned to d). 8. Refer to Example Code Ch 09-2: The assignment statement p = d; is legal even though p is not a Dog. ANS: F Since Poodle extends Dog, Dog is known as a wider class (Poodle is more specific, and therefore narrower). In any assignment statement, it is possible to take a narrower item and assign it into a wider variable, but it is not possible to assign a wider item into a narrower variable. To accomplish this, a cast must be explicitly made. So, the statement p = d; is illegal although the statement p = (Poodle) d; would be legal. 9. The reserved word, extends, is used to denote a has-a relationship. ANS: F extends is used for inheritance. Inheritance is an is-a relationship, not a has-a relationship. 10. The protected visibility modifier provides the best possible encapsulation that permits inheritance.
ANS: T protected limits visibility as much as possible, while still allowing inheritance. In some ways, protected "advertises" that inheritance should be used. 11. You may use the super reserved word to access a parent class's private members. ANS: F super will allow access to all non-private members of a parent class but, not to the private ones. 12. Java doesn't support multiple inheritance; but it does support the implementation of multiple interfaces. ANS: T Single inheritance is one of Java's strong points. One can achieve most of the advantages of multiple inheritance by implementing multiple interfaces. 13. The JavaFX API offers the programmer controls that allow the user to pick colors or specific dates. ANS: T 14. One way to allow for user interactivity in a program is to use a dialog box. ANS: T 15. In order to use a dialog box to display an alert to the user, you must include the AlertType class. ANS: F In order to use a dialog box to display an alert to the user, you must include the Alert class. AlertType is an enumerated type that will specify the type of alert to be displayed. MULTIPLE CHOICE Example Code Ch 09-4 Given the following partial class definition: public class A1 { public int x; private int y; protected int z; ... } public class A2 extends A1 { protected int a; private int b; ... } public class A3 extends A2 {
private int q; ... } 1. Refer to Example Code Ch 09-4: Which of the following is true with respect to A1, A2, and A3? a. b. c. d. e.
A1 is a subclass of A2 and A2 is a subclass of A3 A3 is a subclass of A2 and A2 is a subclass of A1 A1 and A2 are both subclasses of A3 A2 and A3 are both subclasses of A1 A1, A2 and A3 are all subclasses of the class A
ANS: B The reserved word extends is used to create a subclass. Since A2 extends A1, A2 is a subclass of A1. Since A3 extends A2, A3 is a subclass of A2. 2. Refer to Example Code Ch 09-4: Which of the following lists of instance data are accessible in class A2? a. b. c. d. e.
x, y, z, a, b x, y, z, a x, z, a, b z, a, b a, b
ANS: C Class A2 has access to all of its own instance data (a, b) and any instance data from A1 that were protected (z). Further, all classes, including A2, have access to A1's x since it is public, so x, z, a, b are accessible in A2.
3. Refer to Example Code Ch 09-4: Which of the following lists of instance data are accessible in class A3? a. b. c. d. e.
x, y, z, a, b, q a, b, q a, q x, z, a, q x, a, q
ANS: D Obviously q is accessible in A3. Also, A3 has access to anything inherited from A2, which is a. Additionally, since A2 inherits z from A1, it is also inherited by A3. Finally, since x is public, it is visible to all classes. 4. Refer to Example Code Ch 09-4: Which of the following is true regarding the use of instance data y of class A1? a. b. c. d. e.
It is accessible in A1, A2, and A3 It is accessible in A1 and A2 It is accessible only in A1 It is accessible only in A3 It is accessible to any of the three classes
ANS: C Because it is declared as a private instance data, it is not inherited by any subclasses, and therefore y is only accessible in the class it was defined, A1. 5. The instruction super(); does which of the following? a. b. c. d. e.
It calls the method super as defined in the current class. It calls the method super as defined in the current class's parent class. It calls the method super as defined in java.lang. It calls the constructor as defined in the current class. It calls the constructor as defined in the current class's parent class.
ANS: E
The instruction super(); represents an invocation of something in the current class's parent class. Since there is no message but merely super(), it is an invocation of the parent class's constructor. 6. Inheritance through an extended (derived) class supports which of the following concepts? a. b. c. d. e.
interfaces modulary information hiding code reuse correctness
ANS: D By extending a class and inheriting from it, the new class does not have to reimplement any of those inherited methods or instance data, thus saving the programmer time and effort. So, code reuse is the ability to reuse someone else's code for your benefit by extending it for your needs. 7. Aside from permitting inheritance, the visibility modifier protected is also used to a. b. c. d. e.
permit access to the protected item by any class defined in the same package permit access to the protected item by any static class permit access to the protected item by any parent class ensure that the class cannot throw a NullPointException define abstract elements of an interface
ANS: A The visibility modifier protected is used to control access to the item in a protected (guarded) manner. The protection is that access is restricted to the current class (like private items), classes in the same package, or extended classes of this class. 8. Which of the following is an example of multiple inheritance? a. b. c. d. e.
a computer can be a mainframe or a PC a PC can be a desktop or a laptop a laptop is both a PC and a portable device a portable device is a lightweight device Macintosh and IBM PC are both types of PCs
ANS: C
Multiple inheritance means that a given class inherits from more than one parent class. Of those listed above, a laptop computer inherits properties from both PCs and portable devices. The answers in A, B and E are all examples of single inheritance where a class has at least two children (in A, computer has children mainframe and PC, in B, PC has children desktop and laptop, in E, PC has children Macintosh and IBM PC). 9. Java does not support multiple inheritance but some of the abilities of multiple inheritance are available by a. b. c. d. e.
importing classes implementing interfaces overriding parent class methods creating aliases using public rather than protected or private modifiers
ANS: B Since a class can implement any number of interfaces, that class is in essence using the interface classes as if those interfaces were defined in this class. So this class is inheriting the methods and constants of the interfaces. Further, the class could extend another class and thus inherit directly and indirectly from multiple classes. This is not the exact same as multiple inheritance, but it is as close as Java comes to that concept. 10. If a programmer writes a class that he wants to be extended by another programmer, then this programmer must a. b. c. d. e.
change private methods and instance data to be protected change public methods and instance data to be protected change all the methods to be protected change the class to be protected None of these; the programmer doesn't have to change anything
ANS: A protected items are accessible by any subclass of the class that defines them while private items cannot be accessed by any other class. Therefore, previously defined private items must now be protected. Previously defined public entities should remain public so that all other classes can still access those public entities. Previously defined private items should not be made public because this would allow all classes to access them rather than just child classes. 11. All classes in Java are directly or indirectly subclasses of the __________ class. a. b. c. d. e.
Wrapper String Reference this Object
ANS: E Java requires that all classes have a parent class. If a class does not extend another class, then it, by default, extends the Object class. So the Object class is the parent or ancestor of every other class in Java.
12. Which of the following is not a method of the Object class? a. b. c. d. e.
clone compareTo equals toString All of the above are methods of the Object class
ANS: B The Object class defines clone to create a copy of any object, equals to determine if two objects are the same object, and toString to translate an Object into a String. However, compareTo is not implemented by Object and must be explicitly implemented in any class that wants to implement the Comparable interface. 13. Abstract methods are used when defining a. b. c. d. e.
interface classes derived classes classes that have no constructor arrays
classes that have no methods
ANS: A An interface is a class that has defined some of its components, but leaves other components (methods) for you to implement. So, these components (methods) are referred to as abstract and defined in the interface class as abstract. Example Code Ch 09-5 Consider the following class definition: public class AClass { protected int x; protected int y; public AClass(int a, int b) { x = a; y = b; } public int addEm() { return x + y; } public void changeEm() { x++; y--; } public String toString() { return "" + x + " " + y; } }
14. Refer to Example Code Ch 09-5: You want to extend AClass to BClass. BClass will have a third int instance data, z. Which of the following would best define BClass's constructor? a. public BClass(int a, int b, int c) { super(a, b, c); } b. public BClass(int a, int b, int c) { x = a; y = b; z = c; } c. public BClass(int a, int b, int c) { z = c; } d. public BClass(int a, int b, int c) { super(a, b); z = c; } e. public BClass(int a, int b, int c) { super(); } ANS: D Inheritance is useful because it allows you to reuse code. For this problem, you would want to reuse as much of AClass as possible. Answer D allows you to use AClass's constructor, which expects two int parameters. This sets x and y to be a and b respectively. But since AClass does not have an instance data z, you need to directly assign z to be c in the constructor. The answer in B will also work, but does not reuse any code and so is not as desirable as D. The answers in A and E are syntactically invalid since they do not pass the correct number of parameters to AClass's constructor. Finally, the answer in C only sets z correctly and leaves x and y uninitialized. 15. Refer to Example Code Ch 09-5: You want addEm to now add all three values, return the sum, and changeEm to change x and y, but leave z alone. Which should you do? a. Redefine addEm and changeEm without referencing super.addEm() or super.changeEm(). b. Redefine addEm to return the value of z+super.addEm(), but leave changeEm alone. c. Redefine changeEm to call super.changeEm() and then set z = x + y, but leave addEm alone. d. Redefine addEm to return the value of z+super.addEm() and redefine changeEm to call super.changeEm() and then set z = x + y. e. Redefine changeEm to call super.changeEm() without doing anything to z, and redefine addEm to return super.addEm(). ANS: B
Since super.changeEm() will not affect z and we don't want changeEm()to affect z, there is no need to redefine changeEm()for BClass. Any reference to changeEm()will reference AClass's version which is the same one that BClass will use. But addEm needs redefining because the inherited method addEm calls AClass's addEm which only adds x and y together. Now, we want to add x, y and z together. We can either redefine addEm enntirely, or use super.addEm()and add z to the value returned. The latter approach is better since it reuses previously written code. 16. Refer to Example Code Ch 09-5: Which of the following would best redefine the toString method for BClass? a. public String toString(int z) { return " " + x + " " + y + " }
" + z;
b. ) public String toString() { return super.toString(); } c. public String toString() { return super.toString() + " } d. public String toString() { return super.toString()+" }
" + z;
" x+"
e. public String toString() { return " " + x + " + y + " }
"+y+"
"+z;
" + z;
ANS: C The best way to redefine a method is to reuse the parent class's method and supplement it with the code needed to handle the changes in the subclass. Answer C does this. Answer E accomplishes the same task, but does not reuse any of the parent class's code. Answer B returns only x and y, not z, and answer D returns x, y, and z, while answer A is syntactically invalid because the toString method does not accept a parameter. 17. Which of the following is true about Java classes? a. All classes must have one parent but may have any number of children (derived or extended). b. All classes must have one parent and may have a single child (derived or extended) but may have any number of parent classes. c. All classes can have any number (zero or more) of parent classes and any number of children (derived or extended) classes. d. All classes must have one parent and may have a single child (derived or extended) class. e. All classes can have either zero or one parent class and any number of child (derived or extended) classes.
ANS: A Java supports inheritance but not multiple inheritance, so a Java class can have any number of children but only one parent. Further, since all Java classes inherit either directly or indirectly from the Object class, all Java classes have exactly 1 parent class. 18. The relationship between a parent class and a child class is referred to as a(n) __________ relationship. a. b. c. d. e.
has-a is-a was-a instance-of alias
ANS: B The term "is-a" is used to express that a subclass is a type of parent class. For instance, a graduate student is a type of student. The subclass is a more specific type. The has-a relationship refers to the attributes or elements of a class (for instance, a student has a GPA) and instance-of refers to the relationship between a class and an instantiated object of that class. There is no such thing as a was-a relationship and an alias denotes two variables that reference the same object or instance. 19. Two children of the same parent class are known as a. b. c. d. e.
aliases relatives clones brothers siblings
ANS: E The relationship between two children of the same parent is referred to as siblings (brothers would imply a gender). Clones are copies of the same object and aliases are the same object. Brothers and relatives are not used to define relationships between classes in Java. 20. Which of the following is correct? a. b. c. d. e.
a base class is a parent class or super class a base class is a child class or derived class a child class is a super class of its parent a parent class is a subclass of its child None of these are correct
ANS: A The terms base class, parent class, and super class are synonyms for one another. They all imply that the class will be used as a base for inheritance, and that subsequent classes will extend (inherit from) the base class. 21. Using the reserved word super, one can a. b. c. d.
access a parent class's constructor(s) access a parent class's methods and instance data access a child class's constructor(s) access a child class's methods and instance data
e. Both A and B are correct ANS: E The super reserved word provides a mechanism for accessing a parent class's methods and instance data (whether or not they are hidden). In addition, a parent class's constructor(s) may be accessed using super. So the correct answer is the combination of A and B or E. 22. If you instantiate an abstract class, the class or object you wind up with a. b. c. d. e.
is also an abstract class is a normal class is an interface is a reference to an Object you can't instantiate an abstract class
ANS: E You only can instantiate concrete classes, not abstract ones. But you can extend abstract classes as well as interfaces. Example Code Ch 09-6 Assume that Student, Employee and Retired are all extended classes of Person, and all four classes have different implementations of the method getMoney. Consider the following code where ... indicates the required parameters for the constructors: Person p = new Person(...); int m1 = p.getMoney(); p = new Student(...); int m2 = p.getMoney(); if (m2 < 100000) p = new Employee(...); else if (m1 > 50000) p = new Retired(...); int m3 = p.getMoney();
// assignment 1 // assignment 2
// assignment 3
23. Refer to Example Code Ch 09-6: The reference to getMoney() in assignment 1 is to the class a. b. c. d. e.
Person Student Employee Retired This cannot be determined by examining the code
ANS: A At this point of the program, p is a Person, and so getMoney is a reference to Person's getMoney method. 24. Refer to Example Code Ch 09-6: The reference to getMoney() in assignment 2 is to the class a. b. c. d. e.
Person Student Employee Retired This cannot be determined by examining the code
ANS: B At this point of the program, p is a Student, and so getMoney is a reference to Student's getMoney method. 25. Refer to Example Code Ch 09-6: The reference to getMoney() in assignment 3 is to the class a. b. c. d. e.
Person Student Employee Retired This cannot be determined by examining the code
ANS: E Because there is no way to know if (m2 < 100000) is true or false or if (m1 > 50000) is true or false, it is not known whether p is still a reference to Student or if p now references an Employee or a Retired, and therefore the reference to getMoney()may be to Student, Employee or Retired, but we cannot tell which one just by examining the code.
PROBLEM 1. Consider a class Plane and three subclasses, Glider, PropPlane and Jet. What instance data that should be declared in Plane and what instance data should be declared in each of the three subclasses? Come up with at least 2 instance data unique to each of the four classes given that all instance data of Plane will be inherited into the subclasses. ANS: Plane might include instance data such as size, weight, age, cost, carryingCapacity and maxSpeed. Glider might have instance data of maxAltitude and amountWindNeeded, PropPlane might have instance data of fuelType and numberOfProps and Jet might have instance data of fuelType, numberOfNacelles, and minimumSpeed. 2. Assume a class Triangle has been defined. It has three instance data, Point p1, p2, p3. The class also has a constructor that receives the 3 Points and initializes p1, p2, p3, a toString method that outputs the 3 Points, and a computeSurfaceArea method that calculates the surface area of the Triangle (as an int value). We want to extend this class to represent a 3-dimensional Pyramid, which consists of 4 Points. Since the Pyramid will consist of, in essence, 4 triangles, computeSurfaceArea for the Pyramid will compute 4 times the surface area of the Triangle made up of 3 of those 4 Points. Write the Pyramid class to handle the difference(s) between a Pyramid and the previously defined Triangle. Assume the instance data of Triangle are protected and all methods are public. Also assume that the class Point has a toString method. ANS: public class Pyramid extends Triangle { protected Point p4; public Pyramid(Point a1, Point a2, Point a3, Point a4) { super(a1, a2, a3); p4 = a4;
} public String toString() { super.toString() + p4.toString(); } public int computeSurfaceArea() { return 4 * super.computeSurfaceArea(); } } 3. Explain the difference between implementing an interface and a derived class. ANS: Implementing an interface means that you are adding to your class any mechanisms defined in an abstract class. Your class essentially is expanded to contain those items defined in the interface class but you have to implement any of those items that are abstract. The appeal is that other objects might call upon your class to use the interface methods without knowing anything else about your class. The derived class is similar in that you are gaining items previously defined, although in this case, those items are defined in the parent class (as long as those items are protected or public) and you do not have to implement any of them unless you want to redefine them. One difference between the two is that the interface cannot be instantiated directly. Another difference is that your class "inherits" abstract methods from the interface class as opposed to implemented methods from a super class. 4. A motorcycle inherits properties from both a bicycle and a car. Java does not permit multiple inheritance. Assume that Bicycle and Car have both been declared. Explain how you might go about implementing a Motorcycle as a derived class. ANS: You should extend whichever class is closer to the Motorcycle. For instance, both Motorcycle and Bicycle are two-wheeled vehicles and if this attribute is more important than other attributes, it might make sense to extend Bicycle. However, because Motorcycle shares internal combustion engine, gas fuel, similar speed and driving capabilities to a Car, it would probably make more sense to inherit from Car and override those methods that are most different (for instance, gas mileage varies greatly between cars and motorcycles). The Motorcycle derived class would then inherit the above instance data and methods to calculate and access these values. However, because the Motorcycle is also significantly different from a Car, other instance data and methods would need to be added and some methods redefined. For instance, a mechanism to determine how safe a Car is will differ from a mechanism in determining a Motorcycle's safety. Example Code Ch 09-3 Consider the class Car and the subclass SportsCar. Car has instance data of currentSpeed, type, year, cost, model, color and methods of accelerate, brake, getGasMileage, getInsuranceRate and determineSpeed. 5. Refer to Example Code Ch 09-3: What instance data and methods might you define for SportsCar that are not part of Car?
ANS: A sports car may have a racing stripe, which could be stored in a boolean variable, and a maximum speed, as well as the number of gears. So the SportsCar class might add instance data of stripe, maxSpeed and numberGears. There might be methods to determine how safe the SportsCar is and whether it could win a race or not against another SportsCar. 6. Refer to Example Code Ch 09-3: What methods inherited from Car should SportsCar override? ANS: Because a SportsCar will have different acceleration, the accelerate method should be overridden. Also, determineSpeed might change as will getInsuranceRate. The brake method may or may not differ and getGasMileage will probably stay the same. 7. Consider a class named Name which has four instance data (all Strings): first, last, middle, title. Even though Name inherits the equals method from Object, it would make sense to override it. Why? ANS: Object's version of equal compares two objects to see if they are the same Object, not if they are two Objects that share the same information. Two Name objects should be considered equal if they share the same first, middle, last and title Strings, not just if they are aliases for the same Object in memory. Therefore, the equals method should be overridden. 8. Explain the difference between using an imported class and extending a class. ANS: An imported class lets you use someone else's code, but only as it was intended for use. You have no access to members that are not declared public. An extended class allows you to reuse someone else's code, but you can modify it to work as you wish, and you gain access to members that were declared protected as well as anything that was declared public. 9. Why is it a contradiction for an abstract method to be modified as final or static? ANS: A final method cannot be overridden in derived classes so an abstract final method would have no way of being given a definition in a derived class. A static method can be invoked using the class name without declaring an object of the class. Because abstract methods have no implementation, an abstract static method would make no sense.
Java Software Solutions, 9e (Lewis/Loftus) Chapter 9 Inheritance TRUE/FALSE 1. Interface classes cannot be extended but classes that implement interfaces can be extended. ANS: F Any class can be extended whether it is an interface, implements an interface, or neither. The only exception to this is if the class is explicitly modified with the word final in which case it cannot be extended. 2. A derived class has access to all of the methods of the parent class, but only to the protected or public instance data of the parent class. ANS: F Since methods can also be declared as private, any private methods are not accessible by a derived class. So, derived classes only have access to the protected and public methods and instance data of the parent class. 3. If class AParentClass has a protected instance data x, and AChildClass is a derived class of AParentClass, then AChildClass can access x but cannot redefine x to be a different type. ANS: T A derived class can redefine any of the instance data or methods of the parent class. The parent class's version is now hidden, but can be accessed through the use of super, as in super.x. Example Code Ch 09-1 Consider the following class hierarchy:
4. Refer to Example Code Ch 09-1: A is a derived class of X. ANS: F
While A is a descendant of class X, it is not a derived class. Instead, X is a derived class of Y and Y is a derived class of X. A ultimately inherits items from X as long as those items were not overridden by Y. 5. Refer to Example Code Ch 09-1: Y is a derived class of Z. ANS: F Y and Z are known as siblings because they are children of the same parent, but Y and Z may have nothing in common other than what they both inherit from X. 6. Refer to Example Code Ch 09-1: If A, B, Y and Z all contain the same instance data d1, then d1 should be declared in X and inherited into Y, Z, A and B. ANS: T Anything in common between A, B, Y and Z should be declared in X to properly identify that it is a class trait common amongst them. That is, common elements should be defined as high up in the hierarchy as possible. If all descendants of X have the trait (instance data) d1, then it is part of X too. Example Code Ch 09-2 Assume that Poodle is a derived class of Dog and that Dog d = new Dog(...) and Poodle p = new Poodle(...) where the ... are the necessary parameters for the two classes. 7. Refer to Example Code Ch 09-2: The assignment statement d = p; is legal even though d is not a Poodle. ANS: F Since Poodle extends Dog, Dog is a wider class (Poodle is more specific, and therefore narrower). An assignment statement can assign a narrower item into a wider variable (since p is narrower, it can be assigned to d). 8. Refer to Example Code Ch 09-2: The assignment statement p = d; is legal even though p is not a Dog. ANS: F Since Poodle extends Dog, Dog is known as a wider class (Poodle is more specific, and therefore narrower). In any assignment statement, it is possible to take a narrower item and assign it into a wider variable, but it is not possible to assign a wider item into a narrower variable. To accomplish this, a cast must be explicitly made. So, the statement p = d; is illegal although the statement p = (Poodle) d; would be legal. 9. The reserved word, extends, is used to denote a has-a relationship. ANS: F extends is used for inheritance. Inheritance is an is-a relationship, not a has-a relationship. 10. The protected visibility modifier provides the best possible encapsulation that permits inheritance.
ANS: T protected limits visibility as much as possible, while still allowing inheritance. In some ways, protected "advertises" that inheritance should be used. 11. You may use the super reserved word to access a parent class's private members. ANS: F super will allow access to all non-private members of a parent class but, not to the private ones. 12. Java doesn't support multiple inheritance; but it does support the implementation of multiple interfaces. ANS: T Single inheritance is one of Java's strong points. One can achieve most of the advantages of multiple inheritance by implementing multiple interfaces. 13. The JavaFX API offers the programmer controls that allow the user to pick colors or specific dates. ANS: T 14. One way to allow for user interactivity in a program is to use a dialog box. ANS: T 15. In order to use a dialog box to display an alert to the user, you must include the AlertType class. ANS: F In order to use a dialog box to display an alert to the user, you must include the Alert class. AlertType is an enumerated type that will specify the type of alert to be displayed. MULTIPLE CHOICE Example Code Ch 09-4 Given the following partial class definition: public class A1 { public int x; private int y; protected int z; ... } public class A2 extends A1 { protected int a; private int b; ... } public class A3 extends A2 {
private int q; ... } 1. Refer to Example Code Ch 09-4: Which of the following is true with respect to A1, A2, and A3? a. b. c. d. e.
A1 is a subclass of A2 and A2 is a subclass of A3 A3 is a subclass of A2 and A2 is a subclass of A1 A1 and A2 are both subclasses of A3 A2 and A3 are both subclasses of A1 A1, A2 and A3 are all subclasses of the class A
ANS: B The reserved word extends is used to create a subclass. Since A2 extends A1, A2 is a subclass of A1. Since A3 extends A2, A3 is a subclass of A2. 2. Refer to Example Code Ch 09-4: Which of the following lists of instance data are accessible in class A2? a. b. c. d. e.
x, y, z, a, b x, y, z, a x, z, a, b z, a, b a, b
ANS: C Class A2 has access to all of its own instance data (a, b) and any instance data from A1 that were protected (z). Further, all classes, including A2, have access to A1's x since it is public, so x, z, a, b are accessible in A2.
3. Refer to Example Code Ch 09-4: Which of the following lists of instance data are accessible in class A3? a. b. c. d. e.
x, y, z, a, b, q a, b, q a, q x, z, a, q x, a, q
ANS: D Obviously q is accessible in A3. Also, A3 has access to anything inherited from A2, which is a. Additionally, since A2 inherits z from A1, it is also inherited by A3. Finally, since x is public, it is visible to all classes. 4. Refer to Example Code Ch 09-4: Which of the following is true regarding the use of instance data y of class A1? a. b. c. d. e.
It is accessible in A1, A2, and A3 It is accessible in A1 and A2 It is accessible only in A1 It is accessible only in A3 It is accessible to any of the three classes
ANS: C Because it is declared as a private instance data, it is not inherited by any subclasses, and therefore y is only accessible in the class it was defined, A1. 5. The instruction super(); does which of the following? a. b. c. d. e.
It calls the method super as defined in the current class. It calls the method super as defined in the current class's parent class. It calls the method super as defined in java.lang. It calls the constructor as defined in the current class. It calls the constructor as defined in the current class's parent class.
ANS: E
The instruction super(); represents an invocation of something in the current class's parent class. Since there is no message but merely super(), it is an invocation of the parent class's constructor. 6. Inheritance through an extended (derived) class supports which of the following concepts? a. b. c. d. e.
interfaces modulary information hiding code reuse correctness
ANS: D By extending a class and inheriting from it, the new class does not have to reimplement any of those inherited methods or instance data, thus saving the programmer time and effort. So, code reuse is the ability to reuse someone else's code for your benefit by extending it for your needs. 7. Aside from permitting inheritance, the visibility modifier protected is also used to a. b. c. d. e.
permit access to the protected item by any class defined in the same package permit access to the protected item by any static class permit access to the protected item by any parent class ensure that the class cannot throw a NullPointException define abstract elements of an interface
ANS: A The visibility modifier protected is used to control access to the item in a protected (guarded) manner. The protection is that access is restricted to the current class (like private items), classes in the same package, or extended classes of this class. 8. Which of the following is an example of multiple inheritance? a. b. c. d. e.
a computer can be a mainframe or a PC a PC can be a desktop or a laptop a laptop is both a PC and a portable device a portable device is a lightweight device Macintosh and IBM PC are both types of PCs
ANS: C
Multiple inheritance means that a given class inherits from more than one parent class. Of those listed above, a laptop computer inherits properties from both PCs and portable devices. The answers in A, B and E are all examples of single inheritance where a class has at least two children (in A, computer has children mainframe and PC, in B, PC has children desktop and laptop, in E, PC has children Macintosh and IBM PC). 9. Java does not support multiple inheritance but some of the abilities of multiple inheritance are available by a. b. c. d. e.
importing classes implementing interfaces overriding parent class methods creating aliases using public rather than protected or private modifiers
ANS: B Since a class can implement any number of interfaces, that class is in essence using the interface classes as if those interfaces were defined in this class. So this class is inheriting the methods and constants of the interfaces. Further, the class could extend another class and thus inherit directly and indirectly from multiple classes. This is not the exact same as multiple inheritance, but it is as close as Java comes to that concept. 10. If a programmer writes a class that he wants to be extended by another programmer, then this programmer must a. b. c. d. e.
change private methods and instance data to be protected change public methods and instance data to be protected change all the methods to be protected change the class to be protected None of these; the programmer doesn't have to change anything
ANS: A protected items are accessible by any subclass of the class that defines them while private items cannot be accessed by any other class. Therefore, previously defined private items must now be protected. Previously defined public entities should remain public so that all other classes can still access those public entities. Previously defined private items should not be made public because this would allow all classes to access them rather than just child classes. 11. All classes in Java are directly or indirectly subclasses of the __________ class. a. b. c. d. e.
Wrapper String Reference this Object
ANS: E Java requires that all classes have a parent class. If a class does not extend another class, then it, by default, extends the Object class. So the Object class is the parent or ancestor of every other class in Java.
12. Which of the following is not a method of the Object class? a. b. c. d. e.
clone compareTo equals toString All of the above are methods of the Object class
ANS: B The Object class defines clone to create a copy of any object, equals to determine if two objects are the same object, and toString to translate an Object into a String. However, compareTo is not implemented by Object and must be explicitly implemented in any class that wants to implement the Comparable interface. 13. Abstract methods are used when defining a. b. c. d. e.
interface classes derived classes classes that have no constructor arrays
classes that have no methods
ANS: A An interface is a class that has defined some of its components, but leaves other components (methods) for you to implement. So, these components (methods) are referred to as abstract and defined in the interface class as abstract. Example Code Ch 09-5 Consider the following class definition: public class AClass { protected int x; protected int y; public AClass(int a, int b) { x = a; y = b; } public int addEm() { return x + y; } public void changeEm() { x++; y--; } public String toString() { return "" + x + " " + y; } }
14. Refer to Example Code Ch 09-5: You want to extend AClass to BClass. BClass will have a third int instance data, z. Which of the following would best define BClass's constructor? a. public BClass(int a, int b, int c) { super(a, b, c); } b. public BClass(int a, int b, int c) { x = a; y = b; z = c; } c. public BClass(int a, int b, int c) { z = c; } d. public BClass(int a, int b, int c) { super(a, b); z = c; } e. public BClass(int a, int b, int c) { super(); } ANS: D Inheritance is useful because it allows you to reuse code. For this problem, you would want to reuse as much of AClass as possible. Answer D allows you to use AClass's constructor, which expects two int parameters. This sets x and y to be a and b respectively. But since AClass does not have an instance data z, you need to directly assign z to be c in the constructor. The answer in B will also work, but does not reuse any code and so is not as desirable as D. The answers in A and E are syntactically invalid since they do not pass the correct number of parameters to AClass's constructor. Finally, the answer in C only sets z correctly and leaves x and y uninitialized. 15. Refer to Example Code Ch 09-5: You want addEm to now add all three values, return the sum, and changeEm to change x and y, but leave z alone. Which should you do? a. Redefine addEm and changeEm without referencing super.addEm() or super.changeEm(). b. Redefine addEm to return the value of z+super.addEm(), but leave changeEm alone. c. Redefine changeEm to call super.changeEm() and then set z = x + y, but leave addEm alone. d. Redefine addEm to return the value of z+super.addEm() and redefine changeEm to call super.changeEm() and then set z = x + y. e. Redefine changeEm to call super.changeEm() without doing anything to z, and redefine addEm to return super.addEm(). ANS: B
Since super.changeEm() will not affect z and we don't want changeEm()to affect z, there is no need to redefine changeEm()for BClass. Any reference to changeEm()will reference AClass's version which is the same one that BClass will use. But addEm needs redefining because the inherited method addEm calls AClass's addEm which only adds x and y together. Now, we want to add x, y and z together. We can either redefine addEm enntirely, or use super.addEm()and add z to the value returned. The latter approach is better since it reuses previously written code. 16. Refer to Example Code Ch 09-5: Which of the following would best redefine the toString method for BClass? a. public String toString(int z) { return " " + x + " " + y + " }
" + z;
b. ) public String toString() { return super.toString(); } c. public String toString() { return super.toString() + " } d. public String toString() { return super.toString()+" }
" + z;
" x+"
e. public String toString() { return " " + x + " + y + " }
"+y+"
"+z;
" + z;
ANS: C The best way to redefine a method is to reuse the parent class's method and supplement it with the code needed to handle the changes in the subclass. Answer C does this. Answer E accomplishes the same task, but does not reuse any of the parent class's code. Answer B returns only x and y, not z, and answer D returns x, y, and z, while answer A is syntactically invalid because the toString method does not accept a parameter. 17. Which of the following is true about Java classes? a. All classes must have one parent but may have any number of children (derived or extended). b. All classes must have one parent and may have a single child (derived or extended) but may have any number of parent classes. c. All classes can have any number (zero or more) of parent classes and any number of children (derived or extended) classes. d. All classes must have one parent and may have a single child (derived or extended) class. e. All classes can have either zero or one parent class and any number of child (derived or extended) classes.
ANS: A Java supports inheritance but not multiple inheritance, so a Java class can have any number of children but only one parent. Further, since all Java classes inherit either directly or indirectly from the Object class, all Java classes have exactly 1 parent class. 18. The relationship between a parent class and a child class is referred to as a(n) __________ relationship. a. b. c. d. e.
has-a is-a was-a instance-of alias
ANS: B The term "is-a" is used to express that a subclass is a type of parent class. For instance, a graduate student is a type of student. The subclass is a more specific type. The has-a relationship refers to the attributes or elements of a class (for instance, a student has a GPA) and instance-of refers to the relationship between a class and an instantiated object of that class. There is no such thing as a was-a relationship and an alias denotes two variables that reference the same object or instance. 19. Two children of the same parent class are known as a. b. c. d. e.
aliases relatives clones brothers siblings
ANS: E The relationship between two children of the same parent is referred to as siblings (brothers would imply a gender). Clones are copies of the same object and aliases are the same object. Brothers and relatives are not used to define relationships between classes in Java. 20. Which of the following is correct? a. b. c. d. e.
a base class is a parent class or super class a base class is a child class or derived class a child class is a super class of its parent a parent class is a subclass of its child None of these are correct
ANS: A The terms base class, parent class, and super class are synonyms for one another. They all imply that the class will be used as a base for inheritance, and that subsequent classes will extend (inherit from) the base class. 21. Using the reserved word super, one can a. b. c. d.
access a parent class's constructor(s) access a parent class's methods and instance data access a child class's constructor(s) access a child class's methods and instance data
e. Both A and B are correct ANS: E The super reserved word provides a mechanism for accessing a parent class's methods and instance data (whether or not they are hidden). In addition, a parent class's constructor(s) may be accessed using super. So the correct answer is the combination of A and B or E. 22. If you instantiate an abstract class, the class or object you wind up with a. b. c. d. e.
is also an abstract class is a normal class is an interface is a reference to an Object you can't instantiate an abstract class
ANS: E You only can instantiate concrete classes, not abstract ones. But you can extend abstract classes as well as interfaces. Example Code Ch 09-6 Assume that Student, Employee and Retired are all extended classes of Person, and all four classes have different implementations of the method getMoney. Consider the following code where ... indicates the required parameters for the constructors: Person p = new Person(...); int m1 = p.getMoney(); p = new Student(...); int m2 = p.getMoney(); if (m2 < 100000) p = new Employee(...); else if (m1 > 50000) p = new Retired(...); int m3 = p.getMoney();
// assignment 1 // assignment 2
// assignment 3
23. Refer to Example Code Ch 09-6: The reference to getMoney() in assignment 1 is to the class a. b. c. d. e.
Person Student Employee Retired This cannot be determined by examining the code
ANS: A At this point of the program, p is a Person, and so getMoney is a reference to Person's getMoney method. 24. Refer to Example Code Ch 09-6: The reference to getMoney() in assignment 2 is to the class a. b. c. d. e.
Person Student Employee Retired This cannot be determined by examining the code
ANS: B At this point of the program, p is a Student, and so getMoney is a reference to Student's getMoney method. 25. Refer to Example Code Ch 09-6: The reference to getMoney() in assignment 3 is to the class a. b. c. d. e.
Person Student Employee Retired This cannot be determined by examining the code
ANS: E Because there is no way to know if (m2 < 100000) is true or false or if (m1 > 50000) is true or false, it is not known whether p is still a reference to Student or if p now references an Employee or a Retired, and therefore the reference to getMoney()may be to Student, Employee or Retired, but we cannot tell which one just by examining the code.
PROBLEM 1. Consider a class Plane and three subclasses, Glider, PropPlane and Jet. What instance data that should be declared in Plane and what instance data should be declared in each of the three subclasses? Come up with at least 2 instance data unique to each of the four classes given that all instance data of Plane will be inherited into the subclasses. ANS: Plane might include instance data such as size, weight, age, cost, carryingCapacity and maxSpeed. Glider might have instance data of maxAltitude and amountWindNeeded, PropPlane might have instance data of fuelType and numberOfProps and Jet might have instance data of fuelType, numberOfNacelles, and minimumSpeed. 2. Assume a class Triangle has been defined. It has three instance data, Point p1, p2, p3. The class also has a constructor that receives the 3 Points and initializes p1, p2, p3, a toString method that outputs the 3 Points, and a computeSurfaceArea method that calculates the surface area of the Triangle (as an int value). We want to extend this class to represent a 3-dimensional Pyramid, which consists of 4 Points. Since the Pyramid will consist of, in essence, 4 triangles, computeSurfaceArea for the Pyramid will compute 4 times the surface area of the Triangle made up of 3 of those 4 Points. Write the Pyramid class to handle the difference(s) between a Pyramid and the previously defined Triangle. Assume the instance data of Triangle are protected and all methods are public. Also assume that the class Point has a toString method. ANS: public class Pyramid extends Triangle { protected Point p4; public Pyramid(Point a1, Point a2, Point a3, Point a4) { super(a1, a2, a3); p4 = a4;
} public String toString() { super.toString() + p4.toString(); } public int computeSurfaceArea() { return 4 * super.computeSurfaceArea(); } } 3. Explain the difference between implementing an interface and a derived class. ANS: Implementing an interface means that you are adding to your class any mechanisms defined in an abstract class. Your class essentially is expanded to contain those items defined in the interface class but you have to implement any of those items that are abstract. The appeal is that other objects might call upon your class to use the interface methods without knowing anything else about your class. The derived class is similar in that you are gaining items previously defined, although in this case, those items are defined in the parent class (as long as those items are protected or public) and you do not have to implement any of them unless you want to redefine them. One difference between the two is that the interface cannot be instantiated directly. Another difference is that your class "inherits" abstract methods from the interface class as opposed to implemented methods from a super class. 4. A motorcycle inherits properties from both a bicycle and a car. Java does not permit multiple inheritance. Assume that Bicycle and Car have both been declared. Explain how you might go about implementing a Motorcycle as a derived class. ANS: You should extend whichever class is closer to the Motorcycle. For instance, both Motorcycle and Bicycle are two-wheeled vehicles and if this attribute is more important than other attributes, it might make sense to extend Bicycle. However, because Motorcycle shares internal combustion engine, gas fuel, similar speed and driving capabilities to a Car, it would probably make more sense to inherit from Car and override those methods that are most different (for instance, gas mileage varies greatly between cars and motorcycles). The Motorcycle derived class would then inherit the above instance data and methods to calculate and access these values. However, because the Motorcycle is also significantly different from a Car, other instance data and methods would need to be added and some methods redefined. For instance, a mechanism to determine how safe a Car is will differ from a mechanism in determining a Motorcycle's safety. Example Code Ch 09-3 Consider the class Car and the subclass SportsCar. Car has instance data of currentSpeed, type, year, cost, model, color and methods of accelerate, brake, getGasMileage, getInsuranceRate and determineSpeed. 5. Refer to Example Code Ch 09-3: What instance data and methods might you define for SportsCar that are not part of Car?
ANS: A sports car may have a racing stripe, which could be stored in a boolean variable, and a maximum speed, as well as the number of gears. So the SportsCar class might add instance data of stripe, maxSpeed and numberGears. There might be methods to determine how safe the SportsCar is and whether it could win a race or not against another SportsCar. 6. Refer to Example Code Ch 09-3: What methods inherited from Car should SportsCar override? ANS: Because a SportsCar will have different acceleration, the accelerate method should be overridden. Also, determineSpeed might change as will getInsuranceRate. The brake method may or may not differ and getGasMileage will probably stay the same. 7. Consider a class named Name which has four instance data (all Strings): first, last, middle, title. Even though Name inherits the equals method from Object, it would make sense to override it. Why? ANS: Object's version of equal compares two objects to see if they are the same Object, not if they are two Objects that share the same information. Two Name objects should be considered equal if they share the same first, middle, last and title Strings, not just if they are aliases for the same Object in memory. Therefore, the equals method should be overridden. 8. Explain the difference between using an imported class and extending a class. ANS: An imported class lets you use someone else's code, but only as it was intended for use. You have no access to members that are not declared public. An extended class allows you to reuse someone else's code, but you can modify it to work as you wish, and you gain access to members that were declared protected as well as anything that was declared public. 9. Why is it a contradiction for an abstract method to be modified as final or static? ANS: A final method cannot be overridden in derived classes so an abstract final method would have no way of being given a definition in a derived class. A static method can be invoked using the class name without declaring an object of the class. Because abstract methods have no implementation, an abstract static method would make no sense.
Java Software Solutions, 9e (Lewis/Loftus) Chapter 10 Polymorphism TRUE/FALSE 1. If classes C1 and C2 both implement an interface Cint, which has a method whichIsIt, and if C1 c = new C1(); is performed at one point of the program, then a later instruction c.whichIsIt(); will invoke the whichIsIt method defined in C1. ANS: F Because C1 and C2 implement the same interface, they both implement whichIsIt. The variable c is known as a polymorphic variable, meaning that it can change from being an C1 to a C2. So, the message c.whichIsIt(); may invoke C1's whichIsIt or C2's whichIsIt. There is no way to tell until run-time. 2. It is possible to sort an array of int, float, double or String, but not an array of an Object class such as a CD class. ANS: F It is possible to sort any type of array as long as the type has some mechanism to compare two elements and determine their proper ordering (less than, equal, greater than). So, if the CD class has a compareTo method, then it would be possible to sort them. 3. To swap the 3rd and 4th elements in the int array values, you would do: values[3] = values[4]; values[4] = values[3]; ANS: F This code first copies values[4] into values[3] and then copies values[3] into values[4]. The result is that whatever was stored in values[4] is now stored in both values[3] and values[4]. In order to perform the swap appropriately, you would need a third variable to be used as a temporary storage location, as in int temp = values[3]; values[3] = values[4]; values[4] = temp; 4. A polymorphic reference can refer to different types of objects over time. ANS: T That is what polymorphism is all about: late binding. This means that the same name will be associated with different semantics as the program executes. 5. Java allows one to create polymorphic references using inheritance and using interfaces. ANS: T
Inheritance allows one to use a base variable to refer to various descendent members; the correct one will be used during execution. This is polymorphism in action. Interfaces provide a similar mechanism but use abstract methods rather than the concrete ones used in inheritance. The effect is the same, however. 6. A reference variable can refer to any object created from any class related to it by inheritance. ANS: T This is the technique that one uses to accomplish a polymorphic reference--one whose precise interpretation will change during execution, depending upon the precise object to which the variable refers when it is encountered. 7. The type of the reference, not the type of the object, is used to determine which version of a method is invoked in a polymorphic reference. ANS: F This is backwards. It is the type of the object, not the type of the reference, that determines which method is invoked. 8. The fact that the System.out.println() method is able to handle such a wide variety of objects, and print them correctly, is an example of the polymorphic nature of the println() method. ANS: T Precisely! Since println() is highly polymorphic in nature, it is able to print a wide variety of pre-defined (library) and built-in (primitive) data correctly. 9. An interface reference can refer to any object of any class that implements the interface. ANS: T This is one of the polymorphic functions of using an interface name to declare a reference variable. 10. An class reference can refer to any object of any class that descends from the class. ANS: T This is one of the polymorphic functions of using a class name to declare a reference variable. 11. A method's parameter can be polymorphic, giving the method flexible control of its arguments. ANS: T To accomplish this, merely use an interface name or a base class name to declare the variable. Then the parameter is polymorphic, referring to the correct instance of the class during execution, with the correct semantics being accessed during execution. 12. One of the advantages of the linear search is that it does not require its data to be sorted. ANS: T
Most other search techniques require that their data is sorted in order to achieve greater efficiency (speed). But the linear search makes no such requirement. The result is that the linear search may be slower than one might desire, but it always works, and one never needs to pay the (expensive) price of sorting the data before searching it. 13. The binary search can be used on unsorted data. It will just perform more slowly. ANS: F The binary search only works if the data is sorted. The binary search algorithm proceeds by assuming that there is a strict relationship among every pair of data elements, either ascending or descending. Without this order, the binary search will fail to function correctly. 14. A GUI control that allows the user to specify a numeric value within a bounded range is a spinner. ANS: F The GUI control that allows the user to specify a numeric value within a bounded range is a slider. 15. The spinner GUI control can allow the user to select values that are either numbers or strings. ANS: T A spinner lets the user select a value from a list of predefined options which can be either numeric values or a sequence of strings.
MULTIPLE CHOICE 1. A variable declared to be of one class can later reference an extended class of that class. This variable is known as a. b. c. d. e.
protected derivable cloneable polymorphic None of these; a variable declared to be of one class can never reference any other type of class, even an extended class
ANS: D The term polymorphic means that the variable can have many forms. Under ordinary circumstances, Java is strongly defined. This mean a variable, once declared to be of a type, can never change to be of a different type. The exception to this is that polymorphic variables can be any type of derived class (although not at the same time, the variable can change from one type to another). 2. In order to determine the type that a polymorphic variable refers to, the decision is made a. b. c. d. e.
by the programmer at the time the program is written by the compiler at compile time by the operating system when the program is loaded into memory by the Java run-time environment at run time by the user at run time
ANS: D
The polymorphic variable can take on many different types, but it is not known which type it has taken on until the program is executing. At the time the variable is referenced, then the decision must be made. That decision is made by the run-time environment based on the latest assignment of the variable. 3. What does the following code do? Assume list is an array of int values, temp is some previously initialized int value, and c is an int initialized to 0. for (j = 0; j < list.length; j++) if (list[j] < temp) c++; a. b. c. d. e.
It finds the smallest value and stores it in temp. It finds the largest value and stores it in temp. It counts the number of elements equal to the smallest value in list. It counts the number of elements in list that are less than temp. It sorts the values in list to be in ascending order.
ANS: D The statement if (list[j] < temp) c++; compares each element in list to temp and adds one to c only if the element is less than temp, so it counts the number of elements in list less than temp, storing this result in c. Code Example Ch 10-1 An int array stores the following values:
4. Refer to Code Example Ch 10-1: Which of the following lists of numbers would accurately show the array after the first pass of the selection sort algorithm? a. b. c. d. e.
9, 4, 12, 2, 6, 8, 18 2, 4, 9, 6, 12, 8, 18 2, 4, 12, 9, 6, 8, 18 2, 4, 6, 8, 9, 12, 18 2, 4, 9, 12, 6, 8, 18
ANS: C On each successive pass of selection sort, the smallest of the unsorted values is found and swapped with the current array index (where the current index starts at 0 and goes until the second to last position in the array). On the first pass, the smallest element, 2, is swapped with index 0, so 2 and 9 swap places. 5. Refer to Code Example Ch 10-1: Which of the following lists of numbers would accurately show the array after the second pass of the selection sort algorithm? a. b. c. d. e.
9, 4, 12, 2, 6, 8, 18 2, 4, 9, 6, 12, 8, 18 2, 4, 12, 9, 6, 8, 18 2, 4, 6, 8, 9, 12, 18 2, 4, 9, 12, 6, 8, 18
ANS: C
After one pass, the array would be 2, 4, 12, 9, 6, 8, 18. The second pass would look to swap the item in array index 1 (4) with the smallest value after 2 (4). So, 4 would swap with 4 and the array would stay the same as it was after the first pass. 6. Refer to Code Example Ch 10-1: Which of the following lists of numbers would accurately show the array after the fourth pass of the selection sort algorithm? a. b. c. d. e.
9, 4, 12, 2, 6, 8, 18 2, 4, 6, 9, 12, 8, 18 2, 4, 6, 8, 9, 12, 18 2, 4, 6, 9, 8, 12, 18 2, 4, 6, 8, 12, 9, 18
ANS: E The array would be sorted as follows: First pass: 2, 4, 12, 9, 6, 8, 18. Second pass: 2, 4, 12, 9, 6, 8, 18. Third pass: 2, 4, 6, 9, 12, 8, 18. Fourth pass: 2, 4, 6, 8, 12, 9, 18 7. Refer to Code Example Ch 10-1: How many passes will it take in total for the selection sort to sort this array? a. b. c. d. e.
2 4 5 6 7
ANS: D The selection sort uses two for loops where the outer loop iterates through each array index except for the last one. So it makes a total of n - 1 passes where n is the number of items in the array. Since this array has 7 elements, the outer loop iterates 6 times, or requires 6 passes. You might notice that this array is sorted after only 5 passes, but the selection sort algorithm will still make 6 passes (even if the array had been sorted after only 1 pass, it would still make 6 passes!). 8. We compare sorting algorithms by examining a. b. c. d. e.
the number of instructions executed by the sorting algorithm the number of instructions in the algorithm itself (its length) the types of loops used in the sorting algorithm the amount of memory space required by the algorithm A and D
ANS: E Different sorting algorithms require a different number of instructions when executing. The selection sort, for instance, usually requires more instructions than the insertion sort. So we compare sorting algorithms by the number of instructions that each takes to execute to sort the array. We might count the maximum number of instructions that a sorting algorithm will execute in the worst case, or the minimum number in the best case, or count on average the number of instructions executed. If two sorting algorithms require roughly the same number of instructions to sort an array, then we might also examine the amount of memory space required. 9. Both the insertion sort and the selection sort algorithms have efficiencies on the order of ________ where n is the number of values in the array being sorted.
a. b. c. d. e.
n n * log n n^2 n^3 the insertion sort has an efficiency of n and the selection sort has an efficiency of n^2
ANS: C Both sorting algorithms use two nested loops which both execute approximately n times apiece, giving a complexity of n * n or n^2 for both. 10. What are the main programming mechanisms that constitute object-oriented programming? a. b. c. d. e.
encapsulation, inheritance, polymorphism encapsulation, abstraction, inheritance inheritance, polymorphism, recursion polymorphism, recursion, abstaction None of these
ANS: A Encapsulation is the isolation of portions of code so that they cannot be accidentally modified; inheritance provides for code reuse; polymorphism provides for one-name, many semantics. Abstraction is a useful attribute, but it is not a mechanism. Recursion is a control structure, providing for a different way to express looping or repetition. 11. Which of the following methods will sort an array of floats in ascending order? a. void arrange(float[] ary) { for (int n = 0; n < ary.length; n++) for (int k = n; k < ary.length; k++) if (ary[n] > ary[k]) { float x = ary[n]; ary[n] = ary[k]; ary[k] = x; } } b. void arrange(float[] ary) { for (int n = 0; n < ary.length; n++) for (int k = n; k < ary.length; k++) if (ary[n] < ary[k]) { float x = ary[n]; ary[n] = ary[k]; ary[k] = x; } } c. void arrange(float[] ary) { for (int n = 1; n <= ary.length; n++) for (int k = n; k < ary.length; k++) if (ary[n] > ary[k])
{ float x = ary[n]; ary[n] = ary[k]; ary[k] = x; } } d. void arrange(float[] ary) { for (int n = 0; n < ary.length; n++) for (int k = n; k < ary.length; k++) if (ary[n] > ary[k]) float x = ary[n]; ary[n] = ary[k]; ary[k] = x; } e. None of these ANS: A This code sorts correctly. The other alternatives are missing braces, have incorrect comparisons, or incorrect limits on their loops. 12. Polymorphism is achieved by a. b. c. d. e.
overloading overriding embedding abstraction encapsulation
ANS: B Overloading just provides alternatives for methods with differing parameter lists. Overriding provides for polymorphism, because the appropriate method is invoked depending upon the object that currently is being referenced. Embedding is the enclosing of classes within classes. Abstraction has nothing to do with polymorphism. Encapsulation is achieved using the visibility modifiers. 13. Although insertion sort and selection sort have generally the same performance, the selection sort has an advantage over the insertion sort. What is this advantage? a. The selection sort usually makes fewer comparisons. b. The selection sort usually makes fewer swaps. c. The selection sort usually makes fewer passes. d. The selection sort usually makes fewer selections. e. None of these ANS: B The selection sort may make fewer swaps because at each stage of the process, elements are moved into their final positions and never are moved again. 14. What kind of performance can you expect if you perform a linear search on a sorted array? a. The performance will be about the same as on an unsorted array. b. The performance will be much better than on an unsorted array. c. The performance will be much worse than on an unsorted array.
d. The performance will be worse by about n^2 in this case e. None of these ANS: A The linear search doesn't make any assumptions about whether or not its data is sorted. So, if the data happens to be sorted or not, it won't make any difference. The linear sort will perform roughly as n. 15. Can a program exhibit polymorphism if it only implements early binding? a. Yes, because one form of polymorphism is overloading. b. No, because without late binding, polymorphism cannot be supported. c. Yes, because as long as the program uses inheritance and/or interfaces, it supports polymorphism. d. Yes, because early binding has nothing to do with polymorphism. e. None of these ANS: A While inheritance and interfaces support polymorphism, they only do so if one has late binding. But overloading is a form of polymorphism--one (method) name, multiple bodies--so as long as the program uses overloading, polymorphism is in use. 16. Which of the following is true about a comparison between the selection sort and the insertion sort? a. The selection sort requires more additional memory than the insertion sort. b. The insertion sort requires more additional memory than the selection sort. c. Both methods require approximately the same amount of additional memory as the data they are sorting. d. Neither method requires additional memory. e. None of these ANS: D Both the selection sort and the insertion sort can be implemented "in place." This means that no additional memory is required. The data being sorted is just rearranged within the data array as either sort progresses. 17. What is the output of the following code? (Consider the polymorphic invocation.) public class Inherit { class Figure { void display() { System.out.println("Figure"); } } class Rectangle extends Figure { void display() { System.out.println("Rectangle"); } } class Box extends Figure {
void display() { System.out.println("Box"); } } Inherit() { Figure f = new Figure(); Rectangle r = new Rectangle(); Box b = new Box(); f.display(); f = r; f.display(); f = b; f.display(); } public static void main(String[] args) { new Inherit(); } } a. Figure Rectangle Box b. Rectangle Box c. Figure Figure Figure d. Syntax error. This code won't compile or execute e. None of these ANS: A This is a perfect example of polymorphism. The first invocation of the display method has a Figure as its referent. In the second invocation, the reference has been changed to Rectangle. Then for the third invocation it has been changed to Box. 18. What is the output of the following code? public class Inherit { abstract class Speaker { abstract public void speak(); } class Cat extends Speaker { public void speak() { System.out.println("Woof!"); } } class Dog extends Speaker {
public void speak() { System.out.println("Meow!"); } } Inherit() { Speaker d = new Dog(); Speaker c = new Cat(); d.speak(); c.speak(); } public static void main(String[] args) { new Inherit(); } } a. Woof! Meow! b. Meow! Woof! c. Meow! Meow! d. Woof! Woof! e. None of these ANS: B Carefully watch the assignment of objects to the polymorphic references variables, d and c. Then check to see what Cat and Dog objects actually "speak." 19. What is the output of the following code? public class Inherit { abstract class Figure { void display() { System.out.println("Figure"); } } abstract class Rectangle extends Figure { } class Box extends Rectangle { void display() { System.out.println("Rectangle"); } } Inherit() {
Figure f = (Figure) new Box(); f.display(); Rectangle r = (Rectangle) f; r.display(); } public static void main(String[] args) { new Inherit(); } } a. Rectangle Rectange b. Rectangle Figure c. Figure Rectangle d. Figure Figure e. None of these ANS: A f is a polymorphic reference variable, as is r. Trace through the inheritance structure to see that both references' invocation of the display() method will, indeed, display Rectangle. 20. What is the output of the following code? public class Inherit { class Figure { void display() { System.out.println("Figure"); } } class Rectangle extends Figure { void display() { System.out.println("Rectangle"); } } class Box extends Figure { void display() { System.out.println("Box"); } } Inherit() { Figure f = new Figure(); Rectangle r = new Rectangle(); Box b = new Box(); f.display();
f = r; f.display(); f = b; f.display(); } public static void main(String[] args) { new Inherit(); } } a. Figure Rectange Box b. Rectangle Box c. Figure Figure Figure d. Syntax error; this code won't compile e. None of these ANS: A f, r, and b all are polymorphic reference variables. Each is used to invoke a display() method, so three lines will be printed. Checking to see what instances are actually assigned at the point when the reference variables are used to invoke display, you'll see that answer A is correct. 21. What is the output of the following code? public class Inherit { class Figure { void display() { System.out.println("Figure"); } } class Rectangle extends Figure { void display() { System.out.println("Rectangle"); } void display(String s) { System.out.println(s); } } class Box extends Figure { void display() { System.out.println("Box"); } void display(String s)
{ System.out.println("This is printed: "+s); } } Inherit() { Figure f = new Figure(); Rectangle r = new Rectangle(); Box b = new Box(); f.display(); f = r; f.display("one"); f = b; f.display("two"); } public static void main(String[] args) { new Inherit(); } } a. Figure Rectange b. Figure Rectangle Figure Box c. Figure Figure Figure Figure d. Syntax error; this code won't compile e. None of these ANS: D Examine the f variable, and it's invocation of the display method. Does f's display method accept any parameters? No, so, this code has a syntax error and it won't even compile. 22. What is the output of the following code? public class Inherit { abstract class Figure { void display() { System.out.println("Figure"); } } class Line extends Figure { void display() { System.out.println("Line"); } }
void tryme(Figure f) { f.display(); } Inherit() { Figure f = new Line(); tryme(f); } public static void main(String[] args) { new Inherit(); } } a. b. c. d. e.
Line Figure Shape Syntax error; this code won't compile None of these
ANS: A Inherit's f reference variable is pointing at an instance of Line. So, when the tryme method is invoked f is actually pointing at an instance of Line. So, answer A is correct. 23. Given the following code, class Aggregate is incorrect. Choose the correct line so that this program prints: Granite: weight=25.0 value=4 numKind=7 public class Inherit { abstract class Stone { protected float weight = 13; protected int value = 4; abstract public String toString( ); } class Aggregate { protected int numKind; } class Granite extends Aggregate { Granite() { weight = 25; numKind = 7; } public String toString() { return "Granite: weight=" + weight + " value=" + value + " numKind=" + numKind; } } Inherit()
{ Granite g = new Granite( ); System.out.println(g); } public static void main(String[] args) { new Inherit(); } } a. b. c. d. e.
abstract class Aggregate { abstract class Aggregate extends Granite { abstract class Aggregate extends Stone { class Aggregate extends Stone { None of these
ANS: C
You must both create an abstract class and extend the Stone class. 24. If you instantiate an abstract class, the class or object you wind up with a. b. c. d. e.
is also an abstract class is a normal class is an interface is a reference to an Object you can't instantiate an abstract class
ANS: E You only can instantiate concrete classes, not abstract ones. But you can extend abstract classes as well as interfaces.
PROBLEM 1. Demonstrate how the following array is sorted using insertion sort. Show the array after each pass of the outer loop. [16, 3, 12, 13, 8, 1, 18, 9] ANS: 16, 3, 12, 13, 8, 1, 18, 9 (initial) 3, 16, 12, 13, 8, 1, 18, 9 (pass 1) 3, 12, 16, 13, 8, 1, 18, 9 (pass 2) 3, 12, 13, 16, 8, 1, 18, 9 (pass 3) 3, 8, 12, 13, 16, 1, 18, 9 (pass 4) 1, 3, 8, 12, 13, 16, 18, 9 (pass 5) 1, 3, 8, 12, 13, 16, 18, 9 (pass 6) 1, 3, 8, 9, 12, 13, 16, 18 (pass 7) 2. Demonstrate how the following array is sorted using selection sort. Show the array after each pass of the outer loop. [16, 3, 12, 13, 8, 1, 18, 9] ANS:
16, 3, 12, 13, 8, 1, 18, 9 (initial) 1, 3, 12, 13, 8, 16, 18, 9 (pass 1) 1, 3, 12, 13, 8, 16, 18, 9 (pass 2) 1, 3, 8, 13, 12, 16, 18, 9 (pass 3) 1, 3, 8, 9, 12, 16, 18, 13 (pass 4) 1, 3, 8, 9, 12, 16, 18, 13 (pass 5) 1, 3, 8, 9, 12, 13, 18, 16 (pass 6) 1, 3, 8, 9, 12, 13, 16, 18 (pass 7)
3. Explain how to alter the selection sort algorithm so that it sorts in descending order instead of ascending order. ANS: The inner loop of the selection sort searches for the smallest element in the array from the current position until the end of the array. Instead of looking for the smallest element, look for the largest element. 4. Write an insertion sort method to sort an array of String values (instead of an array of int values). Assume the array is an instance data of the current class called list, and number is an int instance data that stores the number of elements currently stored in list. ANS: public void insertionSortForString() { for (int j = 1; j < number; j++) { String key = list[j]; int position = j; while(position > 0 && list[position-1].compareTo(key)>0) { list[position] = list[position - 1]; position--; } list[position] = key; } } 5. Consider the code shown below. It contains a syntax error, preventing successful compilation and execution. What is the error? public class Inherit { class Figure { void display() { System.out.println("Figure"); } } class Rectangle extends Figure { final void display()
{ System.out.println("Rectangle"); } } class Box extends Rectangle { void display() { System.out.println("Box"); } } Inherit() { Figure f = new Figure(); Rectangle r = new Rectangle(); Box b = new Box(); f.display(); r.display(); b.display(); } public static void main(String[] args) { new Inherit(); } } ANS: Consider the effect of the final modifier. It makes it impossible for that method to be overridden. Box extends Rectangle and attempts to override Rectangle's display method, but, since Rectangle's display method is final, it cannot be overridden. Hence the syntax error. 6. Consider this statement: If you declare a (polymorphic) reference variable, v, to be of type Object, by saying: Object v; then v can refer to any kind of object without restriction. If "object" means an instance of the Object class, is this statement true? Why or why not? If "object" means any kind of Java data, is this statement true? Why or why not? ANS: Java only supports single inheritance, with the base class from which all others are derived are named Object. So, following the rules for inheritance, v may indeed refer to any kind of instance of an Object. But, v may not refer to any kind of data whatsoever. v may not refer to primitive data because primitive data does not descend from Java's root Object class. 7. Is it possible to use both overloading and overriding in the same method? ANS: Yes. A method which is declared in a descendent class certainly can override a method in a parent class so long as the method in the parent class isn't declared private. Now, if the parent class contains several overloaded methods, one can override each of them. This makes the overriding methods overloads of the base functions as well.
Java Software Solutions, 9e (Lewis/Loftus) Chapter 10 Polymorphism TRUE/FALSE 1. If classes C1 and C2 both implement an interface Cint, which has a method whichIsIt, and if C1 c = new C1(); is performed at one point of the program, then a later instruction c.whichIsIt(); will invoke the whichIsIt method defined in C1. ANS: F Because C1 and C2 implement the same interface, they both implement whichIsIt. The variable c is known as a polymorphic variable, meaning that it can change from being an C1 to a C2. So, the message c.whichIsIt(); may invoke C1's whichIsIt or C2's whichIsIt. There is no way to tell until run-time. 2. It is possible to sort an array of int, float, double or String, but not an array of an Object class such as a CD class. ANS: F It is possible to sort any type of array as long as the type has some mechanism to compare two elements and determine their proper ordering (less than, equal, greater than). So, if the CD class has a compareTo method, then it would be possible to sort them. 3. To swap the 3rd and 4th elements in the int array values, you would do: values[3] = values[4]; values[4] = values[3]; ANS: F This code first copies values[4] into values[3] and then copies values[3] into values[4]. The result is that whatever was stored in values[4] is now stored in both values[3] and values[4]. In order to perform the swap appropriately, you would need a third variable to be used as a temporary storage location, as in int temp = values[3]; values[3] = values[4]; values[4] = temp; 4. A polymorphic reference can refer to different types of objects over time. ANS: T That is what polymorphism is all about: late binding. This means that the same name will be associated with different semantics as the program executes. 5. Java allows one to create polymorphic references using inheritance and using interfaces. ANS: T
Inheritance allows one to use a base variable to refer to various descendent members; the correct one will be used during execution. This is polymorphism in action. Interfaces provide a similar mechanism but use abstract methods rather than the concrete ones used in inheritance. The effect is the same, however. 6. A reference variable can refer to any object created from any class related to it by inheritance. ANS: T This is the technique that one uses to accomplish a polymorphic reference--one whose precise interpretation will change during execution, depending upon the precise object to which the variable refers when it is encountered. 7. The type of the reference, not the type of the object, is used to determine which version of a method is invoked in a polymorphic reference. ANS: F This is backwards. It is the type of the object, not the type of the reference, that determines which method is invoked. 8. The fact that the System.out.println() method is able to handle such a wide variety of objects, and print them correctly, is an example of the polymorphic nature of the println() method. ANS: T Precisely! Since println() is highly polymorphic in nature, it is able to print a wide variety of pre-defined (library) and built-in (primitive) data correctly. 9. An interface reference can refer to any object of any class that implements the interface. ANS: T This is one of the polymorphic functions of using an interface name to declare a reference variable. 10. An class reference can refer to any object of any class that descends from the class. ANS: T This is one of the polymorphic functions of using a class name to declare a reference variable. 11. A method's parameter can be polymorphic, giving the method flexible control of its arguments. ANS: T To accomplish this, merely use an interface name or a base class name to declare the variable. Then the parameter is polymorphic, referring to the correct instance of the class during execution, with the correct semantics being accessed during execution. 12. One of the advantages of the linear search is that it does not require its data to be sorted. ANS: T
Most other search techniques require that their data is sorted in order to achieve greater efficiency (speed). But the linear search makes no such requirement. The result is that the linear search may be slower than one might desire, but it always works, and one never needs to pay the (expensive) price of sorting the data before searching it. 13. The binary search can be used on unsorted data. It will just perform more slowly. ANS: F The binary search only works if the data is sorted. The binary search algorithm proceeds by assuming that there is a strict relationship among every pair of data elements, either ascending or descending. Without this order, the binary search will fail to function correctly. 14. A GUI control that allows the user to specify a numeric value within a bounded range is a spinner. ANS: F The GUI control that allows the user to specify a numeric value within a bounded range is a slider. 15. The spinner GUI control can allow the user to select values that are either numbers or strings. ANS: T A spinner lets the user select a value from a list of predefined options which can be either numeric values or a sequence of strings.
MULTIPLE CHOICE 1. A variable declared to be of one class can later reference an extended class of that class. This variable is known as a. b. c. d. e.
protected derivable cloneable polymorphic None of these; a variable declared to be of one class can never reference any other type of class, even an extended class
ANS: D The term polymorphic means that the variable can have many forms. Under ordinary circumstances, Java is strongly defined. This mean a variable, once declared to be of a type, can never change to be of a different type. The exception to this is that polymorphic variables can be any type of derived class (although not at the same time, the variable can change from one type to another). 2. In order to determine the type that a polymorphic variable refers to, the decision is made a. b. c. d. e.
by the programmer at the time the program is written by the compiler at compile time by the operating system when the program is loaded into memory by the Java run-time environment at run time by the user at run time
ANS: D
The polymorphic variable can take on many different types, but it is not known which type it has taken on until the program is executing. At the time the variable is referenced, then the decision must be made. That decision is made by the run-time environment based on the latest assignment of the variable. 3. What does the following code do? Assume list is an array of int values, temp is some previously initialized int value, and c is an int initialized to 0. for (j = 0; j < list.length; j++) if (list[j] < temp) c++; a. b. c. d. e.
It finds the smallest value and stores it in temp. It finds the largest value and stores it in temp. It counts the number of elements equal to the smallest value in list. It counts the number of elements in list that are less than temp. It sorts the values in list to be in ascending order.
ANS: D The statement if (list[j] < temp) c++; compares each element in list to temp and adds one to c only if the element is less than temp, so it counts the number of elements in list less than temp, storing this result in c. Code Example Ch 10-1 An int array stores the following values:
4. Refer to Code Example Ch 10-1: Which of the following lists of numbers would accurately show the array after the first pass of the selection sort algorithm? a. b. c. d. e.
9, 4, 12, 2, 6, 8, 18 2, 4, 9, 6, 12, 8, 18 2, 4, 12, 9, 6, 8, 18 2, 4, 6, 8, 9, 12, 18 2, 4, 9, 12, 6, 8, 18
ANS: C On each successive pass of selection sort, the smallest of the unsorted values is found and swapped with the current array index (where the current index starts at 0 and goes until the second to last position in the array). On the first pass, the smallest element, 2, is swapped with index 0, so 2 and 9 swap places. 5. Refer to Code Example Ch 10-1: Which of the following lists of numbers would accurately show the array after the second pass of the selection sort algorithm? a. b. c. d. e.
9, 4, 12, 2, 6, 8, 18 2, 4, 9, 6, 12, 8, 18 2, 4, 12, 9, 6, 8, 18 2, 4, 6, 8, 9, 12, 18 2, 4, 9, 12, 6, 8, 18
ANS: C
After one pass, the array would be 2, 4, 12, 9, 6, 8, 18. The second pass would look to swap the item in array index 1 (4) with the smallest value after 2 (4). So, 4 would swap with 4 and the array would stay the same as it was after the first pass. 6. Refer to Code Example Ch 10-1: Which of the following lists of numbers would accurately show the array after the fourth pass of the selection sort algorithm? a. b. c. d. e.
9, 4, 12, 2, 6, 8, 18 2, 4, 6, 9, 12, 8, 18 2, 4, 6, 8, 9, 12, 18 2, 4, 6, 9, 8, 12, 18 2, 4, 6, 8, 12, 9, 18
ANS: E The array would be sorted as follows: First pass: 2, 4, 12, 9, 6, 8, 18. Second pass: 2, 4, 12, 9, 6, 8, 18. Third pass: 2, 4, 6, 9, 12, 8, 18. Fourth pass: 2, 4, 6, 8, 12, 9, 18 7. Refer to Code Example Ch 10-1: How many passes will it take in total for the selection sort to sort this array? a. b. c. d. e.
2 4 5 6 7
ANS: D The selection sort uses two for loops where the outer loop iterates through each array index except for the last one. So it makes a total of n - 1 passes where n is the number of items in the array. Since this array has 7 elements, the outer loop iterates 6 times, or requires 6 passes. You might notice that this array is sorted after only 5 passes, but the selection sort algorithm will still make 6 passes (even if the array had been sorted after only 1 pass, it would still make 6 passes!). 8. We compare sorting algorithms by examining a. b. c. d. e.
the number of instructions executed by the sorting algorithm the number of instructions in the algorithm itself (its length) the types of loops used in the sorting algorithm the amount of memory space required by the algorithm A and D
ANS: E Different sorting algorithms require a different number of instructions when executing. The selection sort, for instance, usually requires more instructions than the insertion sort. So we compare sorting algorithms by the number of instructions that each takes to execute to sort the array. We might count the maximum number of instructions that a sorting algorithm will execute in the worst case, or the minimum number in the best case, or count on average the number of instructions executed. If two sorting algorithms require roughly the same number of instructions to sort an array, then we might also examine the amount of memory space required. 9. Both the insertion sort and the selection sort algorithms have efficiencies on the order of ________ where n is the number of values in the array being sorted.
a. b. c. d. e.
n n * log n n^2 n^3 the insertion sort has an efficiency of n and the selection sort has an efficiency of n^2
ANS: C Both sorting algorithms use two nested loops which both execute approximately n times apiece, giving a complexity of n * n or n^2 for both. 10. What are the main programming mechanisms that constitute object-oriented programming? a. b. c. d. e.
encapsulation, inheritance, polymorphism encapsulation, abstraction, inheritance inheritance, polymorphism, recursion polymorphism, recursion, abstaction None of these
ANS: A Encapsulation is the isolation of portions of code so that they cannot be accidentally modified; inheritance provides for code reuse; polymorphism provides for one-name, many semantics. Abstraction is a useful attribute, but it is not a mechanism. Recursion is a control structure, providing for a different way to express looping or repetition. 11. Which of the following methods will sort an array of floats in ascending order? a. void arrange(float[] ary) { for (int n = 0; n < ary.length; n++) for (int k = n; k < ary.length; k++) if (ary[n] > ary[k]) { float x = ary[n]; ary[n] = ary[k]; ary[k] = x; } } b. void arrange(float[] ary) { for (int n = 0; n < ary.length; n++) for (int k = n; k < ary.length; k++) if (ary[n] < ary[k]) { float x = ary[n]; ary[n] = ary[k]; ary[k] = x; } } c. void arrange(float[] ary) { for (int n = 1; n <= ary.length; n++) for (int k = n; k < ary.length; k++) if (ary[n] > ary[k])
{ float x = ary[n]; ary[n] = ary[k]; ary[k] = x; } } d. void arrange(float[] ary) { for (int n = 0; n < ary.length; n++) for (int k = n; k < ary.length; k++) if (ary[n] > ary[k]) float x = ary[n]; ary[n] = ary[k]; ary[k] = x; } e. None of these ANS: A This code sorts correctly. The other alternatives are missing braces, have incorrect comparisons, or incorrect limits on their loops. 12. Polymorphism is achieved by a. b. c. d. e.
overloading overriding embedding abstraction encapsulation
ANS: B Overloading just provides alternatives for methods with differing parameter lists. Overriding provides for polymorphism, because the appropriate method is invoked depending upon the object that currently is being referenced. Embedding is the enclosing of classes within classes. Abstraction has nothing to do with polymorphism. Encapsulation is achieved using the visibility modifiers. 13. Although insertion sort and selection sort have generally the same performance, the selection sort has an advantage over the insertion sort. What is this advantage? a. The selection sort usually makes fewer comparisons. b. The selection sort usually makes fewer swaps. c. The selection sort usually makes fewer passes. d. The selection sort usually makes fewer selections. e. None of these ANS: B The selection sort may make fewer swaps because at each stage of the process, elements are moved into their final positions and never are moved again. 14. What kind of performance can you expect if you perform a linear search on a sorted array? a. The performance will be about the same as on an unsorted array. b. The performance will be much better than on an unsorted array. c. The performance will be much worse than on an unsorted array.
d. The performance will be worse by about n^2 in this case e. None of these ANS: A The linear search doesn't make any assumptions about whether or not its data is sorted. So, if the data happens to be sorted or not, it won't make any difference. The linear sort will perform roughly as n. 15. Can a program exhibit polymorphism if it only implements early binding? a. Yes, because one form of polymorphism is overloading. b. No, because without late binding, polymorphism cannot be supported. c. Yes, because as long as the program uses inheritance and/or interfaces, it supports polymorphism. d. Yes, because early binding has nothing to do with polymorphism. e. None of these ANS: A While inheritance and interfaces support polymorphism, they only do so if one has late binding. But overloading is a form of polymorphism--one (method) name, multiple bodies--so as long as the program uses overloading, polymorphism is in use. 16. Which of the following is true about a comparison between the selection sort and the insertion sort? a. The selection sort requires more additional memory than the insertion sort. b. The insertion sort requires more additional memory than the selection sort. c. Both methods require approximately the same amount of additional memory as the data they are sorting. d. Neither method requires additional memory. e. None of these ANS: D Both the selection sort and the insertion sort can be implemented "in place." This means that no additional memory is required. The data being sorted is just rearranged within the data array as either sort progresses. 17. What is the output of the following code? (Consider the polymorphic invocation.) public class Inherit { class Figure { void display() { System.out.println("Figure"); } } class Rectangle extends Figure { void display() { System.out.println("Rectangle"); } } class Box extends Figure {
void display() { System.out.println("Box"); } } Inherit() { Figure f = new Figure(); Rectangle r = new Rectangle(); Box b = new Box(); f.display(); f = r; f.display(); f = b; f.display(); } public static void main(String[] args) { new Inherit(); } } a. Figure Rectangle Box b. Rectangle Box c. Figure Figure Figure d. Syntax error. This code won't compile or execute e. None of these ANS: A This is a perfect example of polymorphism. The first invocation of the display method has a Figure as its referent. In the second invocation, the reference has been changed to Rectangle. Then for the third invocation it has been changed to Box. 18. What is the output of the following code? public class Inherit { abstract class Speaker { abstract public void speak(); } class Cat extends Speaker { public void speak() { System.out.println("Woof!"); } } class Dog extends Speaker {
public void speak() { System.out.println("Meow!"); } } Inherit() { Speaker d = new Dog(); Speaker c = new Cat(); d.speak(); c.speak(); } public static void main(String[] args) { new Inherit(); } } a. Woof! Meow! b. Meow! Woof! c. Meow! Meow! d. Woof! Woof! e. None of these ANS: B Carefully watch the assignment of objects to the polymorphic references variables, d and c. Then check to see what Cat and Dog objects actually "speak." 19. What is the output of the following code? public class Inherit { abstract class Figure { void display() { System.out.println("Figure"); } } abstract class Rectangle extends Figure { } class Box extends Rectangle { void display() { System.out.println("Rectangle"); } } Inherit() {
Figure f = (Figure) new Box(); f.display(); Rectangle r = (Rectangle) f; r.display(); } public static void main(String[] args) { new Inherit(); } } a. Rectangle Rectange b. Rectangle Figure c. Figure Rectangle d. Figure Figure e. None of these ANS: A f is a polymorphic reference variable, as is r. Trace through the inheritance structure to see that both references' invocation of the display() method will, indeed, display Rectangle. 20. What is the output of the following code? public class Inherit { class Figure { void display() { System.out.println("Figure"); } } class Rectangle extends Figure { void display() { System.out.println("Rectangle"); } } class Box extends Figure { void display() { System.out.println("Box"); } } Inherit() { Figure f = new Figure(); Rectangle r = new Rectangle(); Box b = new Box(); f.display();
f = r; f.display(); f = b; f.display(); } public static void main(String[] args) { new Inherit(); } } a. Figure Rectange Box b. Rectangle Box c. Figure Figure Figure d. Syntax error; this code won't compile e. None of these ANS: A f, r, and b all are polymorphic reference variables. Each is used to invoke a display() method, so three lines will be printed. Checking to see what instances are actually assigned at the point when the reference variables are used to invoke display, you'll see that answer A is correct. 21. What is the output of the following code? public class Inherit { class Figure { void display() { System.out.println("Figure"); } } class Rectangle extends Figure { void display() { System.out.println("Rectangle"); } void display(String s) { System.out.println(s); } } class Box extends Figure { void display() { System.out.println("Box"); } void display(String s)
{ System.out.println("This is printed: "+s); } } Inherit() { Figure f = new Figure(); Rectangle r = new Rectangle(); Box b = new Box(); f.display(); f = r; f.display("one"); f = b; f.display("two"); } public static void main(String[] args) { new Inherit(); } } a. Figure Rectange b. Figure Rectangle Figure Box c. Figure Figure Figure Figure d. Syntax error; this code won't compile e. None of these ANS: D Examine the f variable, and it's invocation of the display method. Does f's display method accept any parameters? No, so, this code has a syntax error and it won't even compile. 22. What is the output of the following code? public class Inherit { abstract class Figure { void display() { System.out.println("Figure"); } } class Line extends Figure { void display() { System.out.println("Line"); } }
void tryme(Figure f) { f.display(); } Inherit() { Figure f = new Line(); tryme(f); } public static void main(String[] args) { new Inherit(); } } a. b. c. d. e.
Line Figure Shape Syntax error; this code won't compile None of these
ANS: A Inherit's f reference variable is pointing at an instance of Line. So, when the tryme method is invoked f is actually pointing at an instance of Line. So, answer A is correct. 23. Given the following code, class Aggregate is incorrect. Choose the correct line so that this program prints: Granite: weight=25.0 value=4 numKind=7 public class Inherit { abstract class Stone { protected float weight = 13; protected int value = 4; abstract public String toString( ); } class Aggregate { protected int numKind; } class Granite extends Aggregate { Granite() { weight = 25; numKind = 7; } public String toString() { return "Granite: weight=" + weight + " value=" + value + " numKind=" + numKind; } } Inherit()
{ Granite g = new Granite( ); System.out.println(g); } public static void main(String[] args) { new Inherit(); } } a. b. c. d. e.
abstract class Aggregate { abstract class Aggregate extends Granite { abstract class Aggregate extends Stone { class Aggregate extends Stone { None of these
ANS: C
You must both create an abstract class and extend the Stone class. 24. If you instantiate an abstract class, the class or object you wind up with a. b. c. d. e.
is also an abstract class is a normal class is an interface is a reference to an Object you can't instantiate an abstract class
ANS: E You only can instantiate concrete classes, not abstract ones. But you can extend abstract classes as well as interfaces.
PROBLEM 1. Demonstrate how the following array is sorted using insertion sort. Show the array after each pass of the outer loop. [16, 3, 12, 13, 8, 1, 18, 9] ANS: 16, 3, 12, 13, 8, 1, 18, 9 (initial) 3, 16, 12, 13, 8, 1, 18, 9 (pass 1) 3, 12, 16, 13, 8, 1, 18, 9 (pass 2) 3, 12, 13, 16, 8, 1, 18, 9 (pass 3) 3, 8, 12, 13, 16, 1, 18, 9 (pass 4) 1, 3, 8, 12, 13, 16, 18, 9 (pass 5) 1, 3, 8, 12, 13, 16, 18, 9 (pass 6) 1, 3, 8, 9, 12, 13, 16, 18 (pass 7) 2. Demonstrate how the following array is sorted using selection sort. Show the array after each pass of the outer loop. [16, 3, 12, 13, 8, 1, 18, 9] ANS:
16, 3, 12, 13, 8, 1, 18, 9 (initial) 1, 3, 12, 13, 8, 16, 18, 9 (pass 1) 1, 3, 12, 13, 8, 16, 18, 9 (pass 2) 1, 3, 8, 13, 12, 16, 18, 9 (pass 3) 1, 3, 8, 9, 12, 16, 18, 13 (pass 4) 1, 3, 8, 9, 12, 16, 18, 13 (pass 5) 1, 3, 8, 9, 12, 13, 18, 16 (pass 6) 1, 3, 8, 9, 12, 13, 16, 18 (pass 7)
3. Explain how to alter the selection sort algorithm so that it sorts in descending order instead of ascending order. ANS: The inner loop of the selection sort searches for the smallest element in the array from the current position until the end of the array. Instead of looking for the smallest element, look for the largest element. 4. Write an insertion sort method to sort an array of String values (instead of an array of int values). Assume the array is an instance data of the current class called list, and number is an int instance data that stores the number of elements currently stored in list. ANS: public void insertionSortForString() { for (int j = 1; j < number; j++) { String key = list[j]; int position = j; while(position > 0 && list[position-1].compareTo(key)>0) { list[position] = list[position - 1]; position--; } list[position] = key; } } 5. Consider the code shown below. It contains a syntax error, preventing successful compilation and execution. What is the error? public class Inherit { class Figure { void display() { System.out.println("Figure"); } } class Rectangle extends Figure { final void display()
{ System.out.println("Rectangle"); } } class Box extends Rectangle { void display() { System.out.println("Box"); } } Inherit() { Figure f = new Figure(); Rectangle r = new Rectangle(); Box b = new Box(); f.display(); r.display(); b.display(); } public static void main(String[] args) { new Inherit(); } } ANS: Consider the effect of the final modifier. It makes it impossible for that method to be overridden. Box extends Rectangle and attempts to override Rectangle's display method, but, since Rectangle's display method is final, it cannot be overridden. Hence the syntax error. 6. Consider this statement: If you declare a (polymorphic) reference variable, v, to be of type Object, by saying: Object v; then v can refer to any kind of object without restriction. If "object" means an instance of the Object class, is this statement true? Why or why not? If "object" means any kind of Java data, is this statement true? Why or why not? ANS: Java only supports single inheritance, with the base class from which all others are derived are named Object. So, following the rules for inheritance, v may indeed refer to any kind of instance of an Object. But, v may not refer to any kind of data whatsoever. v may not refer to primitive data because primitive data does not descend from Java's root Object class. 7. Is it possible to use both overloading and overriding in the same method? ANS: Yes. A method which is declared in a descendent class certainly can override a method in a parent class so long as the method in the parent class isn't declared private. Now, if the parent class contains several overloaded methods, one can override each of them. This makes the overriding methods overloads of the base functions as well.
Java Software Solutions, 9e (Lewis/Loftus) Chapter 11 Exceptions TRUE/FALSE 1. All run-time errors throw exceptions. ANS: F Java classifies any throwable object as either an error or an exception, and so no run-time error will throw an exception. Run-time errors cause termination of the program. Exceptions can be handled so that the program continues executing (but only if the exception is handled properly). 2. If an exception is thrown and not caught anywhere in the program, then the program terminates. ANS: T Exceptions are events of interest or are run-time situations that cannot be handled normally without an exception handler. An exception is caught by an associated exception handler. If the exception is thrown but not handled, then the program must terminate. 3. A try statement must have at least one catch statements but could have many catch statements and may or may not have a finally clause. ANS: T All try statements must have at least one catch statement or there is no reason to have the try statement. There can be one catch statement for each type of exception that might be thrown. The programmer may specify as many catch statements as is felt necessary. Further, a try statement may have a finally clause, but does not need one. 4. Programmers can define their own exceptions by extending the Exception class or one of the descendants of this class. ANS: T Java predefines a number of Exception classes so that many of the types of exceptions that can cause a program to terminate are handled. However, Java allows programmers to add to the language by defining their own exceptions for whatever unique situations they might encounter. These new exceptions will either be children of the Exception class, or children of subclasses or descendants of Exception. 5. If an exception arises in a catch statement, and the exception is of the type caught by the catch statement, then the catch statement catches the same exception. For instance, if the following catch statement first catches an ArithmeticException and, while executing, throws another ArithmeticException, it is able to catch the second ArithmeticException as well the first. catch (ArithmeticException ex) {...} ANS: F
An exception causes the current statement to stop executing and control transfers outside to the first catch (after the current statement) that can catch the exception. So a catch statement will not catch exceptions that are thrown from inside of itself although a catch statement can have nested additional try and catch statements. 6. While the Exception class is part of java.lang, IOException is part of java.io. ANS: T Exception is the ancestor class of all Exceptions. One child of Exception is IOException, which is a checked exception that is thrown from various IO methods. So, while the Exception class is defined in the java.lang package, the IOException class is defined with the rest of the IO methods, in java.io. 7. The difference between the throw reserved word and the throws reserved word is that throw is used within a method body, while throws is used within a method header. ANS: T throw is an imperative command that is used within a method to create and throw a new exception. throws is a compiler directive that tells the compiler that the current method may issue a throw that is not caught within the method and thus may escape to an outer level. 8. An ArithmeticException is Throwable. ANS: T It inherits Throwable through RunTimeException and Exception. 9. An ArithmeticException is a checked exception. ANS: F It inherits from RunTimeException so it is unchecked. 10. An unchecked exception is an exception that must either be caught and handled or listed in the throws clause of any method that might throw or propagate it. ANS: F This is basically the definition of a checked, not an unchecked exception. Unchecked exceptions can be ignored completely in the code, if desired. MULTIPLE CHOICE 1. A Java program can handle an exception in several different ways. Which of the following is not a way a Java program might handle an exception? a. b. c. d. e.
ignore the exception handle the exception where it arises using try and catch statements propagate the exception to another method where it can be handled throw the exception to a predefined Exception class to be handled All of these are valid ways to handle an exception
ANS: D
A thrown exception is either caught by the current code if the code is contained inside a try statement and the appropriate catch statement is implemented, or else it is propagated to the method that invoked the method that caused the exception. Then it is caught there in an appropriate catch statement, or else it continues to be propagated through the methods in the opposite order that those methods were invoked. This process stops however once the main method is reached. If not caught there, the exception causes termination of the program (this would be answer A, the exception was ignored). However, an exception is not thrown to an Exception class. 2. An exception can produce a "call stack trace" which lists a. b. c. d.
the active methods in the order that they were invoked the active methods in the opposite order that they were invoked the values of all instance data of the object where the exception was raised the values of all instance data of the object where the exception was raised and all local variables and parameters of the method where the exception was raised e. the name of the exception thrown ANS: B The call stack trace provides the names of the methods as stored on the run-time stack. The method names are removed from the stack in the opposite order that they were placed; that is, the earliest method is placed there first, the next method second, and so forth so that the most recently invoked method is the last item on the stack. Thus, it is the first one removed. The stack trace then displays all active methods in the opposite order that they were called (most recent first). 3. An exception that could also arise in the try statement that does not have an associated catch statement is a. b. c. d. e.
ClassNotFoundException IllegalArgumentException NegativeArraySizeException NullPointerException OutOfMemoryException
ANS: D If the array has not yet been instantiated, then it throws a NullPointerException. The ClassNotFoundException, IllegalArgumentException and OutOfMemoryException will not be thrown since there is no code in the try statement that either refers to some unknown class, uses an argument, or deals with the generation of new memory. The NegativeArraySizeException will only arise when instantiating an array. 4. A finally clause will execute only if the try statement that precedes it does not throw an exception only if the try statement that precedes it throws an exception that is caught only if the try statement that precedes it throws an exception that is not caught only if the try statement that precedes it throws an exception, regardless of whether or not it is caught e. in any circumstance a. b. c. d.
ANS: E A finally clause, if specified (because it is optional) will execute no matter what happens with respect to the try and catch statements.
5. Which of the following messages passed to the String str could throw a StringIndexOutOfBoundsException? a. b. c. d. e.
str length(); str charAt(2); str replace('a', 'A'); str equals(str); Any of these could throw a StringIndexOutOfBoundsException
ANS: B The StringIndexOutOfBoundsException is thrown if a parameter of a String method references a position in the String that is beyond the bounds of the String (i.e. a negative int or an int greater than or equal to the number of characters in the String). This can occur in either charAt or substring methods. Example Code Ch 11-1 public static void main(String[] args) { try { ExceptionThrowerCode etc = new ExceptionThrowerCode(); etc.m1(); etc.m2(); } catch (ArithmeticException ae) { ... } } public class ExceptionThrowerCode { ... public void m1() { ... } public void m2() { try { m3(); } catch(ArithmeticException ae) {...} catch(NullPointerException npe) {...} } public void m3() { try { ... } catch(ArithmeticException ae) {...} } }
6. Refer to Example Code Ch 11-1: If an ArithmeticException arises in the try statement in m3 a. b. c. d. e.
it is caught in main it is caught in m1 it is caught in m2 it is caught in m3 it is not caught and the program terminates
ANS: D The method m3 has a catch statement for an ArithmeticException, so if one arises in the try statement in m3, it is caught in the catch statement in m3. 7. Refer to Example Code Ch 11-1: If a NullPointerException arises in the try statement in m3 a. b. c. d. e.
it is caught in main it is caught in m1 it is caught in m2 it is caught in m3 it is not caught and the program terminates
ANS: C The method m3 has no catch statement for a NullPointerException, and so the exception is propagated to the calling method, m2. Method m2 has a catch statement for a NullPointerException so that is where the exception is caught. 8. Refer to Example Code Ch 11-1: If a NullPointerException arises in the try statement in m1 a. b. c. d. e.
it is caught in main it is caught in m1 it is caught in m2 it is caught in m3 it is not caught and the program terminates
ANS: E The method m1 has no catch statements at all, so any exception is propagated to the calling method, main. The method main only has a catch statement for an ArithmeticException so the NullPointerException is not caught and the program terminates. 9. NullPointerExceptions and ArithmeticExceptions are both derived from which class? a. b. c. d. e.
Error Exception RuntimeException IllegalAccessException CheckedException
ANS: C
Both of these exceptions are children of the RuntimeException class which, itself, is a child of Exception. Error is a throwable object that is different from Exception while IllegalAccessException and CheckedException are children of Exception but not of RuntimeException. 10. In order to have some code throw an exception, which of the following reserved words should you use? a. b. c. d. e.
throw throws try Throwable goto
ANS: A The reserved word throw is used to throw an exception when the exception is detected, as in: if (score < 0) throw new IllegalTestScoreException("Input score " + score + " is negative"); 11. Assume Exceptionname is a checked exception. If a method uses a class that can generate Exceptionname, then either the method must include try and catch statements where a catch statement catches Exceptionname, or the method header must include the statement a. b. c. d. e.
throw Exceptionname throws Exceptionname catch Exceptionname catches Exceptionname implements Exceptionname
ANS: B A checked exception must be caught somewhere and so, if not caught in the method that might generate the exception, the exception must be thrown to whatever called the method. This is accomplished by stating that the method throws Exceptionname. 12. Which of the following is not true of the RuntimeException class? a. All RuntimeException throw checked exceptions. b. All RuntimeException are Throwable objects. c. RuntimeException has child classes ArithmeticException and NullPointerException. d. RuntimeException objects are not Error objects. e. All of these are true ANS: A The answers in B, C and D are all true, RuntimeException are Throwable objects and are not part of the Error class, and two types of RuntimeException are ArithmeticException and NullPointerException. Exceptions that are not RuntimeExceptions include various checked exceptions, but RuntimeExceptions are not checked exceptions. 13. Character streams manage a. byte-sized data
b. c. d. e.
binary data Unicode characters ASCII characters compressed data
ANS: C Character streams are used to manage 16-bit Unicode characters. This differs from a byte stream that is used to manage any kind of byte-sized data, including ASCII characters and binary data of other types. 14. A processing stream is a data stream that a. b. c. d. e.
can manage both input streams and output streams at the same time performs some manipulation or process on the data can only manage input streams operates on input and output devices but not files can manage byte streams and character streams at the same time
ANS: B A data stream represents a particular source or destination stream and is used for input or output. A processing stream is like a data stream where some additional process(es) is(are) added to the input or output. For example, a processing byte stream might input all items from a file and remove any ASCII characters that are not digits so that an input expected to be a number will not throw a NumberFormatException. 15. System.err is a(n) a. b. c. d. e.
input stream GUI dialog box that indicates when an error has arisen object Error subclass RuntimException subclass
ANS: C There are three default streams available in Java: System.in, System.out, and System.err. All of these are objects with System.in being an input stream, System.out being an output stream and System.err being an error stream (which is also an output stream). 16. The Scanner class provides an abstraction for input operations by a. using try and catch statements to catch any IOException instead of throwing the Exception elsewhere b. parsing input lines into individual tokens c. performing conversion operations from String to the appropriate type as specified in the Scanner message d. inputting from the standard input stream if create is called using System.in e. All of these ANS: E
Input into a Java program is difficult because it requires a lot of overhead. The Scanner class implements all of that overhead so that the programmer does not have to see it. Thus, Scanner is an abstraction for performing input operations without the details. These details include importing java.io classes, handling IOExceptions in some way, inputting from the standard input stream, dividing the input into individual tokens and converting each token as needed into the requesting form. 17. The term "exception propagation" means a. an exception is caught by the first catch clause b. an exception not caught by the first catch clause is caught by an outer (enclosing) catch clause c. exceptions are caught, sequentially, by catch clauses in the current try block d. exceptions are always caught by the outermost try block e. None of these explain what exception propagation is ANS: E Exception propagation means that an exception is caught by a matching catch clause at the current try block level, and if none matches, then at the next enclosing try block level, and so forth, until the exception either has been caught by a matching clause or the exception passes out of the main routine and is caught by the Java Virtual Machine. 18. When a program terminates because a thrown exception is not handled, the program a. starts up again automatically b. opens a dialog box which asks the user whether the program should start again, end, or enter a debugging mode c. saves all output to a disk file named runStackTrace.txt d. opens a dialog box for the user to specify a disk filename and all output is stored to that file e. outputs a message indicating what the exception was and where it was thrown ANS: E If a thrown exception is not caught anywhere in the program, the program terminates, displaying the contents of the run stack trace. The first item on the run stack trace is the exception that was thrown and where it was thrown (the line number of the method of the class where the exception was raised) 19. A method that uses the Scanner class to obtain input does not require either catching or throwing an IOException. This is because a. the Scanner class does not call upon any classes that throw checked exceptions b. the Scanner class's methods call input methods in try statements and catch IOExceptions so that they are handled directly in the Scanner class c. the Scanner class uses dialog boxes instead of java.io classes so that it does not have to deal with IOExceptions d. the Scanner class overrides the class IOException making it an unchecked exception e. None of the above; methods do require handling IOExceptions even if thrown by a method in a Scanner class ANS: B By having its own catch (IOException) catch statement, any code in the Scanner class that causes an IOException is caught by the Scanner class so that classes that might use the Scanner class do not have to handle this checked exception.
20. The difference between a checked and an unchecked exception is a. b. c. d. e.
checked exceptions need not be listed in a throws clause unchecked exceptions must be listed in a throws clause neither kind of exception follows the rules of exception propagation an unchecked exception requires no throws clause a checked exception always must be caught by a try block while this is not true for an unchecked exception
ANS: D A checked exception must either be caught or it must be listed in a throws clause. An unchecked exception requires no throws clause. Both kinds of exceptions follow the rules of exception propagation. 21. A disabled component is a. b. c. d. e.
one that is grayed out one that is no longer active one that is still visually apparent but no longer functions if clicked provides an indication of functionality that is not currently available All of these are true
ANS: E Components that are disabled appear grayed out; they are disabled for the moment, but remain visually apparent. They provide an indication of functionality that can/will be enabled at some other point in time.
PROBLEM 1. Explain or provide an example showing how an ArithmeticException could arise. ANS: An ArithmeticException could occur if an arithmetic operation could not take place because of an illegal action such as division by zero or square root of a negative number. 2. Explain or provide an example showing how a NullPointerException could arise. ANS: A NullPointerException could occur if an object was not instantiated (it had the value null) before a message was passed to it. 3. Explain or provide an example showing how a NumberFormatException could arise. ANS: A NumberFormatException could occur if an expected value for a numeric operation was not a legal number, such as trying to parse a String value to create an equivalent int where the String contains a non-digit character. 4. Explain or provide an example showing how an IndexOutOfBoundsException could arise.
ANS: An IndexOutOfBoundsException could occur if a numeric parameter that was used as an index into an object such as an array or a String was out of range, such as charAt(-1). 5. Explain or provide an example showing how an IOException could arise. ANS: An IOException could occur if something happened when inputting from keyboard or inputting or outputting to disk such as a disk was not in disk drive. 6. What are the three standard I/O streams and what purposes do they fulfill? ANS: The three standard I/O streams are System.in, System.out, and System.err. System.in is the standard system input stream. Most usually it is connected to the keyboard. System.out is the standard system output stream. It usually is connected to the display. Both System.in and System.out are used for "normal" input and output. System.err usually is connected to the standard error output. This, too, usually is connected to the display. It is used for the display of warning and error messages that otherwise might become lost due, perhaps, to output redirection. 7. Why might you want to create your own exception class? What purpose would it serve? ANS: If you have a collection of error conditions that pertain to a specific function or group of functions that a portion of a program may generate, it might be very wise to create an exception class for that collection of error conditions. Then you would not need to test explicitly for error conditions within that code. You would protect the code with try-catch blocks. This would make the code far cleaner, easier to understand, and easier to maintain. 8. Explain what happens if an exception is not caught. ANS: 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 time during this propagation but if it propagates out of the main method, the program will terminate.
Java Software Solutions, 9e (Lewis/Loftus) Chapter 11 Exceptions TRUE/FALSE 1. All run-time errors throw exceptions. ANS: F Java classifies any throwable object as either an error or an exception, and so no run-time error will throw an exception. Run-time errors cause termination of the program. Exceptions can be handled so that the program continues executing (but only if the exception is handled properly). 2. If an exception is thrown and not caught anywhere in the program, then the program terminates. ANS: T Exceptions are events of interest or are run-time situations that cannot be handled normally without an exception handler. An exception is caught by an associated exception handler. If the exception is thrown but not handled, then the program must terminate. 3. A try statement must have at least one catch statements but could have many catch statements and may or may not have a finally clause. ANS: T All try statements must have at least one catch statement or there is no reason to have the try statement. There can be one catch statement for each type of exception that might be thrown. The programmer may specify as many catch statements as is felt necessary. Further, a try statement may have a finally clause, but does not need one. 4. Programmers can define their own exceptions by extending the Exception class or one of the descendants of this class. ANS: T Java predefines a number of Exception classes so that many of the types of exceptions that can cause a program to terminate are handled. However, Java allows programmers to add to the language by defining their own exceptions for whatever unique situations they might encounter. These new exceptions will either be children of the Exception class, or children of subclasses or descendants of Exception. 5. If an exception arises in a catch statement, and the exception is of the type caught by the catch statement, then the catch statement catches the same exception. For instance, if the following catch statement first catches an ArithmeticException and, while executing, throws another ArithmeticException, it is able to catch the second ArithmeticException as well the first. catch (ArithmeticException ex) {...} ANS: F
An exception causes the current statement to stop executing and control transfers outside to the first catch (after the current statement) that can catch the exception. So a catch statement will not catch exceptions that are thrown from inside of itself although a catch statement can have nested additional try and catch statements. 6. While the Exception class is part of java.lang, IOException is part of java.io. ANS: T Exception is the ancestor class of all Exceptions. One child of Exception is IOException, which is a checked exception that is thrown from various IO methods. So, while the Exception class is defined in the java.lang package, the IOException class is defined with the rest of the IO methods, in java.io. 7. The difference between the throw reserved word and the throws reserved word is that throw is used within a method body, while throws is used within a method header. ANS: T throw is an imperative command that is used within a method to create and throw a new exception. throws is a compiler directive that tells the compiler that the current method may issue a throw that is not caught within the method and thus may escape to an outer level. 8. An ArithmeticException is Throwable. ANS: T It inherits Throwable through RunTimeException and Exception. 9. An ArithmeticException is a checked exception. ANS: F It inherits from RunTimeException so it is unchecked. 10. An unchecked exception is an exception that must either be caught and handled or listed in the throws clause of any method that might throw or propagate it. ANS: F This is basically the definition of a checked, not an unchecked exception. Unchecked exceptions can be ignored completely in the code, if desired. MULTIPLE CHOICE 1. A Java program can handle an exception in several different ways. Which of the following is not a way a Java program might handle an exception? a. b. c. d. e.
ignore the exception handle the exception where it arises using try and catch statements propagate the exception to another method where it can be handled throw the exception to a predefined Exception class to be handled All of these are valid ways to handle an exception
ANS: D
A thrown exception is either caught by the current code if the code is contained inside a try statement and the appropriate catch statement is implemented, or else it is propagated to the method that invoked the method that caused the exception. Then it is caught there in an appropriate catch statement, or else it continues to be propagated through the methods in the opposite order that those methods were invoked. This process stops however once the main method is reached. If not caught there, the exception causes termination of the program (this would be answer A, the exception was ignored). However, an exception is not thrown to an Exception class. 2. An exception can produce a "call stack trace" which lists a. b. c. d.
the active methods in the order that they were invoked the active methods in the opposite order that they were invoked the values of all instance data of the object where the exception was raised the values of all instance data of the object where the exception was raised and all local variables and parameters of the method where the exception was raised e. the name of the exception thrown ANS: B The call stack trace provides the names of the methods as stored on the run-time stack. The method names are removed from the stack in the opposite order that they were placed; that is, the earliest method is placed there first, the next method second, and so forth so that the most recently invoked method is the last item on the stack. Thus, it is the first one removed. The stack trace then displays all active methods in the opposite order that they were called (most recent first). 3. An exception that could also arise in the try statement that does not have an associated catch statement is a. b. c. d. e.
ClassNotFoundException IllegalArgumentException NegativeArraySizeException NullPointerException OutOfMemoryException
ANS: D If the array has not yet been instantiated, then it throws a NullPointerException. The ClassNotFoundException, IllegalArgumentException and OutOfMemoryException will not be thrown since there is no code in the try statement that either refers to some unknown class, uses an argument, or deals with the generation of new memory. The NegativeArraySizeException will only arise when instantiating an array. 4. A finally clause will execute only if the try statement that precedes it does not throw an exception only if the try statement that precedes it throws an exception that is caught only if the try statement that precedes it throws an exception that is not caught only if the try statement that precedes it throws an exception, regardless of whether or not it is caught e. in any circumstance a. b. c. d.
ANS: E A finally clause, if specified (because it is optional) will execute no matter what happens with respect to the try and catch statements.
5. Which of the following messages passed to the String str could throw a StringIndexOutOfBoundsException? a. b. c. d. e.
str length(); str charAt(2); str replace('a', 'A'); str equals(str); Any of these could throw a StringIndexOutOfBoundsException
ANS: B The StringIndexOutOfBoundsException is thrown if a parameter of a String method references a position in the String that is beyond the bounds of the String (i.e. a negative int or an int greater than or equal to the number of characters in the String). This can occur in either charAt or substring methods. Example Code Ch 11-1 public static void main(String[] args) { try { ExceptionThrowerCode etc = new ExceptionThrowerCode(); etc.m1(); etc.m2(); } catch (ArithmeticException ae) { ... } } public class ExceptionThrowerCode { ... public void m1() { ... } public void m2() { try { m3(); } catch(ArithmeticException ae) {...} catch(NullPointerException npe) {...} } public void m3() { try { ... } catch(ArithmeticException ae) {...} } }
6. Refer to Example Code Ch 11-1: If an ArithmeticException arises in the try statement in m3 a. b. c. d. e.
it is caught in main it is caught in m1 it is caught in m2 it is caught in m3 it is not caught and the program terminates
ANS: D The method m3 has a catch statement for an ArithmeticException, so if one arises in the try statement in m3, it is caught in the catch statement in m3. 7. Refer to Example Code Ch 11-1: If a NullPointerException arises in the try statement in m3 a. b. c. d. e.
it is caught in main it is caught in m1 it is caught in m2 it is caught in m3 it is not caught and the program terminates
ANS: C The method m3 has no catch statement for a NullPointerException, and so the exception is propagated to the calling method, m2. Method m2 has a catch statement for a NullPointerException so that is where the exception is caught. 8. Refer to Example Code Ch 11-1: If a NullPointerException arises in the try statement in m1 a. b. c. d. e.
it is caught in main it is caught in m1 it is caught in m2 it is caught in m3 it is not caught and the program terminates
ANS: E The method m1 has no catch statements at all, so any exception is propagated to the calling method, main. The method main only has a catch statement for an ArithmeticException so the NullPointerException is not caught and the program terminates. 9. NullPointerExceptions and ArithmeticExceptions are both derived from which class? a. b. c. d. e.
Error Exception RuntimeException IllegalAccessException CheckedException
ANS: C
Both of these exceptions are children of the RuntimeException class which, itself, is a child of Exception. Error is a throwable object that is different from Exception while IllegalAccessException and CheckedException are children of Exception but not of RuntimeException. 10. In order to have some code throw an exception, which of the following reserved words should you use? a. b. c. d. e.
throw throws try Throwable goto
ANS: A The reserved word throw is used to throw an exception when the exception is detected, as in: if (score < 0) throw new IllegalTestScoreException("Input score " + score + " is negative"); 11. Assume Exceptionname is a checked exception. If a method uses a class that can generate Exceptionname, then either the method must include try and catch statements where a catch statement catches Exceptionname, or the method header must include the statement a. b. c. d. e.
throw Exceptionname throws Exceptionname catch Exceptionname catches Exceptionname implements Exceptionname
ANS: B A checked exception must be caught somewhere and so, if not caught in the method that might generate the exception, the exception must be thrown to whatever called the method. This is accomplished by stating that the method throws Exceptionname. 12. Which of the following is not true of the RuntimeException class? a. All RuntimeException throw checked exceptions. b. All RuntimeException are Throwable objects. c. RuntimeException has child classes ArithmeticException and NullPointerException. d. RuntimeException objects are not Error objects. e. All of these are true ANS: A The answers in B, C and D are all true, RuntimeException are Throwable objects and are not part of the Error class, and two types of RuntimeException are ArithmeticException and NullPointerException. Exceptions that are not RuntimeExceptions include various checked exceptions, but RuntimeExceptions are not checked exceptions. 13. Character streams manage a. byte-sized data
b. c. d. e.
binary data Unicode characters ASCII characters compressed data
ANS: C Character streams are used to manage 16-bit Unicode characters. This differs from a byte stream that is used to manage any kind of byte-sized data, including ASCII characters and binary data of other types. 14. A processing stream is a data stream that a. b. c. d. e.
can manage both input streams and output streams at the same time performs some manipulation or process on the data can only manage input streams operates on input and output devices but not files can manage byte streams and character streams at the same time
ANS: B A data stream represents a particular source or destination stream and is used for input or output. A processing stream is like a data stream where some additional process(es) is(are) added to the input or output. For example, a processing byte stream might input all items from a file and remove any ASCII characters that are not digits so that an input expected to be a number will not throw a NumberFormatException. 15. System.err is a(n) a. b. c. d. e.
input stream GUI dialog box that indicates when an error has arisen object Error subclass RuntimException subclass
ANS: C There are three default streams available in Java: System.in, System.out, and System.err. All of these are objects with System.in being an input stream, System.out being an output stream and System.err being an error stream (which is also an output stream). 16. The Scanner class provides an abstraction for input operations by a. using try and catch statements to catch any IOException instead of throwing the Exception elsewhere b. parsing input lines into individual tokens c. performing conversion operations from String to the appropriate type as specified in the Scanner message d. inputting from the standard input stream if create is called using System.in e. All of these ANS: E
Input into a Java program is difficult because it requires a lot of overhead. The Scanner class implements all of that overhead so that the programmer does not have to see it. Thus, Scanner is an abstraction for performing input operations without the details. These details include importing java.io classes, handling IOExceptions in some way, inputting from the standard input stream, dividing the input into individual tokens and converting each token as needed into the requesting form. 17. The term "exception propagation" means a. an exception is caught by the first catch clause b. an exception not caught by the first catch clause is caught by an outer (enclosing) catch clause c. exceptions are caught, sequentially, by catch clauses in the current try block d. exceptions are always caught by the outermost try block e. None of these explain what exception propagation is ANS: E Exception propagation means that an exception is caught by a matching catch clause at the current try block level, and if none matches, then at the next enclosing try block level, and so forth, until the exception either has been caught by a matching clause or the exception passes out of the main routine and is caught by the Java Virtual Machine. 18. When a program terminates because a thrown exception is not handled, the program a. starts up again automatically b. opens a dialog box which asks the user whether the program should start again, end, or enter a debugging mode c. saves all output to a disk file named runStackTrace.txt d. opens a dialog box for the user to specify a disk filename and all output is stored to that file e. outputs a message indicating what the exception was and where it was thrown ANS: E If a thrown exception is not caught anywhere in the program, the program terminates, displaying the contents of the run stack trace. The first item on the run stack trace is the exception that was thrown and where it was thrown (the line number of the method of the class where the exception was raised) 19. A method that uses the Scanner class to obtain input does not require either catching or throwing an IOException. This is because a. the Scanner class does not call upon any classes that throw checked exceptions b. the Scanner class's methods call input methods in try statements and catch IOExceptions so that they are handled directly in the Scanner class c. the Scanner class uses dialog boxes instead of java.io classes so that it does not have to deal with IOExceptions d. the Scanner class overrides the class IOException making it an unchecked exception e. None of the above; methods do require handling IOExceptions even if thrown by a method in a Scanner class ANS: B By having its own catch (IOException) catch statement, any code in the Scanner class that causes an IOException is caught by the Scanner class so that classes that might use the Scanner class do not have to handle this checked exception.
20. The difference between a checked and an unchecked exception is a. b. c. d. e.
checked exceptions need not be listed in a throws clause unchecked exceptions must be listed in a throws clause neither kind of exception follows the rules of exception propagation an unchecked exception requires no throws clause a checked exception always must be caught by a try block while this is not true for an unchecked exception
ANS: D A checked exception must either be caught or it must be listed in a throws clause. An unchecked exception requires no throws clause. Both kinds of exceptions follow the rules of exception propagation. 21. A disabled component is a. b. c. d. e.
one that is grayed out one that is no longer active one that is still visually apparent but no longer functions if clicked provides an indication of functionality that is not currently available All of these are true
ANS: E Components that are disabled appear grayed out; they are disabled for the moment, but remain visually apparent. They provide an indication of functionality that can/will be enabled at some other point in time.
PROBLEM 1. Explain or provide an example showing how an ArithmeticException could arise. ANS: An ArithmeticException could occur if an arithmetic operation could not take place because of an illegal action such as division by zero or square root of a negative number. 2. Explain or provide an example showing how a NullPointerException could arise. ANS: A NullPointerException could occur if an object was not instantiated (it had the value null) before a message was passed to it. 3. Explain or provide an example showing how a NumberFormatException could arise. ANS: A NumberFormatException could occur if an expected value for a numeric operation was not a legal number, such as trying to parse a String value to create an equivalent int where the String contains a non-digit character. 4. Explain or provide an example showing how an IndexOutOfBoundsException could arise.
ANS: An IndexOutOfBoundsException could occur if a numeric parameter that was used as an index into an object such as an array or a String was out of range, such as charAt(-1). 5. Explain or provide an example showing how an IOException could arise. ANS: An IOException could occur if something happened when inputting from keyboard or inputting or outputting to disk such as a disk was not in disk drive. 6. What are the three standard I/O streams and what purposes do they fulfill? ANS: The three standard I/O streams are System.in, System.out, and System.err. System.in is the standard system input stream. Most usually it is connected to the keyboard. System.out is the standard system output stream. It usually is connected to the display. Both System.in and System.out are used for "normal" input and output. System.err usually is connected to the standard error output. This, too, usually is connected to the display. It is used for the display of warning and error messages that otherwise might become lost due, perhaps, to output redirection. 7. Why might you want to create your own exception class? What purpose would it serve? ANS: If you have a collection of error conditions that pertain to a specific function or group of functions that a portion of a program may generate, it might be very wise to create an exception class for that collection of error conditions. Then you would not need to test explicitly for error conditions within that code. You would protect the code with try-catch blocks. This would make the code far cleaner, easier to understand, and easier to maintain. 8. Explain what happens if an exception is not caught. ANS: 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 time during this propagation but if it propagates out of the main method, the program will terminate.
Java Software Solutions, 9e (Lewis/Loftus) Chapter 12 Recursion TRUE/FALSE 1. A recursive method without a base case leads to infinite recursion. ANS: T Without the base case, the recursive method calls itself without the ability to stop, and thus leads to infinite recursion. 2. The following method lacks a base case. public int noBaseCase(int x) { if (x > 0) return noBaseCase(x - 1) + 1; else return noBaseCase(x - 2) + 2; } ANS: T A base case is a condition that, when taken, stops the recursion by not calling the method recursively. In the above method, there is a condition, but whether the condition is true or false, the method invokes itself recursively. 3. Traversing a maze is much easier to do iteratively than recursively. ANS: F One reason that recursion is appealing is that it automatically backtracks to the point of the last decision. In traversing a maze, when one reaches a dead end, the best place to continue is at the point of the previous intersection (or decision). So, backtracking is performed. To solve a maze iteratively requires implementing a backtracking mechanism, which is available automatically in recursion. 4. Some problems are easier to solve recursively than iteratively. ANS: T Since recursion performs backtracking automatically, any problem that requires backtracking is easier to solve using recursion. Such problems include traversing a maze and searching through a "search space", a topic covered in Artificial Intelligence and Advanced Algorithms courses. In some cases, it is easy to find a recursive solution and so the recursive solution is easier than the iterative solution. 5. The following two methods will both compute the same thing when invoked with the same value of x. That is, method1(x) = = method2(x). public int method1(int x) { if (x > 0) return method1(x - 1) + 1; else return 0; } public int method2(int x) {
if (x > 0) return 1 + method2(x - 1); else return 0; } ANS: T The only difference between the two methods is the order of the recursive call and adding 1 to the return value. The difference is denoted by calling the first method head recursive and the second tail recursive. So both methods will compute the same value, but arrive at the value in different ways. 6. Consider the following recursive sum method: public int sum(int x) { if (x == 0) return 0; else return sum(x - 1) + 1; } If the base case is replaced with if (x == 1) return 1; the method will still compute the same thing. ANS: F The original method causes infinite recursion if called with a parameter < 0, but works properly if called with any parameter >= 0. With the new base case, the method now works properly if called with any parameter >= 1 but causes infinite recursion if the parameter < 1. So, sum(0) now differs from what it was previously. 7. The recursive method to solve the Towers of Hanoi is usable only if the parameter for the number of disks is 7 or smaller. ANS: F The Towers of Hanoi solution can be used for any number of disks as long as it is at least 1 but the size will affect its performance. 8. A Koch snowflake of order = 1 can be drawn without recursion. ANS: T The Koch snowflake of order 1 is made up of straight lines. It is not until the order is greater than 1 that recursion is applied. 9. Since iterative solutions often use loop variables and recursive solutions do not, the recursive solution is usually more memory efficient (uses less memory) than the equivalent iterative solution. ANS: F The recursive solution may use no local variables whatsoever, but the recursive solution usually uses parameters. Every time the method is called recursively, new parameters are required, and so recursive solutions usually use a substantially larger amount of memory than an iterative solution. This depends on how many times the method is called recursively. 10. We can define a list of int values recursively as a list_item, followed by a comma, followed by a list where a list_item is any int value. ANS: F
The recursive definition does not include a base case so that all lists of int values will be infinitely long! 11. It always is possible to replace a recursion by an iteration and vice versa. ANS: T Both recursion and iteration are forms of repetition. Whether one phrases the repetition using recursion or iteration is a matter of style, taste, sometimes efficiency, sometimes convenience. But they are equivalent in terms of computation and each may be replaced by the other. 12. If one were to create a Towers of Hanoi puzzle with four towers instead of three, with rules changed appropriately, it should be possible to create a recursive solution for the puzzle where one of the constraints is that at some point during the solution all of the disks must reside on each of the four towers. ANS: T The solution to this version of the game can be phrased as follows: Use the 3-peg Towers solution to move all the disks from peg A to peg B; then use the 3-peg Towers solution to move all the disks from peg B to peg C; repeat, moving from peg C to peg D. 13. The Koch snowflake has an infinitely long perimeter, but it contains a finite area. ANS: T As the order of the Koch snowflake increases the perimeter grows exponentially large. In the limit, the perimeter is infinitely long. But, since the entire snowflake can be contained within a bounding square, the area of the snowflake is finite. MULTIPLE CHOICE 1. The following method should return true if the int parameter is even and either positive or 0, and false otherwise. Which set of code should you use to replace ... so that the method works appropriately? public boolean question3(int x) a. if (x == 0) return true; else if (x < 0) return false; else return question3(x - 1); b. if (x == 0) return false; else if (x < 0) return true; else return question3(x - 1); c. if (x == 0) return true; else if (x < 0) return false; else return question3(x - 2); d. if (x == 0) return false; else if (x < 0) return true; else return question3(x - 2); e. return(x == 0); ANS: C
{ ... }
The method will recursively call itself subtracting 2 from x until x == 0 or x<0. If x == 0, then x - 2 * i == 0 (for some int value i) or x == 2 * i, so x must be even. Otherwise, the recursion ends when x < 0, meaning that the original x was odd or less than 0. 2. What is wrong with the following recursive sum method? The method is supposed to sum up the values between 1 and x (for instance, sum(5)should be 5 + 4 + 3 + 2 + 1 = 15). public int sum(int x) { if (x == 0) return 0; else return sum(x - 1) + x; } a. b. c. d. e.
The base case should return 1 instead of 0. The recursive case should return sum(x - 1) + 1 instead ofsum(x - 1) + x. The base case condition should be (x <= 0) instead of (x == 0). The recursive case should return sum(x) + 1. The method should return a boolean instead of an int.
ANS: B The method does not appropriately handle a negative parameter, such as sum(-5). The result is infinite recursion. We might define a negative parameter as something that should return 0, or allow a negative parameter to compute a negative sum as in: public int sum(int x) { if (x == 0) return 0; else if (x < 0) return -1 * sum(-x); else return sum(x - 1) + x; } 3. What does the following recursive method determine?. public boolean question16(int[]a, int[] b, int j) { if (j == a.length) return false; else if (j == b.length) return true; else return question16(a, b, j+1); } a. b. c. d. e.
returns true if a and b are equal in size, false otherwise returns true if a is larger than b, false otherwise returns true if b is larger than a, false otherwise returns true if a and b have no elements return the length of array a + length of array b
ANS: B The method returns true if the third parameter, j, is equal to the length of b but not equal to the length of a. Thus, the method returns true if the third parameter has reached the value indicating the end of array b but not the end of array a so this is true if a is larger than b. If a and b are equal length or if a is shorter than b, false is returned. 4. Why is the following method one which has infinite recursion? public int infiniteRecursion(int n)
{ if (n > 0) return infiniteRecursion(n) + 1; else return 0; } a. b. c. d. e.
because there is no base case because the base case will never be true because the recursive call does not move the parameter closer to the base case because the recursive call moves the problem further away from the base case None of these; this method isn't infinitely recursive
ANS: C The recursive case has the method calling itself with the same parameter, and so n does not change, thus if (n > 0) is initially true, it will remain true. 5. Which of the following methods would properly compute the value of x % y (x mod y) recursively, assuming that x and y are not negative numbers? a. public int recursiveMod(int x, int y) { if (x < y) return y; else return recursiveMod(x, y - x); } b. public int recursiveMod(int x, int y) { if (x == y) return 0; else return recursiveMod(x - y, y) + 1; } c. public int recursiveMod(int x, int y) { if (x < y) return x; else return recursiveMod(x - y, y) + 1; } d. public int recursiveMod(int x, int y) { if (x < y) return x; else return recursiveMod(x - y, y); } e. public int recursiveMod(int x, int y) { while (x > y) x = x - y; return x; } ANS: D The value x % y can be computed by continually subtracting y from x until x<y. Then, the result is x. For instance, 7 % 3 = 4 % 3 = 1 % 3 = 1. The code in answers A, B, and C do not compute x % y and answer E computes mod but uses an iterative solution, not a recursive one. 6. A recursive algorithm is superior to an iterative algorithm along which of the following criteria? a. The recursive algorithm is easier to debug. b. The recursive algorithm is computationally more efficient. c. The recursive algorithm is more elegant.
d. The recursive algorithm requires less memory to execute. e. All of these ANS: C When comparing most recursive algorithms to their iterative counterparts, it is almost always the case that the recursive algorithm is shorter, so it tackles the same problem with less code. This means it is more elegant (which does not necessarily mean it is easier to understand or more efficient). 7. Aside from writing recursive methods, another way that recursion is often used is to define a. b. c. d. e.
words in English mathematical functions rules and laws child classes of a parent class in object-oriented programming recursion is used in all of these
ANS: B Mathematics often defines functions recursively for simplicity. 8. What is a fractal? a. a portion of a larger structure (a fraction) b. a geometric shape that can be made up of the same pattern repeated at different scales and orientations c. a recursively defined numeric function d. a ratio (a fraction) e. None of these ANS: B A fractal is a geometric shape that is "self-similar"; that is, it appears to be the same regardless of scale and orientation. The same shape appears at different scales and orientations. 9. The Koch fractal of order 1 is a. b. c. d. e.
a triangle a square a point a circle None of these
ANS: A The Koch fractal of order 1 is the simplest possible closed figure that contains an area-–a triangle. 10. Each time the order of a Koch fractal increases by one, the number of straight line segments a. b. c. d. e.
increases by a factor of two increases by a factor of three increases by a factor of four is squared is cubed
ANS: C Each line segment is replaced by four equal-length line segments each time the order increases by one. So, the total number of straight line segments increases by a factor of four each time the order is increased by one.
11. The difference between direct and indirect recursion is a. direct recursion occurs when a method invokes itself; indirect recursion occurs when there is an intervening method b. indirect recursion occurs when a method invokes itself; direct recursion occurs when there is an intervening method c. direct recursion only occurs with methods declared to be private; indirect recursion can occur with methods declared to be private, protected, or public d. indirect recursion only occurs with methods declared to be private; direct recursion can occur with methods declared to be private, protected, or public e. None of these ANS: A Direct recursion means that a method directly invokes itself with no intervening method. Indirect recursion occurs when there are one or more intervening methods before the original method is invoked again. 12. What can be said about the difference or similarity, if any, between an infinite loop and an infinite recursion? a. b. c. d. e.
It is impossible to detect the latter while it's easy to detect the former. Both continue to repeat indefinitely. Both will be caught by the compiler. Both will be caught by the Java Virtual Machine during execution. None of these
ANS: B Both infinite loops and recursion are similar in that they continue to repeat indefinitely. Neither can be caught by the compiler or by the JVM. 13. Define the magnitude of a number as the location of the decimal point from the left of the number (that is, if a number has 4 digits followed by the decimal point, it will have a magnitude of 4). 100 would then have a magnitude of 3 and 55,555.555 would have a magnitude of 5. A partial recursive method is given below to compute a positive int parameter's magnitude. Which answer below is needed to complete the method? public int magnitude(double x) { if (x < 1) return 0; else return _______; } a. b. c. d. e.
magnitude(x - 1) + 10; magnitude(x - 10) + 1; magnitude(x / 10) + 10; magnitude(x / 10) + 1; magnitude(x / 10) * 2;
ANS: D The method must count the number of digits to the left of the decimal point, so it continually divides the value by 10 until the value has no digits to the left of the decimal point (this is the case if the value is less than 1). Each time the value is divided by 10, 1 is added to the return value. 55,555.555 will be divided by 10 five times before it becomes less than 1, and thus return 5.
14. What does the following method compute? Assume the method is called initially with i = 0. public int question9(String a, char b, int i) { if (i == a.length()) return 0; else if (b == a.charAt(i)) return question9(a, b, i+1) + 1; else return question9(a, b, i+1); } a. b. c. d. e.
the length of String a the length of String a concatenated with char b the number of times char b appears in String a the value 1 if char b appears in String a at least once and 0 otherwise the char which appears at location i in String a
ANS: C The method compares each character in String a with char b until i reaches the length of String a. 1 is added to the return value for each match. Example Code Ch 12-1 Given the following recursive method: public int question1_2(int x, int y) { if (x == y) return 0; else return question1_2(x-1, y) + 1; } 15. Refer to Example Code Ch 12-1: If the method is called as question1_2(8, 3), what is returned? a. b. c. d. e.
11 8 5 3 24
ANS: C The method computes x - y if x > y. The method works as follows: each time the method is called recursively, it subtracts 1 from x until (x == y) is becomes true, and adds 1 to the return value. So, 1 is added each time the method is called, and the method is called once for each int value between x and y. 16. Refer to Example Code Ch 12-1: Calling this method will result in infinite recursion if which of the following conditions is initially true? a. b. c. d. e.
(x == y) (x != y) (x > y) (x < y) (x == 0) && (y != 0)
ANS: D If (x < y) is true initially, then the else clause is executed resulting in the method being recursively invoked with a value of x - 1, or a smaller value of x, so that (x < y) will be true again, and so for each successive recursive call, (x < y) will be true and the base case, x == y, will never be true. Example Code Ch 12-2 Given the following recursive factorial method: public int factorial(int x) { if (x > 1) return x * factorial (x - 1); else return 1; } 17. Refer to Example Code Ch 12-2: What is returned if factorial(3) is called? a. b. c. d. e.
0 1 3 6 9
ANS: D With factorial(3) x> 1, so it returns 3*factorial(2), with factorial(2) x> 1 so it returns 2*factorial(1), with factorial(1), 1 is returned, so we have 3*2*1 = 6. 18. Refer to Example Code Ch 12-2: What is returned if factorial(0) is called? a. b. c. d. e.
0 1 2 nothing, factorial(0) causes infinite recursion nothing, factorial(0) produces a run-time error
ANS: B With factorial(0) x > 1 is not true, so the base case is executed and 1 is returned. Therefore, although ordinarily 0 * a value = 0, factorial(0) is computed as 1, as defined. 19. Refer to Example Code Ch 12-2: How many times is the factorial method called with factorial(5)? Include the original method call in your counting. a. b. c. d. e.
1 4 5 6 7
ANS: C The method is first invoked with factorial(5), which in turn returns 5 * factorial(4), so factorial is invoked again, which in turn returns 4 * factorial(3), so factorial is invoked again, which in turn returns 3 * factorial(2), so factorial is invoked again, which in turn returns 2 * factorial(1), so factorial is invoked again, and finally factorial(1)invokes the base case and returns 1. So, factorial was invoked 5 times.
20. Refer to Example Code Ch 12-2: What condition defines the base case for this method? a. b. c. d. e.
(x > 1) (x == 1) (x == 0) (x <= 0) (x <= 1)
ANS: E The if condition is (x > 1) but this is the recursive case, so the base case is the opposite condition. The opposite of (x > 1) is (x <= 1). Example Code Ch 12-3 Given the two recursive methods shown below, foo and bar. Assume int[] a = {6, 2, 4, 6, 2, 1, 6, 2, 5} public int foo(int[] a, int b, int j) { if (j < a.length) if (a[j] != b) return foo (a, b, j+1); else return foo (a, b, j+1) + 1; else return 0; } public int bar(int[] a, int j) { if (j < a.length) return a[j] + bar(a, j+1); else return 0; } 21. Refer to Example Code 12-3: What is the result of calling foo(a, 2, 0)? a. b. c. d. e.
0 1 2 3 4
ANS: C The method foo counts the number of occurrences of the int parameter in the second position in the array starting at the index given as the third parameter. So, foo(a, 2, 0) finds the number of 2s in a. 2 appears 3 times in array a. 22. Refer to Example Code 12-3: What is the result of calling foo(a, 3, 0)? a. b. c. d. e.
0 1 2 3 4
ANS: A
The method foo counts the number of occurrences of the int parameter in the second position in the array starting at the index given as the third parameter. So, foo(a, 3, 0) finds the number of 3s in a. There are none. 23. Refer to Example Code 12-3: What is the result of calling foo(a, 2, 9)? a. b. c. d. e.
0 1 2 3 4
ANS: A The method foo counts the number of occurrences of the int parameter in the second position in the array starting at the index given as the third parameter. So, foo(a, 2, 9) results in the base case being executed immediately becuase 9 == a.length and the base case returns 0. 24. Refer to Example Code 12-3: What is the result of calling bar(a, 0)? a. b. c. d. e.
0 5 6 12 34
ANS: E The bar method recursively sums the elements of array a starting at the location of the second parameter. Since the starting point is location 0, this call sums all elements of a which equals 34. 25. Refer to Example Code 12-3: What is the result of calling bar(a, 8)? a. b. c. d. e.
0 5 6 12 34
ANS: B The bar method recursively sums the elements of array a starting at the location of the second parameter (8 in this case). So bar(a, 8) sums up only the last element in the array, 5, and so 5 is returned. 26. Recall the Towers of Hanoi recursive solution for this problem. If there are two disks to move from one Tower to another, how many disk movements would it take to solve the problem using the recursive solution? a. b. c. d. e.
0 1 2 3 4
ANS: D
The Towers of Hanoi solution requires using the previous solution twice + 1 extra move. To solve it for 1 disk, it takes 1 move. To solve it for 2 disks, it takes using the solution for 1 disk twice + 1, or 1 move + 1 move + 1 move = 3 moves. We capture this in the equation 2n - 1 where n is the number of disks. 27. Recall the Towers of Hanoi recursive solution for this problem. If there are six disks to move from one Tower to another, how many disk movements would it take to solve the problem using the recursive solution? a. b. c. d. e.
6 13 31 63 127
ANS: D The Towers of Hanoi solution requires using the previous solution twice + 1 extra move. To solve it for 1 disk, it takes 1 move. To solve it for 2 disks, it takes using the solution for 1 disk twice + 1 extra move, or 1 move + 1 move + 1 extra move = 3 moves. We capture this in the equation 2n - 1 where n is the number of disks. For 3 disks this takes 7 moves, for 4 disks this takes 15 moves, for 5 disks this takes 31 moves and for 6 disks this takes 63 moves. 28. Recall the Towers of Hanoi recursive solution for this problem. The solution to the Towers of Hanoi has a(n) __________ complexity. a. b. c. d. e.
linear polynomial logarithmic exponential bad
ANS: D The complexity for Towers of Hanoi is 2n - 1, which is known as exponential because, as n increases by 1, the number of moves doubles, or the complexity increases exponentially. Example Code Ch 12-4 The following recursive method recognizes whether a String parameter consists of a specific pattern and returns true if the String has that pattern, false otherwise. public boolean patternRecognizer(String a) { if (a == null) return false; else if (a.length() == 1 || (a.length() == 2 && a.charAt(0) == a.charAt(1))) return true; else if (a.length() == 2 && a.charAt(0) != a.charAt(1)) return false; else if (a.charAt(0) == a.charAt(a.length() - 1)) return patternRecognizer(a.substring(1,a.length()-1)); else return false; } 29. Refer to Example Code Ch 12-4: Which String of the following would result in patternRecognizer returing true?
a. b. c. d. e.
"abcba" "aaabbb" "abcde" "aabba" All of these
ANS: A The method patternRecognizer returns true if the String is a palindrome. This can be seen by analyzing the code. If the String has 1 character, or 2 characters which are equal, it returns true, otherwise if the first and last characters are the same, it recursively calls itself with the substring starting at character 1 and going to the second to last character (so, since in "abcba" the first and last characters are the same, the method is called recursively with the substring "bcb"). Only if the first and last characters do not match is false returned. The only palindrome in the list of options is A, "abcba". 30. Refer to Example Code Ch 12-4: If the method is called as patternRecognizer(x) where x = "aa", what will the result be? a. b. c. d. e.
true false NullPointerException a run-time error infinite recursion
ANS: A One of the base cases tests to see if the String has 2 characters and if so, returns true if the two characters are the same. 31. Refer to Example Code Ch 12-4: If the statement a.substring(1, a.length() - 1 was changed to be a.substring(1, a.length()) then the method would a. b. c. d. e.
have infinite recursion unless the String was null always return true always return false return true only if all the characters of the String were the same return true only if the String had only two characters and they were the same
ANS: D The original method recursively calls itself with a substring equal to the String minus the first and last characters. This new version would recursively call itself with a substring equal to the String minus the first character. The method would return true if the first character of the String (or substring) equaled the last character. Since the substring for each recursive call is the same as the previous String less the first character, it winds up comparing each character in the String to the last in the String and returning true only if each character of the String equals the last character. This means all of the characters are the same.
PROBLEM
1. Provide a definition for the following terms as they relate to programming: recursion, indirect recursion and infinite recursion. ANS: Recursion: writing a method that calls itself. Indirect recursion: writing a method that calls other methods that call the original method so that the recursion is not done directly through the first method. Infinite recursion: recursion where the recursion is never stopped by a base case because either the base case was not defined, or the base case is never reached. 2. Explain what a "base case" is in a recursive method. ANS: The part of a recursive method that does not call itself (either directly or indirectly) to calculate the answer is called the base case. This is the case that stops the method, stopping otherwise infinite recursion. Every well written recursive method will have at least one base case. 3. Rewrite the following iterative method as a recursive method that computes the same thing. Note: your recursive method will require an extra parameter. public int iterative1(int x) { int count = 0, factor = 2; while (factor < x) { if (x % factor == 0) count++; factor++; } return count; } ANS: public int recursion1(int x, int y) { if (y >= x) return 0; else if (x % y == 0) return 1 + recursion1(x, y + 1); else return recursion(x, y + 1); } where this method is called with y =2 initially 4. Rewrite the following iterative method as a recursive method that computes the same thing. Note: your recursive method will require an extra parameter. public String reversal(String x) { int y = x.length(); String s = ""; for (int j = y - 1; j >= 0; j--) s += x.charAt(j); return s; }
ANS: public String reversal(String x, int j) { if (j < 0) return ""; else return x.charAt(j) + reversal(x, j-1); } where the recursive reversal is called with j = x.length() - 1. 5. Rewrite the following iterative method as a recursive method that returns the same String. public String listOfNumbers() { String s = ""; for (j = 1; j < 10; j++) s += j; return s; } ANS: public String listOfNumbers(int j) { if (j == 10) return ""; else return ""+ j + listOfNumbers(j+1); } where the recursive listOfNumbers is called with j = 1. 6. Describe how to solve the Towers of Hanoi problem using 4 disks (that is, write down move for move how to solve the problem). ANS: Move disk from 1 to 2 Move disk from 1 to 3 Move disk from 2 to 3 Move disk from 1 to 2 Move disk from 3 to 1 Move disk from 3 to 2 Move disk from 1 to 2 Move disk from 1 to 3 Move disk from 2 to 3 Move disk from 2 to 1 Move disk from 3 to 1 Move disk from 2 to 3 Move disk from 1 to 2 Move disk from 1 to 3 Move disk from 2 to 3 7. For the Towers of Hanoi problem, show how many moves it will take to solve the problem with 5 disks, 6 disks, 7 disks, 8 disks, 9 disks, and 10 disks. ANS: For 5 disks, it takes 31 moves For 6 disks, it takes 63 moves
For 7 disks, it takes 127 moves For 8 disks, it takes 255 moves For 9 disks, it takes 511 moves For 10 disks, it takes 1023 moves 8. Assume a function g(x) is defined as follows where x is an int parameter: g(x) = g(x - 1) * g (x - 3) if x is even and x > 3 = g(x - 2) if x is odd and x > 3 = x otherwise Write a recursive method to compute g. ANS: public int g(int x) { if (x > 3 && x % 2 == 0) return g(x - 1) * g (x - 3); else if (x > 3) return g(x - 2); else return x; } 9. Demonstrate how factorial(4) is computed given the following recursive method for factorial: public int factorial(int n) { if (n > 1) return factorial(n - 1) * n; else return 1; } ANS: factorial(4) = factorial(3) * 4 factorial(3) = factorial(2) * 3 factorial(2) = factorial(1) * 2 factorial(1) = 1 factorial(2) = 1 * 2 = 2 factorial(3) = 2 * 3 = 6 factorial(4) = 6 * 4 = 24 10. Describe the difference(s) between the following two sets of code, neither of which reaches a terminating condition. public void forever1() { while (true); } public void forever2() { forever2(); } ANS:
The method forever1 is iterative and so, since the while loop condition is always true, the method never exits the loop. The method forever2 is recursive, so that each time it is called, it requires method handling mechanisms (which use an entity called the run-time stack). So, while neither method will terminate naturally, forever2 takes more time and will eventually run out of run-time stack space resulting in an Exception being thrown and the program terminating. 11. The game of high-low is one where one person selects a number between 1 and 100 and a user tries to guess it by guessing a number and being told if the guessed number is the right number, too low or too high. The user repeats guessing until getting the correct answer. A logical user will always guess at the midpoint of the possible values (for instance, the first guess would be 50 followed by either 25 or 75, etc). Write a recursive method to play the game of high-low by having the computer guess a midpoint. The method should receive three parameters, the number itself, the lowest value in the range and the highest value in the range and return the number of guesses that it took to guess the right number. ANS: public int highLow(int guess, int low, int high) { int mid = (low + high) / 2; if (mid == guess) return 1; else if (mid < guess) return highLow(guess, mid, high) + 1; else return highLow(guess, low, mid) + 1; } 12. Recursion is a popular programming tool but beginning programmers tend to shy away from it. Why do you suppose this is true? ANS: Unlike iterative and conditional control structures, recursion is a new way of thinking for most programmers. The idea of seeing a solution by defining it in terms of itself seems natural but is not a mechanism that most students are taught to use. Therefore, recursion is often difficult. Further, debugging recursive methods is often very difficult because the logical and run-time errors are harder to track down. 13. Write a recursive method called numSegments(int order) that yields the number of line segments in a Koch snowflake of order order. ANS: public int numSegments(int order) { return (order <= 1) ? 3 : 4 * numSegments(order - 1); }
14. The Euclidean algorithm for calculating the greatest common divisor (gcd) of two integers a and b is: "If a is a nonnegative integer, b is a positive integer, and r = a mod b, then gcd(a,b) = gcd(b,r). Write a recursive method that uses the Euclidean algorithm to calculate the gcd. ANS: int gcd(int a, int b) { int r = a;
if (a >= 0 && b > 0) r = gcd(b, a % b); return r; }
Java Software Solutions, 9e (Lewis/Loftus) Chapter 12 Recursion TRUE/FALSE 1. A recursive method without a base case leads to infinite recursion. ANS: T Without the base case, the recursive method calls itself without the ability to stop, and thus leads to infinite recursion. 2. The following method lacks a base case. public int noBaseCase(int x) { if (x > 0) return noBaseCase(x - 1) + 1; else return noBaseCase(x - 2) + 2; } ANS: T A base case is a condition that, when taken, stops the recursion by not calling the method recursively. In the above method, there is a condition, but whether the condition is true or false, the method invokes itself recursively. 3. Traversing a maze is much easier to do iteratively than recursively. ANS: F One reason that recursion is appealing is that it automatically backtracks to the point of the last decision. In traversing a maze, when one reaches a dead end, the best place to continue is at the point of the previous intersection (or decision). So, backtracking is performed. To solve a maze iteratively requires implementing a backtracking mechanism, which is available automatically in recursion. 4. Some problems are easier to solve recursively than iteratively. ANS: T Since recursion performs backtracking automatically, any problem that requires backtracking is easier to solve using recursion. Such problems include traversing a maze and searching through a "search space", a topic covered in Artificial Intelligence and Advanced Algorithms courses. In some cases, it is easy to find a recursive solution and so the recursive solution is easier than the iterative solution. 5. The following two methods will both compute the same thing when invoked with the same value of x. That is, method1(x) = = method2(x). public int method1(int x) { if (x > 0) return method1(x - 1) + 1; else return 0; } public int method2(int x) {
if (x > 0) return 1 + method2(x - 1); else return 0; } ANS: T The only difference between the two methods is the order of the recursive call and adding 1 to the return value. The difference is denoted by calling the first method head recursive and the second tail recursive. So both methods will compute the same value, but arrive at the value in different ways. 6. Consider the following recursive sum method: public int sum(int x) { if (x == 0) return 0; else return sum(x - 1) + 1; } If the base case is replaced with if (x == 1) return 1; the method will still compute the same thing. ANS: F The original method causes infinite recursion if called with a parameter < 0, but works properly if called with any parameter >= 0. With the new base case, the method now works properly if called with any parameter >= 1 but causes infinite recursion if the parameter < 1. So, sum(0) now differs from what it was previously. 7. The recursive method to solve the Towers of Hanoi is usable only if the parameter for the number of disks is 7 or smaller. ANS: F The Towers of Hanoi solution can be used for any number of disks as long as it is at least 1 but the size will affect its performance. 8. A Koch snowflake of order = 1 can be drawn without recursion. ANS: T The Koch snowflake of order 1 is made up of straight lines. It is not until the order is greater than 1 that recursion is applied. 9. Since iterative solutions often use loop variables and recursive solutions do not, the recursive solution is usually more memory efficient (uses less memory) than the equivalent iterative solution. ANS: F The recursive solution may use no local variables whatsoever, but the recursive solution usually uses parameters. Every time the method is called recursively, new parameters are required, and so recursive solutions usually use a substantially larger amount of memory than an iterative solution. This depends on how many times the method is called recursively. 10. We can define a list of int values recursively as a list_item, followed by a comma, followed by a list where a list_item is any int value. ANS: F
The recursive definition does not include a base case so that all lists of int values will be infinitely long! 11. It always is possible to replace a recursion by an iteration and vice versa. ANS: T Both recursion and iteration are forms of repetition. Whether one phrases the repetition using recursion or iteration is a matter of style, taste, sometimes efficiency, sometimes convenience. But they are equivalent in terms of computation and each may be replaced by the other. 12. If one were to create a Towers of Hanoi puzzle with four towers instead of three, with rules changed appropriately, it should be possible to create a recursive solution for the puzzle where one of the constraints is that at some point during the solution all of the disks must reside on each of the four towers. ANS: T The solution to this version of the game can be phrased as follows: Use the 3-peg Towers solution to move all the disks from peg A to peg B; then use the 3-peg Towers solution to move all the disks from peg B to peg C; repeat, moving from peg C to peg D. 13. The Koch snowflake has an infinitely long perimeter, but it contains a finite area. ANS: T As the order of the Koch snowflake increases the perimeter grows exponentially large. In the limit, the perimeter is infinitely long. But, since the entire snowflake can be contained within a bounding square, the area of the snowflake is finite. MULTIPLE CHOICE 1. The following method should return true if the int parameter is even and either positive or 0, and false otherwise. Which set of code should you use to replace ... so that the method works appropriately? public boolean question3(int x) a. if (x == 0) return true; else if (x < 0) return false; else return question3(x - 1); b. if (x == 0) return false; else if (x < 0) return true; else return question3(x - 1); c. if (x == 0) return true; else if (x < 0) return false; else return question3(x - 2); d. if (x == 0) return false; else if (x < 0) return true; else return question3(x - 2); e. return(x == 0); ANS: C
{ ... }
The method will recursively call itself subtracting 2 from x until x == 0 or x<0. If x == 0, then x - 2 * i == 0 (for some int value i) or x == 2 * i, so x must be even. Otherwise, the recursion ends when x < 0, meaning that the original x was odd or less than 0. 2. What is wrong with the following recursive sum method? The method is supposed to sum up the values between 1 and x (for instance, sum(5)should be 5 + 4 + 3 + 2 + 1 = 15). public int sum(int x) { if (x == 0) return 0; else return sum(x - 1) + x; } a. b. c. d. e.
The base case should return 1 instead of 0. The recursive case should return sum(x - 1) + 1 instead ofsum(x - 1) + x. The base case condition should be (x <= 0) instead of (x == 0). The recursive case should return sum(x) + 1. The method should return a boolean instead of an int.
ANS: B The method does not appropriately handle a negative parameter, such as sum(-5). The result is infinite recursion. We might define a negative parameter as something that should return 0, or allow a negative parameter to compute a negative sum as in: public int sum(int x) { if (x == 0) return 0; else if (x < 0) return -1 * sum(-x); else return sum(x - 1) + x; } 3. What does the following recursive method determine?. public boolean question16(int[]a, int[] b, int j) { if (j == a.length) return false; else if (j == b.length) return true; else return question16(a, b, j+1); } a. b. c. d. e.
returns true if a and b are equal in size, false otherwise returns true if a is larger than b, false otherwise returns true if b is larger than a, false otherwise returns true if a and b have no elements return the length of array a + length of array b
ANS: B The method returns true if the third parameter, j, is equal to the length of b but not equal to the length of a. Thus, the method returns true if the third parameter has reached the value indicating the end of array b but not the end of array a so this is true if a is larger than b. If a and b are equal length or if a is shorter than b, false is returned. 4. Why is the following method one which has infinite recursion? public int infiniteRecursion(int n)
{ if (n > 0) return infiniteRecursion(n) + 1; else return 0; } a. b. c. d. e.
because there is no base case because the base case will never be true because the recursive call does not move the parameter closer to the base case because the recursive call moves the problem further away from the base case None of these; this method isn't infinitely recursive
ANS: C The recursive case has the method calling itself with the same parameter, and so n does not change, thus if (n > 0) is initially true, it will remain true. 5. Which of the following methods would properly compute the value of x % y (x mod y) recursively, assuming that x and y are not negative numbers? a. public int recursiveMod(int x, int y) { if (x < y) return y; else return recursiveMod(x, y - x); } b. public int recursiveMod(int x, int y) { if (x == y) return 0; else return recursiveMod(x - y, y) + 1; } c. public int recursiveMod(int x, int y) { if (x < y) return x; else return recursiveMod(x - y, y) + 1; } d. public int recursiveMod(int x, int y) { if (x < y) return x; else return recursiveMod(x - y, y); } e. public int recursiveMod(int x, int y) { while (x > y) x = x - y; return x; } ANS: D The value x % y can be computed by continually subtracting y from x until x<y. Then, the result is x. For instance, 7 % 3 = 4 % 3 = 1 % 3 = 1. The code in answers A, B, and C do not compute x % y and answer E computes mod but uses an iterative solution, not a recursive one. 6. A recursive algorithm is superior to an iterative algorithm along which of the following criteria? a. The recursive algorithm is easier to debug. b. The recursive algorithm is computationally more efficient. c. The recursive algorithm is more elegant.
d. The recursive algorithm requires less memory to execute. e. All of these ANS: C When comparing most recursive algorithms to their iterative counterparts, it is almost always the case that the recursive algorithm is shorter, so it tackles the same problem with less code. This means it is more elegant (which does not necessarily mean it is easier to understand or more efficient). 7. Aside from writing recursive methods, another way that recursion is often used is to define a. b. c. d. e.
words in English mathematical functions rules and laws child classes of a parent class in object-oriented programming recursion is used in all of these
ANS: B Mathematics often defines functions recursively for simplicity. 8. What is a fractal? a. a portion of a larger structure (a fraction) b. a geometric shape that can be made up of the same pattern repeated at different scales and orientations c. a recursively defined numeric function d. a ratio (a fraction) e. None of these ANS: B A fractal is a geometric shape that is "self-similar"; that is, it appears to be the same regardless of scale and orientation. The same shape appears at different scales and orientations. 9. The Koch fractal of order 1 is a. b. c. d. e.
a triangle a square a point a circle None of these
ANS: A The Koch fractal of order 1 is the simplest possible closed figure that contains an area-–a triangle. 10. Each time the order of a Koch fractal increases by one, the number of straight line segments a. b. c. d. e.
increases by a factor of two increases by a factor of three increases by a factor of four is squared is cubed
ANS: C Each line segment is replaced by four equal-length line segments each time the order increases by one. So, the total number of straight line segments increases by a factor of four each time the order is increased by one.
11. The difference between direct and indirect recursion is a. direct recursion occurs when a method invokes itself; indirect recursion occurs when there is an intervening method b. indirect recursion occurs when a method invokes itself; direct recursion occurs when there is an intervening method c. direct recursion only occurs with methods declared to be private; indirect recursion can occur with methods declared to be private, protected, or public d. indirect recursion only occurs with methods declared to be private; direct recursion can occur with methods declared to be private, protected, or public e. None of these ANS: A Direct recursion means that a method directly invokes itself with no intervening method. Indirect recursion occurs when there are one or more intervening methods before the original method is invoked again. 12. What can be said about the difference or similarity, if any, between an infinite loop and an infinite recursion? a. b. c. d. e.
It is impossible to detect the latter while it's easy to detect the former. Both continue to repeat indefinitely. Both will be caught by the compiler. Both will be caught by the Java Virtual Machine during execution. None of these
ANS: B Both infinite loops and recursion are similar in that they continue to repeat indefinitely. Neither can be caught by the compiler or by the JVM. 13. Define the magnitude of a number as the location of the decimal point from the left of the number (that is, if a number has 4 digits followed by the decimal point, it will have a magnitude of 4). 100 would then have a magnitude of 3 and 55,555.555 would have a magnitude of 5. A partial recursive method is given below to compute a positive int parameter's magnitude. Which answer below is needed to complete the method? public int magnitude(double x) { if (x < 1) return 0; else return _______; } a. b. c. d. e.
magnitude(x - 1) + 10; magnitude(x - 10) + 1; magnitude(x / 10) + 10; magnitude(x / 10) + 1; magnitude(x / 10) * 2;
ANS: D The method must count the number of digits to the left of the decimal point, so it continually divides the value by 10 until the value has no digits to the left of the decimal point (this is the case if the value is less than 1). Each time the value is divided by 10, 1 is added to the return value. 55,555.555 will be divided by 10 five times before it becomes less than 1, and thus return 5.
14. What does the following method compute? Assume the method is called initially with i = 0. public int question9(String a, char b, int i) { if (i == a.length()) return 0; else if (b == a.charAt(i)) return question9(a, b, i+1) + 1; else return question9(a, b, i+1); } a. b. c. d. e.
the length of String a the length of String a concatenated with char b the number of times char b appears in String a the value 1 if char b appears in String a at least once and 0 otherwise the char which appears at location i in String a
ANS: C The method compares each character in String a with char b until i reaches the length of String a. 1 is added to the return value for each match. Example Code Ch 12-1 Given the following recursive method: public int question1_2(int x, int y) { if (x == y) return 0; else return question1_2(x-1, y) + 1; } 15. Refer to Example Code Ch 12-1: If the method is called as question1_2(8, 3), what is returned? a. b. c. d. e.
11 8 5 3 24
ANS: C The method computes x - y if x > y. The method works as follows: each time the method is called recursively, it subtracts 1 from x until (x == y) is becomes true, and adds 1 to the return value. So, 1 is added each time the method is called, and the method is called once for each int value between x and y. 16. Refer to Example Code Ch 12-1: Calling this method will result in infinite recursion if which of the following conditions is initially true? a. b. c. d. e.
(x == y) (x != y) (x > y) (x < y) (x == 0) && (y != 0)
ANS: D If (x < y) is true initially, then the else clause is executed resulting in the method being recursively invoked with a value of x - 1, or a smaller value of x, so that (x < y) will be true again, and so for each successive recursive call, (x < y) will be true and the base case, x == y, will never be true. Example Code Ch 12-2 Given the following recursive factorial method: public int factorial(int x) { if (x > 1) return x * factorial (x - 1); else return 1; } 17. Refer to Example Code Ch 12-2: What is returned if factorial(3) is called? a. b. c. d. e.
0 1 3 6 9
ANS: D With factorial(3) x> 1, so it returns 3*factorial(2), with factorial(2) x> 1 so it returns 2*factorial(1), with factorial(1), 1 is returned, so we have 3*2*1 = 6. 18. Refer to Example Code Ch 12-2: What is returned if factorial(0) is called? a. b. c. d. e.
0 1 2 nothing, factorial(0) causes infinite recursion nothing, factorial(0) produces a run-time error
ANS: B With factorial(0) x > 1 is not true, so the base case is executed and 1 is returned. Therefore, although ordinarily 0 * a value = 0, factorial(0) is computed as 1, as defined. 19. Refer to Example Code Ch 12-2: How many times is the factorial method called with factorial(5)? Include the original method call in your counting. a. b. c. d. e.
1 4 5 6 7
ANS: C The method is first invoked with factorial(5), which in turn returns 5 * factorial(4), so factorial is invoked again, which in turn returns 4 * factorial(3), so factorial is invoked again, which in turn returns 3 * factorial(2), so factorial is invoked again, which in turn returns 2 * factorial(1), so factorial is invoked again, and finally factorial(1)invokes the base case and returns 1. So, factorial was invoked 5 times.
20. Refer to Example Code Ch 12-2: What condition defines the base case for this method? a. b. c. d. e.
(x > 1) (x == 1) (x == 0) (x <= 0) (x <= 1)
ANS: E The if condition is (x > 1) but this is the recursive case, so the base case is the opposite condition. The opposite of (x > 1) is (x <= 1). Example Code Ch 12-3 Given the two recursive methods shown below, foo and bar. Assume int[] a = {6, 2, 4, 6, 2, 1, 6, 2, 5} public int foo(int[] a, int b, int j) { if (j < a.length) if (a[j] != b) return foo (a, b, j+1); else return foo (a, b, j+1) + 1; else return 0; } public int bar(int[] a, int j) { if (j < a.length) return a[j] + bar(a, j+1); else return 0; } 21. Refer to Example Code 12-3: What is the result of calling foo(a, 2, 0)? a. b. c. d. e.
0 1 2 3 4
ANS: C The method foo counts the number of occurrences of the int parameter in the second position in the array starting at the index given as the third parameter. So, foo(a, 2, 0) finds the number of 2s in a. 2 appears 3 times in array a. 22. Refer to Example Code 12-3: What is the result of calling foo(a, 3, 0)? a. b. c. d. e.
0 1 2 3 4
ANS: A
The method foo counts the number of occurrences of the int parameter in the second position in the array starting at the index given as the third parameter. So, foo(a, 3, 0) finds the number of 3s in a. There are none. 23. Refer to Example Code 12-3: What is the result of calling foo(a, 2, 9)? a. b. c. d. e.
0 1 2 3 4
ANS: A The method foo counts the number of occurrences of the int parameter in the second position in the array starting at the index given as the third parameter. So, foo(a, 2, 9) results in the base case being executed immediately becuase 9 == a.length and the base case returns 0. 24. Refer to Example Code 12-3: What is the result of calling bar(a, 0)? a. b. c. d. e.
0 5 6 12 34
ANS: E The bar method recursively sums the elements of array a starting at the location of the second parameter. Since the starting point is location 0, this call sums all elements of a which equals 34. 25. Refer to Example Code 12-3: What is the result of calling bar(a, 8)? a. b. c. d. e.
0 5 6 12 34
ANS: B The bar method recursively sums the elements of array a starting at the location of the second parameter (8 in this case). So bar(a, 8) sums up only the last element in the array, 5, and so 5 is returned. 26. Recall the Towers of Hanoi recursive solution for this problem. If there are two disks to move from one Tower to another, how many disk movements would it take to solve the problem using the recursive solution? a. b. c. d. e.
0 1 2 3 4
ANS: D
The Towers of Hanoi solution requires using the previous solution twice + 1 extra move. To solve it for 1 disk, it takes 1 move. To solve it for 2 disks, it takes using the solution for 1 disk twice + 1, or 1 move + 1 move + 1 move = 3 moves. We capture this in the equation 2n - 1 where n is the number of disks. 27. Recall the Towers of Hanoi recursive solution for this problem. If there are six disks to move from one Tower to another, how many disk movements would it take to solve the problem using the recursive solution? a. b. c. d. e.
6 13 31 63 127
ANS: D The Towers of Hanoi solution requires using the previous solution twice + 1 extra move. To solve it for 1 disk, it takes 1 move. To solve it for 2 disks, it takes using the solution for 1 disk twice + 1 extra move, or 1 move + 1 move + 1 extra move = 3 moves. We capture this in the equation 2n - 1 where n is the number of disks. For 3 disks this takes 7 moves, for 4 disks this takes 15 moves, for 5 disks this takes 31 moves and for 6 disks this takes 63 moves. 28. Recall the Towers of Hanoi recursive solution for this problem. The solution to the Towers of Hanoi has a(n) __________ complexity. a. b. c. d. e.
linear polynomial logarithmic exponential bad
ANS: D The complexity for Towers of Hanoi is 2n - 1, which is known as exponential because, as n increases by 1, the number of moves doubles, or the complexity increases exponentially. Example Code Ch 12-4 The following recursive method recognizes whether a String parameter consists of a specific pattern and returns true if the String has that pattern, false otherwise. public boolean patternRecognizer(String a) { if (a == null) return false; else if (a.length() == 1 || (a.length() == 2 && a.charAt(0) == a.charAt(1))) return true; else if (a.length() == 2 && a.charAt(0) != a.charAt(1)) return false; else if (a.charAt(0) == a.charAt(a.length() - 1)) return patternRecognizer(a.substring(1,a.length()-1)); else return false; } 29. Refer to Example Code Ch 12-4: Which String of the following would result in patternRecognizer returing true?
a. b. c. d. e.
"abcba" "aaabbb" "abcde" "aabba" All of these
ANS: A The method patternRecognizer returns true if the String is a palindrome. This can be seen by analyzing the code. If the String has 1 character, or 2 characters which are equal, it returns true, otherwise if the first and last characters are the same, it recursively calls itself with the substring starting at character 1 and going to the second to last character (so, since in "abcba" the first and last characters are the same, the method is called recursively with the substring "bcb"). Only if the first and last characters do not match is false returned. The only palindrome in the list of options is A, "abcba". 30. Refer to Example Code Ch 12-4: If the method is called as patternRecognizer(x) where x = "aa", what will the result be? a. b. c. d. e.
true false NullPointerException a run-time error infinite recursion
ANS: A One of the base cases tests to see if the String has 2 characters and if so, returns true if the two characters are the same. 31. Refer to Example Code Ch 12-4: If the statement a.substring(1, a.length() - 1 was changed to be a.substring(1, a.length()) then the method would a. b. c. d. e.
have infinite recursion unless the String was null always return true always return false return true only if all the characters of the String were the same return true only if the String had only two characters and they were the same
ANS: D The original method recursively calls itself with a substring equal to the String minus the first and last characters. This new version would recursively call itself with a substring equal to the String minus the first character. The method would return true if the first character of the String (or substring) equaled the last character. Since the substring for each recursive call is the same as the previous String less the first character, it winds up comparing each character in the String to the last in the String and returning true only if each character of the String equals the last character. This means all of the characters are the same.
PROBLEM
1. Provide a definition for the following terms as they relate to programming: recursion, indirect recursion and infinite recursion. ANS: Recursion: writing a method that calls itself. Indirect recursion: writing a method that calls other methods that call the original method so that the recursion is not done directly through the first method. Infinite recursion: recursion where the recursion is never stopped by a base case because either the base case was not defined, or the base case is never reached. 2. Explain what a "base case" is in a recursive method. ANS: The part of a recursive method that does not call itself (either directly or indirectly) to calculate the answer is called the base case. This is the case that stops the method, stopping otherwise infinite recursion. Every well written recursive method will have at least one base case. 3. Rewrite the following iterative method as a recursive method that computes the same thing. Note: your recursive method will require an extra parameter. public int iterative1(int x) { int count = 0, factor = 2; while (factor < x) { if (x % factor == 0) count++; factor++; } return count; } ANS: public int recursion1(int x, int y) { if (y >= x) return 0; else if (x % y == 0) return 1 + recursion1(x, y + 1); else return recursion(x, y + 1); } where this method is called with y =2 initially 4. Rewrite the following iterative method as a recursive method that computes the same thing. Note: your recursive method will require an extra parameter. public String reversal(String x) { int y = x.length(); String s = ""; for (int j = y - 1; j >= 0; j--) s += x.charAt(j); return s; }
ANS: public String reversal(String x, int j) { if (j < 0) return ""; else return x.charAt(j) + reversal(x, j-1); } where the recursive reversal is called with j = x.length() - 1. 5. Rewrite the following iterative method as a recursive method that returns the same String. public String listOfNumbers() { String s = ""; for (j = 1; j < 10; j++) s += j; return s; } ANS: public String listOfNumbers(int j) { if (j == 10) return ""; else return ""+ j + listOfNumbers(j+1); } where the recursive listOfNumbers is called with j = 1. 6. Describe how to solve the Towers of Hanoi problem using 4 disks (that is, write down move for move how to solve the problem). ANS: Move disk from 1 to 2 Move disk from 1 to 3 Move disk from 2 to 3 Move disk from 1 to 2 Move disk from 3 to 1 Move disk from 3 to 2 Move disk from 1 to 2 Move disk from 1 to 3 Move disk from 2 to 3 Move disk from 2 to 1 Move disk from 3 to 1 Move disk from 2 to 3 Move disk from 1 to 2 Move disk from 1 to 3 Move disk from 2 to 3 7. For the Towers of Hanoi problem, show how many moves it will take to solve the problem with 5 disks, 6 disks, 7 disks, 8 disks, 9 disks, and 10 disks. ANS: For 5 disks, it takes 31 moves For 6 disks, it takes 63 moves
For 7 disks, it takes 127 moves For 8 disks, it takes 255 moves For 9 disks, it takes 511 moves For 10 disks, it takes 1023 moves 8. Assume a function g(x) is defined as follows where x is an int parameter: g(x) = g(x - 1) * g (x - 3) if x is even and x > 3 = g(x - 2) if x is odd and x > 3 = x otherwise Write a recursive method to compute g. ANS: public int g(int x) { if (x > 3 && x % 2 == 0) return g(x - 1) * g (x - 3); else if (x > 3) return g(x - 2); else return x; } 9. Demonstrate how factorial(4) is computed given the following recursive method for factorial: public int factorial(int n) { if (n > 1) return factorial(n - 1) * n; else return 1; } ANS: factorial(4) = factorial(3) * 4 factorial(3) = factorial(2) * 3 factorial(2) = factorial(1) * 2 factorial(1) = 1 factorial(2) = 1 * 2 = 2 factorial(3) = 2 * 3 = 6 factorial(4) = 6 * 4 = 24 10. Describe the difference(s) between the following two sets of code, neither of which reaches a terminating condition. public void forever1() { while (true); } public void forever2() { forever2(); } ANS:
The method forever1 is iterative and so, since the while loop condition is always true, the method never exits the loop. The method forever2 is recursive, so that each time it is called, it requires method handling mechanisms (which use an entity called the run-time stack). So, while neither method will terminate naturally, forever2 takes more time and will eventually run out of run-time stack space resulting in an Exception being thrown and the program terminating. 11. The game of high-low is one where one person selects a number between 1 and 100 and a user tries to guess it by guessing a number and being told if the guessed number is the right number, too low or too high. The user repeats guessing until getting the correct answer. A logical user will always guess at the midpoint of the possible values (for instance, the first guess would be 50 followed by either 25 or 75, etc). Write a recursive method to play the game of high-low by having the computer guess a midpoint. The method should receive three parameters, the number itself, the lowest value in the range and the highest value in the range and return the number of guesses that it took to guess the right number. ANS: public int highLow(int guess, int low, int high) { int mid = (low + high) / 2; if (mid == guess) return 1; else if (mid < guess) return highLow(guess, mid, high) + 1; else return highLow(guess, low, mid) + 1; } 12. Recursion is a popular programming tool but beginning programmers tend to shy away from it. Why do you suppose this is true? ANS: Unlike iterative and conditional control structures, recursion is a new way of thinking for most programmers. The idea of seeing a solution by defining it in terms of itself seems natural but is not a mechanism that most students are taught to use. Therefore, recursion is often difficult. Further, debugging recursive methods is often very difficult because the logical and run-time errors are harder to track down. 13. Write a recursive method called numSegments(int order) that yields the number of line segments in a Koch snowflake of order order. ANS: public int numSegments(int order) { return (order <= 1) ? 3 : 4 * numSegments(order - 1); }
14. The Euclidean algorithm for calculating the greatest common divisor (gcd) of two integers a and b is: "If a is a nonnegative integer, b is a positive integer, and r = a mod b, then gcd(a,b) = gcd(b,r). Write a recursive method that uses the Euclidean algorithm to calculate the gcd. ANS: int gcd(int a, int b) { int r = a;
if (a >= 0 && b > 0) r = gcd(b, a % b); return r; }
Java Software Solutions, 9e (Lewis/Loftus) Chapter 13 Collections TRUE/FALSE 1. An Abstract Data Type is a data structure; that is, it is the listing of the instance data and the visibility modifiers for those instance data. ANS: F An Abstract Data Type includes the data structure but also includes the methods implemented to access/manipulate the data structure. 2. The push and enqueue operations are essentially the same operations. push is used for stacks and enqueue is used for queues. ANS: F While both operations are "add" or "insert" operations for their respective Abstract Data Types, they differ in that push always adds at the top (or front) of the stack while enqueue always adds at the rear of the queue. 3. The Abstract Data Type (ADT) is thought of as abstract because the operations that are to be implemented are separated from the actual implementation; that is, an ADT can be implemented in more than one way and that implementation is separate from how we might use the ADT. ANS: T The importance of the ADT is that the operations are implemented as we would expect so that the operation is performed correctly even if we do not know how the operation is implemented. In this way, we assume that a queue adds at the rear and removes from the front so that we have a FIFO access even though we do not know how the queue is implemented itself. 4. An array is a list ADT. ANS: F An array is a data structure that can be used to store a list of values but the array does not have operations already implemented to perform List operations such as add to the end or delete a given value. 5. A linked list that contains six Nodes will have six reference pointers. ANS: F In order to access the linked list, there needs to be a seventh reference pointer, at least -- one that references the first item in the list. 6. The linked list is superior in all ways to the array when it comes to implementing a list. ANS: F
The advantage of the linked list is that it is dynamic while the array is static. However, the array supports random access (the ability to access any element of the array easily) whereas a linked list does not support this (to access the 8th element, the first 7 elements must be traversed). So, the linked list has a major disadvantage, and even though it is dynamic, many programmers choose to use an array to implement a list because of this drawback. 7. Queues and stacks can be implemented using either arrays or linked lists. ANS: T The queue and the stack are both Abstract Data Types. Their method of implementation is immaterial; it is the operations (enqueue, dequeue, push, pop) that define them. So both ADTs can be implemented using either arrays or linked lists. 8. In order to input a list of values and output them in order, you could use a queue. In order to input a list of values and output them in opposite order, you could use a stack. ANS: T The queue provides First-in First-out access, so the items would be accessed in the order that they were entered. The stack provides Last-in First-out access, so the items would be accessed in the opposite order that they were entered. 9. All classes are considered Abstract Data Types. ANS: F To be considered an Abstract Data Type, the type must define a data structure and the methods to manipulate the data structure. However, a programmer does not have to set up a data structure in this way. For instance, if the instance data are made public, then there is no need to implement methods to manipulate those instance data; they can be directly modified from other classes. Therefore, just because a class exists does not mean that the class is an ADT. 10. All Abstract Data Types are defined as classes in Java. ANS: T In Java, all data are either primitives or classes. An ADT is a data structure, so it is more than just a primitive type, but a structure of different types. Therefore, the ADT must be defined in a class. Not all classes are necessarily ADTs, but all ADTs are defined as classes. 11. It is possible to restrict the type of object which is stored within a Java collection by using a generic type when the collection is declared. ANS: T That is precisely the function of generics -- to provide a way to specify the precise type of object to which the collection is restricted. 12. Trees and graphs, because they are dynamic in nature, cannot be implemented using Java arrays. ANS: F
While it is true that any given array has a fixed size, and therefore the maximum current size (number of nodes) in a tree or graph is limited to the size of its underlying array, one can allocate a larger array, copy the elements from the original array into the new array, and continue expanding the implementation in this manner. This technique succeeds because Java arrays are Objects, and the mechanism to access all Objects is via references. In other languages (like C, C++, C#, Pascal, etc.) arrays are not objects and so this technique would fail. 13. A bi-directional list is an example of a non-linear data structure. ANS: T Although a bi-directional list has more than one link in each node, when you draw a picture of a bidirectional list it still is linear. 14. The only difference between a stack and a queue is that stacks operate using FIFO and queues operate using LIFO. ANS: F This is exactly backwards. Stacks operate using last-in-first-out (LIFO) while queues operate using first-in-first-out (FIFO). 15. Generics provide a mechanism for ensuring that collections are heterogeneous rather than homogeneous. ANS: F Generics force collections to store objects all of the same type (homogeneous), not possibly dissimilar types (heterogeneous). MULTIPLE CHOICE 1. An array can be classified as what type of object? a. b. c. d. e.
dynamic ordered first-in first-out heterogeneous collection
ANS: E An array stores a group of items and is dubbed a collection type, as opposed to other types that can store a single item. There are numerous collection types, the array being one composed only of homogeneous items (the array stores multiple items but they all must be of the same type). 2. A collection where the items stored there are of different types is referred to as a(n) ________ type. a. b. c. d. e.
homogeneous heterogeneous dynamic abstract vector
ANS: B
The term heterogeneous means that the elements are different types. In Java, classes can store heterogeneous types. For instance one instance data might be an int and another a String and a third a double. Arrays on the other hand are homogeneous types because every element stored in the array is the same type. 3. Which of the following is considered an Abstract Data Type? a. b. c. d. e.
array reference variable any of the primitive types vector All of these
ANS: D An Abstract Data Type comprises a data structure and the methods to manipulate and access the data structure. Of those listed, only the vector combines both of these. The array is a data structure but without the methods (such as an insert method or a search method) while reference variables and primitive types are data but not data structures. 4. Abstract Data Types have which of the following object-oriented features? a. b. c. d. e.
information hiding inheritance polymorphism message passing All of these
ANS: C All of these answers are types of object-oriented features. An Abstract Data Type encapsulates a data structure and the methods to manipulate the data structure such that information hiding is preserved. Therefore, all ADTs make use of information hiding so that the data structure cannot be manipulated directly from outside of the ADT, but the other object-oriented features are not required. 5. Which of the following criticisms of an array is applicable to a Java array? a. b. c. d. e.
It is an inefficient structure to access random elements. It only supports first-in first-out types of accesses. It is fixed in size (static). It cannot be used to create an Abstract Data Type such as a queue or stack. All of these
ANS: C The size of any array in Java is fixed when the array is instantiated. If, in adding elements to the array, it becomes filled, the array itself cannot change in size. A new array could be created with the old array elements moved into the new array, but this is inefficient. 6. The advantage of creating a BookList for a list of books using a linked list instead of using an array is that the linked list a. b. c. d. e.
offers easier access to a random element in the list uses less memory is easier to implement and debug can store types other than Books, unlike the array is dynamic and so can be any size needed
ANS: E The advantage of the linked list over the array to implement such data structures as lists of items is that more items can always be added to it. This is known as a dynamic structure, unlike the fixed-sized array which is known as a static structure. Disadvantages of the linked list are that they are not easy to access randomly, unlike an array, and they are often more difficult to implement and debug than code using arrays. Further, while the linked list stores one Node for each item in the list, each Node requires at least two data items, the information, and a link to the next Node, so they may use more memory than an array. 7. A linked list that stores int values would be comprised of a group of Nodes. We might define the Node by a. class Node { Node next; } b. class Node { int next; } c. class Node { int data; } d. class Node { int data; Node next; } e. class Node { int[ ] data; Node next; } ANS: D The linked list stores int values, so each Node requires an int data type. Further, because it is a linked list, each node must contain a reference to the next Node, which is defined as Node next; where next is the reference. Example Code Ch 13-2 Assume that a linked list is implemented using the Node class where a Node contains instance data of int info; and Node next; where next references the next Node in the linked list. Also assume that head references the first Node in the list. 8. Refer to Example Code Ch 13-2: Which of the following instructions would create an initially empty linked list? a. Node head = new Node(); b. Node head = Node
c. Node head = null; d. Node head = new Node(0); e. Node head = list; ANS: C The initial linked list will be empty, and so head should be null to indicate that there are no Nodes in the list yet. The answer in B is syntactically invalid, and the answers in A and D may be invalid depending on what parameter(s) the Node constructor expects, but in any event, the answers in A and D will create a Node, and therefore the initial list will not be empty. 9. Refer to Example Code Ch 13-2: Assume Node temp references the last element of the linked list. Which of the following conditions is true about temp? a. b. c. d. e.
(temp.info == 0) (temp.next == null) (temp == head) (temp == null) (temp.next == null && temp.info == null)
ANS: B Since temp is the last Node in the list, there is no next node, so temp.next is null. The answer in E is incorrect because temp references the last Node and this Node does have a value, so temp.info will equal some int value. 10. Refer to Example Code Ch 13-2: Assume that the linked list has at least two Nodes in it. Which of the following instructions will return the second int value in the list? a. b. c. d. e.
return head.info; return head.next.info; return head.next.next.info; return head.next.next.next.info; It is not possible to return the second int value in the list using head.
ANS: B The variable head references the first Node in the list, so that head.info is the first int value. The statement head.next references the second Node in the list, so head.next.info references the second Node's data item. 11. Refer to Example Code Ch 13-2: Assume Node temp is currently set equal to head. Which of the following while loops could be used to iterate through each element of a linked list? a. while (head != null) head = temp.next; b. while (temp != null) temp = temp.next; c. while (head != null) temp = temp.next; d. while (head != null) head = head.next; e. while (temp != null)
head = head.next; ANS: B To iterate through the list, we will use a different reference variable than head so that we do not lose our reference to the list, so we use temp instead. To iterate through the list, temp starts at head and continues until temp becomes null (it no longer references a node). To move to the next item in the list, temp is updated to be temp.next. The answer in D loses the reference to the list and so is not what we would desire to do. The other loops have incorrect logic resulting in either infinite loops, or loops that cause run-time exceptions. 12. Refer to Example Code Ch 13-2: Assume Node2 is defined as follows: int data; Node2 a, b; where a refers to the Node2 before this one in a linked list and b refers to the Node2 after this one in a linked list. Node2 could then be used to create which of the following variations of a linked list? a. b. c. d. e.
singly linked list doubly linked list singly linked list with a header node singly linked list with a top node circularly linked list
ANS: B Because each item in the linked list has a reference to both the next node and the previous node, the list is known as a doubly linked list. With only a reference to the next node, the list would be known as a singly linked list. A list with a header node has a special node which has references to both the first node in the list and the last node in the list (often referred to as a head and a tail). Example Code Ch 13-3 Assume that countIt and sumIt methods receive a parameter, Node temp, which references the first Node in a linked list where Node is a class that consists of data instances int info and Node next, and further assume that the int variables count and sum are initialized to 0. 13. Refer to Example Code Ch 13-3: Which of the following methods could be used to count the number of items in the linked list? a. public int countIt(Node temp) { while (temp != null) { count += temp.info; temp = temp.next; } return count; } b. public int countIt(Node temp) { while (temp != null) { count++; } return count; }
c. public int countIt(Node temp) { while (count != null) { count++; temp = temp.next; } return count; } d. public int countIt(Node temp) { while (temp != head) { count++; temp = temp.next; } return count; } e. public int countIt(Node temp) { while (temp != null) { if (next != null) count++; temp = temp.next; } return count; } ANS: C Answer A sums all items in the array. Answer B does not advance temp to reference the next Node, and is, therefore, an infinite loop. Answer C properly counts each Node and moves on to the next Node. Answer D has the wrong loop condition and answer E counts all of the items in the list except for the last one. 14. Refer to Example Code Ch 13-3: Which of the following methods could be used to sum the number of items in the linked list? a. public int sumIt(Node temp) { while (temp != null) { sum += temp.info; temp = temp.next; } return sum; } b. public int sumIt(Node temp) { while (temp != null) { sum += temp.info; } return sum;
} c. public int sumIt(Node temp) { while (temp != null) { sum++; temp = temp.next; } return sum; } d. public int sumIt(Node temp) { while (temp != head) { sum += temp.info; temp = temp.next; } return sum; } e. public int sumIt(Node temp) { while (temp != null) { if (next != null) sum += temp.info; temp = temp.next; } return sum; } ANS: A Answer B does not advance temp to reference the next Node, and is, therefore, an infinite loop. Answer C counts the number of items in the list but does not sum up the values of these items. Answer D has the wrong loop condition and answer E counts all of the items in the list except for the last one. Example Code Ch 13-4 Assume that a linked list consists of Node objects, where Node has two instance data, int info and Node next. The linked list stores in the info data, 20, 11, 13, 19, 12, 14 in that order. Assume that Node head references the first item in the list. 15. Refer to Example Code Ch 13-4: What will be returned by the following? return head.next.next.next.info; a. b. c. d. e.
20 11 13 19 12
ANS: D
The variable head references the first item, which stores 20, head.next references the second item, which stores 11, head.next.next references the third item, which stores 13, and head.next.next.next references the fourth item, which stores 19. 16. Refer to Example Code Ch 13-4: What will be returned by the following? return head.info; a. b. c. d. e.
20 11 13 19 12
ANS: A The variable head references the first item, so head.data is the instance data info of the first item which stores 20. 17. Refer to Example Code Ch 13-4: What will the following statement accomplish? head.next.next = head.next.next.next; a. b. c. d. e.
It will result in the list ending after 13. It will result in the value 13 being deleted from the list. It will result in the list ending after 19. It will result in the value 19 being deleted from the list. It will result in the list ending after 12.
ANS: B The reference head.next.next is of the second Node in the list's next instance data, or 11's next. By setting this Node's next field to be head.next.next.next, this Node now references the Node storing 19 rather than 13, so it deletes 13 from the list. 18. Refer to Example Code Ch 13-4: What is the result to the linked list of the following instructions? Assume that newNode is a Node, already constructed. newNode.data = 1; newNode.next = head.next; head.next = newNode; a. b. c. d. e.
The value 1 is inserted into the linked list before 20. The value 1 is inserted into the linked list after 20 and before 11. The value 1 is inserted into the linked list after 11 and before 13. The value 1 is inserted into the linked list after 13 and before 19. The value 1 is inserted into the linked list after 20 and the rest of the list is lost.
ANS: B The statement newNode.next = head.next; sets the new node's next field to equal the second item in the list, so the new node, which stores 1, is inserted before 11. The statement head.next = newNode resets the first Node's next field to reference the new node, so 1 is now inserted after 20 and before 11. 19. A variation of a linked list is a circular linked list where the last Node in the list has next = head rather than next = null. One problem with this type of list is that
a. it wastes memory space since head already points at the first Node, so the last one does not need to b. there is no ability to add a new Node at the end of the list since the last Node points at the first Node c. it is more difficult to traverse the list since the old terminating condition, (next == null), is no longer true for the last node d. a header Node for this type of list is more complex e. All of these ANS: C Answers A, B and D are not true. This list uses no more memory than an ordinary linked list; adding a Node at the end requires the same amount of effort as before, and a header Node would be no different than before. However, answer C is true: the decision of whether there is another Node in the list or not can no longer be determined by testing (next == null) since the last Node's next field is equal to head instead of null. 20. Which of the following is used to see the top item of a stack without removing it from the stack? a. b. c. d. e.
push pop peak see top
ANS: C The three commands associated with a stack are push, pop and peak. push adds a new element to the top of the stack, pop removes the top element off of the stack and peak returns the top of the stack without removing it. 21. One operation that we might want to implement on a stack and a queue is full, which determines if the data structure has room for another item to be added. This operation would be useful a. b. c. d. e.
only if the queue or stack is implemented using an array only if the queue or stack is implemented using a linked list only for a queue only for a stack None of these; a full operation is not useful at all
ANS: A Since the array is a static sized object, if it becomes filled, then any add type of operation, whether it is a list insert, a queue enqueue or a stack push, should be prevented. This can be determined by first checking to see if the structure is full or not. This is not necessary if the data structure is implemented using a linked list since we assume that there will always be dynamic memory available to add a new element. 22. What type of structure should be used to gain a last-in first-out access to data? a. b. c. d. e.
a vector an array a linked list a queue a stack
ANS: E The stack is a data structure that allows only a last-in first-out (LIFO) access. Queues offer only a first-in first-out (FIFO) access. The vector, array and linked list types all offer any form of access desired. 23. To simulate people waiting in a line, which data structure would you use? a. b. c. d. e.
a vector a set a list a queue a stack
ANS: D
The FIFO access of a queue is the same access of people waiting in line -- the first person in the line will be the first to leave the line (be helped, given access to whatever he/she was waiting for). So, simulations of any kind of line structure will use the queue data structure. 24. In a linked list in Java a. b. c. d. e.
the link is an object the link is a node the link is a reference the link is an int the link is a class
ANS: C In a linked list, the link is a reference to the next node. One follows the link by "dereferencing" -- that is, by examining the contents of the reference. Nodes are objects. Objects are instances of classes. The data portion of a node may well be an int, as well as any other types of data. 25. A linear data structure a. b. c. d. e.
always has more than one link per node is sometimes represented as a tree or a graph can have only a single link per node almost always is kept in sorted order, either ascending or descending None of these
ANS: C A linear data structure is one that, when you draw a picture of it, displays as a line of connected nodes. It is linear and it looks like a line. A simple list is an example of such a data structure so a linear data structure may have as few as one link per node. Data structures that display as trees or graphs are not linear; they are two-dimensional (at least). There is no requirement (or convention) that linear data structures be kept in any kind of order, sorted or otherwise. 26. A simple linear list a. b. c. d. e.
is an example of a degenerate tree is an example of a degenerate graph is an example of a degenerate digraph cannot be represented as a degenerate tree, graph, or digraph None of these
ANS: A
A simple linear list is directed, from its starting node to its end node. Neither graphs nor digraphs have a start node but, a tree does: the root of the tree. So, a simple linear list is an example of a degenerate tree, one which has a branching factor of one, with each node having but a single successor, beginning at the root, and ending at the single leaf (end node). 27. A dynamic data structure a. b. c. d. e.
almost always is implemented using lists of one sort or another is just a collection almost always is implemented using references (pointers) to objects can have a fixed size None of these
ANS: C A dynamic data structure is one that can grow and shrink during execution. In order to implement such a data structure in Java, one must use references (pointers) to objects. Java collections are but one set of examples of dynamic data structures provided by the Java libraries. Example Code Ch 13-5 Consider the following operations on a queue data structure that stores int values: Queue q = new Queue(); q.enqueue(3); q.enqueue(5); q.enqueue(9); System.out.println(q.dequeue()); // d1 q.enqueue(2); q.enqueue(4); System.out.println(q.dequeue()); // d2 System.out.println(q.dequeue()); // d3 q.enqueue(1); q.enqueue(8); 28. Refer to Example Code Ch 13-5: After this code executes, how many elements would remain in q? a. b. c. d. e.
0 4 5 6 7
ANS: B The constructor creates an initially empty queue. Each enqueue operation adds one int to the queue and each dequeue operation removes one int from the queue. There are 7 enqueue operations and 3 dequeue operations, leaving 4 int values in q at the end. 29. Refer to Example Code Ch 13-5: What value is returned by the last dequeue operation, denoted with a d3 as a comment. a. b. c. d. e.
3 5 9 2 4
ANS: C The dequeue operations remove the next item in the queue, so the dequeue in d1 removes 3, the dequeue in d2 removes 5 and the dequeue in d3 removes 9. 30. Refer to Example Code Ch 13-5: If we replace the System.out.println statements (denoted in comments as d1, d2 and d3) with the statement q.enqueue(q.dequeue()); q would contain which order of int values after all instructions have executed? a. b. c. d. e.
3, 5, 9, 2, 4, 1, 8 3, 5, 9, 1, 8, 2, 4 5, 9, 2, 4, 1, 8, 3 3, 2, 4, 5, 9, 1, 8 2, 4, 1, 8, 3, 5, 9
ANS: D The original order of int values in q is 3, 5, 9. At d1, the first item is dequeued and then enqueued resulting in 5, 9, 3. Two more enqueues result in 5, 9, 3, 2, 4. At d2 and d3, the first two items are dequeued and then enqueued resulting in 3, 2, 4, 5, 9. Finally, 1 and 8 are enqueued leaving q as 3, 2, 4, 5, 9, 1, 8. Example Code Ch 13-6 Assume a stack class stores int values. Consider the following sequence of instructions. Stack s = new Stack(); s.push(16); s.push(12); s.push(19); int x = s.pop(); s.push(5); s.push(9); s.push(4); int y = s.pop(); int z = s.pop(); 31. Refer to Example Code Ch 13-6: After the instructions execute, x has the value a. b. c. d. e.
16 12 19 0 None of these; the instruction int x = s.pop() results in an exception being thrown
ANS: C The stack offers a last-in first-out access, so at the point when s.pop() is first executed, the item removed is the last item pushed onto s, or 19. 32. Refer to Example Code Ch 13-6: After the instructions execute, z has the value a. b. c. d. e.
4 9 5 12 16
ANS: B
At that point that the int z = s.pop(); executes, a previous s.pop(); will have removed the most recently pushed item (4), so this pop removes the next most recently pushed item (9). PROBLEM Example Code Ch 13-1 The following is a class definition of a linked list Node: class Node { int info; Node next; } 1. Refer to Example Code Ch 13-1: Show the instructions required to create a linked list that is referenced by head and stores in order, the int values 3, 6 and 2. Assume that Node's constructor receives no parameters. ANS: Node head = new Node(); head.info = 3; head.next = new Node(); head.next.info = 6; head.next.next = new Node(); head.next.next.info = 2; head.next.next.next = null; 2. Refer to Example Code Ch 13-1: Assume that head references a linked list and stores in order, the int values 3, 2 and 6. Show the instructions needed to move the value 2 in front of the value 6 so that the list is now 3, 2 and 6. ANS: Node temp = head.next; head.next = head.next.next; head.next.next = temp; temp.next = null; 3. Refer to Example Code Ch 13-1: Assume that head references a linked list and stores in order, the int values 3, 6 and 2. Show the instructions needed to delete the Node with 3 so that head would reference the list 6 and 2. ANS: head = head.next; 4. Refer to Example Code Ch 13-1: Assume that head references a linked list, although we don't know what is currently stored in that list. Write a block of code using a try-catch block that will work through the entire linked list, printing each element out, stopping only when we have reached the end of the list because a NullPointerException is thrown. Once the Exception is thrown, output the number of elements found in the list. ANS: int count = 0;
try { Node temp = head; while (true) { System.out.println(temp.info); temp = temp.next; count++; } } catch (NullPointerException npe) { System.out.println("Number of elements in the list is " + count); } 5. A queue q stores int values. Show what q will look like after each of the following instructions is executed. q.enqueue(6); q.enqueue(12); q.enqueue(13); q.dequeue(); q.dequeue(); q.enqueue(19); q.enqueue(21); q.enqueue(22); q.dequeue(); q.enqueue(20); ANS: queue: q.enqueue(6); q.enqueue(12); q.enqueue(13); q.dequeue(); q.dequeue(); q.enqueue(19); q.enqueue(21); q.enqueue(22); q.dequeue(); q.enqueue(20);
Front --> Rear 6 6 12 6 12 13 12 13 13 13 19 13 19 21 13 19 21 22 19 21 22 19 21 22 20
6. A stack s stores int values. Show what s will look like after each of the following instructions is executed. s.push(5); s.push(1); s.push(4); s.push(3); s.pop(); s.push(2); s.pop(); s.pop(); s.push(8);
s.push(7); s.pop(); s.push(3); ANS: s.push(5); s.push(1); s.push(4); s.push(3); s.pop(); s.push(2); s.pop(); s.pop(); s.push(8); s.push(7); s.pop(); s.push(3);
Top --> Bottom 5 1 5 4 1 5 3 4 1 4 1 5 2 4 1 4 1 5 1 5 8 1 5 7 8 1 8 1 5 3 8 1
5 5
5 5
7. One use of a stack is to reverse the order of input. Write a method that reads a series of Strings from the keyboard (assume the Scanner class has been imported) and outputs the Strings in reverse order of how they were entered. The input will end with the String "end" but do not output the String "end". Assume that SStack is a stack that can store Strings. Remember to declare and instantiate your SStack in your method. ANS: public void reverseOrder() { SStack s = new SStack(); Scanner scanner = Scanner.create(System.in) String in = scanner.next(); while (!in.equals("end")) { s.push(in); in = scanner.next(); } while (!s.empty()) { System.out.println(s.pop()); } } 8. What is an ADT (Abstract Data Type) and why are ADTs considered to be abstract? ANS: An ADT is a collection of data and the particular operations that are allowed on that data. An ADT has a name, a domain of values, and a set of operations that can be performed. An ADT is considered to be abstract because the operations you can perform are separated from the underlying implementation; the details on how an ADT stores its data and accomplishes its methods are separate from the concept that it embodies.
9. An abstract data type not covered in detail in the chapter is the Set ADT. A Set is like a set as covered in Mathematics courses. For instance, a set of even numbers might be {2, 4, 8, 12, 18, 32}. List 6 operations that you might implement for a Set ADT. ANS: addElement, removeElement, isAnElementOf, intersect, union, subset. Others might include toString, superset, equals, compareTo, and difference. 10. Two abstract data types are the ordered list and the unordered list. Explain how these two ADTs are similar and how they differ. To answer this question, assume that you do not know how they are implemented (that is, whether they are implemented using an array or a linked list). ANS: The ordered list will require a mechanism to make sure that new elements are inserted in their appropriate place using some kind of ordering operation, whether this is an ordered insert or a sort. Since items are ordered, searching for and deleting an item might be simplified (for instance, if you are looking for a word in the dictionary and you have reached a word that is alphabetically beyond the word, then you know that you have gone too far or that the word is not in the dictionary). A deletion will have to maintain the ordering of the items in the list. In an unordered list, there is no order at all, so new items can be added at the end, simplifying the add/insert operation, and deleted items can be replaced by the last item in the list so that no shifting of elements is needed. Finally, in the unordered list, searching requires looking over every element until the item is found, or the end of the list is reached. 11. A double-ended queue, called a dequeue, is a queue that, instead of having single links in one direction, has a pair of links, one pointed in each direction. Dequeues allow one to "push" and "pop" information at either end. Is this ADT the same or different from a doubly linked list, as described in the textbook? ANS: This ADT is the same as a doubly linked list. Each node contains a pair of links, one pointed in each direction; information can be added or deleted at either end of the list; and nodes can store any kind of data. This illustrates the fact that data structures may go by many names, depending upon how one thinks about them. 12. What common exception(s) might arise when using an array? What common exception(s) might arise when using a linked list? ANS: In the array, an ArrayOutOfBoundsException or IndexOutOfBoundsException might arise if you use an array index that is either negative or larger than (or equal to) the size of the array. In the linked list, a NullPointerException will arise if you attempt to access an item that is equal to null. And, since the linked list uses dynamic memory, an OutOfMemoryException might also arise if you try to add to the list when additional memory is no longer available. 13. Challenge: Assume a function g(x) is defined as follows where x is an int parameter: g(x) = g(x - 1) * g (x - 3) if x is even and x > 3 = g(x - 2) if x is odd and x > 3 = x otherwise
Write a recursive method to compute g. In implementing a queue using an array, a problem might arise if the queue is implemented in such a way that items in the queue are inserted at the next available location and removed from the next leading position, but such that, once deleted, the emptied space is unused. The problem that arises is one where there is free space still in the array, but it is not usable because it is not at the end. Demonstrate this problem with a queue that is stored in an array of size 5 for the following instructions. Next, explain how you might resolve this problem. Queue q = new Queue(5); // assume the Queue constructor takes 5 as the size of the array q.enqueue(3); q.enqueue(4); q.enqueue(1); q.dequeue(); q.dequeue(); q.enqueue(6); q.enqueue(5); q.dequeue(); // at this point, there are only 2 items in the queue q.enqueue(7); // this enqueue can not occur, why?? ANS: Array index q.enqueue(3); q.enqueue(4); q.enqueue(1); q.dequeue(); q.dequeue(); q.enqueue(6); q.enqueue(5); q.dequeue(); q.enqueue(7);
0
1
//
2
3 3 3 3
4 4 4 4
1 1 1 1 1
6 6 5 6 5 7 cannot be added since 5 is in the last array element
To solve this problem of not being able to add to a non-full queue even though the last element in the queue is in the last available array location, we need to change the array into a circular array whereby the next element (7) can be added to the beginning of the array. This complicates the queue but is more memory efficient.
Java Software Solutions, 9e (Lewis/Loftus) Chapter 13 Collections TRUE/FALSE 1. An Abstract Data Type is a data structure; that is, it is the listing of the instance data and the visibility modifiers for those instance data. ANS: F An Abstract Data Type includes the data structure but also includes the methods implemented to access/manipulate the data structure. 2. The push and enqueue operations are essentially the same operations. push is used for stacks and enqueue is used for queues. ANS: F While both operations are "add" or "insert" operations for their respective Abstract Data Types, they differ in that push always adds at the top (or front) of the stack while enqueue always adds at the rear of the queue. 3. The Abstract Data Type (ADT) is thought of as abstract because the operations that are to be implemented are separated from the actual implementation; that is, an ADT can be implemented in more than one way and that implementation is separate from how we might use the ADT. ANS: T The importance of the ADT is that the operations are implemented as we would expect so that the operation is performed correctly even if we do not know how the operation is implemented. In this way, we assume that a queue adds at the rear and removes from the front so that we have a FIFO access even though we do not know how the queue is implemented itself. 4. An array is a list ADT. ANS: F An array is a data structure that can be used to store a list of values but the array does not have operations already implemented to perform List operations such as add to the end or delete a given value. 5. A linked list that contains six Nodes will have six reference pointers. ANS: F In order to access the linked list, there needs to be a seventh reference pointer, at least -- one that references the first item in the list. 6. The linked list is superior in all ways to the array when it comes to implementing a list. ANS: F
The advantage of the linked list is that it is dynamic while the array is static. However, the array supports random access (the ability to access any element of the array easily) whereas a linked list does not support this (to access the 8th element, the first 7 elements must be traversed). So, the linked list has a major disadvantage, and even though it is dynamic, many programmers choose to use an array to implement a list because of this drawback. 7. Queues and stacks can be implemented using either arrays or linked lists. ANS: T The queue and the stack are both Abstract Data Types. Their method of implementation is immaterial; it is the operations (enqueue, dequeue, push, pop) that define them. So both ADTs can be implemented using either arrays or linked lists. 8. In order to input a list of values and output them in order, you could use a queue. In order to input a list of values and output them in opposite order, you could use a stack. ANS: T The queue provides First-in First-out access, so the items would be accessed in the order that they were entered. The stack provides Last-in First-out access, so the items would be accessed in the opposite order that they were entered. 9. All classes are considered Abstract Data Types. ANS: F To be considered an Abstract Data Type, the type must define a data structure and the methods to manipulate the data structure. However, a programmer does not have to set up a data structure in this way. For instance, if the instance data are made public, then there is no need to implement methods to manipulate those instance data; they can be directly modified from other classes. Therefore, just because a class exists does not mean that the class is an ADT. 10. All Abstract Data Types are defined as classes in Java. ANS: T In Java, all data are either primitives or classes. An ADT is a data structure, so it is more than just a primitive type, but a structure of different types. Therefore, the ADT must be defined in a class. Not all classes are necessarily ADTs, but all ADTs are defined as classes. 11. It is possible to restrict the type of object which is stored within a Java collection by using a generic type when the collection is declared. ANS: T That is precisely the function of generics -- to provide a way to specify the precise type of object to which the collection is restricted. 12. Trees and graphs, because they are dynamic in nature, cannot be implemented using Java arrays. ANS: F
While it is true that any given array has a fixed size, and therefore the maximum current size (number of nodes) in a tree or graph is limited to the size of its underlying array, one can allocate a larger array, copy the elements from the original array into the new array, and continue expanding the implementation in this manner. This technique succeeds because Java arrays are Objects, and the mechanism to access all Objects is via references. In other languages (like C, C++, C#, Pascal, etc.) arrays are not objects and so this technique would fail. 13. A bi-directional list is an example of a non-linear data structure. ANS: T Although a bi-directional list has more than one link in each node, when you draw a picture of a bi-directional list it still is linear. 14. The only difference between a stack and a queue is that stacks operate using FIFO and queues operate using LIFO. ANS: F This is exactly backwards. Stacks operate using last-in-first-out (LIFO) while queues operate using first-in-first-out (FIFO). 15. Generics provide a mechanism for ensuring that collections are heterogeneous rather than homogeneous. ANS: F Generics force collections to store objects all of the same type (homogeneous), not possibly dissimilar types (heterogeneous). MULTIPLE CHOICE 1. An array can be classified as what type of object? a. b. c. d. e.
dynamic ordered first-in first-out heterogeneous collection
ANS: E An array stores a group of items and is dubbed a collection type, as opposed to other types that can store a single item. There are numerous collection types, the array being one composed only of homogeneous items (the array stores multiple items but they all must be of the same type). 2. A collection where the items stored there are of different types is referred to as a(n) ________ type. a. b. c. d. e.
homogeneous heterogeneous dynamic abstract vector
ANS: B
The term heterogeneous means that the elements are different types. In Java, classes can store heterogeneous types. For instance one instance data might be an int and another a String and a third a double. Arrays on the other hand are homogeneous types because every element stored in the array is the same type. 3. Which of the following is considered an Abstract Data Type? a. b. c. d. e.
array reference variable any of the primitive types vector All of these
ANS: D An Abstract Data Type comprises a data structure and the methods to manipulate and access the data structure. Of those listed, only the vector combines both of these. The array is a data structure but without the methods (such as an insert method or a search method) while reference variables and primitive types are data but not data structures. 4. Abstract Data Types have which of the following object-oriented features? a. b. c. d. e.
information hiding inheritance polymorphism message passing All of these
ANS: C All of these answers are types of object-oriented features. An Abstract Data Type encapsulates a data structure and the methods to manipulate the data structure such that information hiding is preserved. Therefore, all ADTs make use of information hiding so that the data structure cannot be manipulated directly from outside of the ADT, but the other object-oriented features are not required. 5. Which of the following criticisms of an array is applicable to a Java array? a. b. c. d. e.
It is an inefficient structure to access random elements. It only supports first-in first-out types of accesses. It is fixed in size (static). It cannot be used to create an Abstract Data Type such as a queue or stack. All of these
ANS: C The size of any array in Java is fixed when the array is instantiated. If, in adding elements to the array, it becomes filled, the array itself cannot change in size. A new array could be created with the old array elements moved into the new array, but this is inefficient. 6. The advantage of creating a BookList for a list of books using a linked list instead of using an array is that the linked list a. b. c. d. e.
offers easier access to a random element in the list uses less memory is easier to implement and debug can store types other than Books, unlike the array is dynamic and so can be any size needed
ANS: E The advantage of the linked list over the array to implement such data structures as lists of items is that more items can always be added to it. This is known as a dynamic structure, unlike the fixed-sized array which is known as a static structure. Disadvantages of the linked list are that they are not easy to access randomly, unlike an array, and they are often more difficult to implement and debug than code using arrays. Further, while the linked list stores one Node for each item in the list, each Node requires at least two data items, the information, and a link to the next Node, so they may use more memory than an array. 7. A linked list that stores int values would be comprised of a group of Nodes. We might define the Node by a. class Node { Node next; } b. class Node { int next; } c. class Node { int data; } d. class Node { int data; Node next; } e. class Node { int[ ] data; Node next; } ANS: D The linked list stores int values, so each Node requires an int data type. Further, because it is a linked list, each node must contain a reference to the next Node, which is defined as Node next; where next is the reference. Example Code Ch 13-2 Assume that a linked list is implemented using the Node class where a Node contains instance data of int info; and Node next; where next references the next Node in the linked list. Also assume that head references the first Node in the list. 8. Refer to Example Code Ch 13-2: Which of the following instructions would create an initially empty linked list? a. Node head = new Node(); b. Node head = Node
c. Node head = null; d. Node head = new Node(0); e. Node head = list; ANS: C The initial linked list will be empty, and so head should be null to indicate that there are no Nodes in the list yet. The answer in B is syntactically invalid, and the answers in A and D may be invalid depending on what parameter(s) the Node constructor expects, but in any event, the answers in A and D will create a Node, and therefore the initial list will not be empty. 9. Refer to Example Code Ch 13-2: Assume Node temp references the last element of the linked list. Which of the following conditions is true about temp? a. b. c. d. e.
(temp.info == 0) (temp.next == null) (temp == head) (temp == null) (temp.next == null && temp.info == null)
ANS: B Since temp is the last Node in the list, there is no next node, so temp.next is null. The answer in E is incorrect because temp references the last Node and this Node does have a value, so temp.info will equal some int value. 10. Refer to Example Code Ch 13-2: Assume that the linked list has at least two Nodes in it. Which of the following instructions will return the second int value in the list? a. b. c. d. e.
return head.info; return head.next.info; return head.next.next.info; return head.next.next.next.info; It is not possible to return the second int value in the list using head.
ANS: B The variable head references the first Node in the list, so that head.info is the first int value. The statement head.next references the second Node in the list, so head.next.info references the second Node's data item. 11. Refer to Example Code Ch 13-2: Assume Node temp is currently set equal to head. Which of the following while loops could be used to iterate through each element of a linked list? a. while (head != null) head = temp.next; b. while (temp != null) temp = temp.next; c. while (head != null) temp = temp.next; d. while (head != null) head = head.next; e. while (temp != null)
head = head.next; ANS: B To iterate through the list, we will use a different reference variable than head so that we do not lose our reference to the list, so we use temp instead. To iterate through the list, temp starts at head and continues until temp becomes null (it no longer references a node). To move to the next item in the list, temp is updated to be temp.next. The answer in D loses the reference to the list and so is not what we would desire to do. The other loops have incorrect logic resulting in either infinite loops, or loops that cause run-time exceptions. 12. Refer to Example Code Ch 13-2: Assume Node2 is defined as follows: int data; Node2 a, b; where a refers to the Node2 before this one in a linked list and b refers to the Node2 after this one in a linked list. Node2 could then be used to create which of the following variations of a linked list? a. b. c. d. e.
singly linked list doubly linked list singly linked list with a header node singly linked list with a top node circularly linked list
ANS: B Because each item in the linked list has a reference to both the next node and the previous node, the list is known as a doubly linked list. With only a reference to the next node, the list would be known as a singly linked list. A list with a header node has a special node which has references to both the first node in the list and the last node in the list (often referred to as a head and a tail). Example Code Ch 13-3 Assume that countIt and sumIt methods receive a parameter, Node temp, which references the first Node in a linked list where Node is a class that consists of data instances int info and Node next, and further assume that the int variables count and sum are initialized to 0. 13. Refer to Example Code Ch 13-3: Which of the following methods could be used to count the number of items in the linked list? a. public int countIt(Node temp) { while (temp != null) { count += temp.info; temp = temp.next; } return count; } b. public int countIt(Node temp) { while (temp != null) { count++; } return count; }
c. public int countIt(Node temp) { while (count != null) { count++; temp = temp.next; } return count; } d. public int countIt(Node temp) { while (temp != head) { count++; temp = temp.next; } return count; } e. public int countIt(Node temp) { while (temp != null) { if (next != null) count++; temp = temp.next; } return count; } ANS: C Answer A sums all items in the array. Answer B does not advance temp to reference the next Node, and is, therefore, an infinite loop. Answer C properly counts each Node and moves on to the next Node. Answer D has the wrong loop condition and answer E counts all of the items in the list except for the last one. 14. Refer to Example Code Ch 13-3: Which of the following methods could be used to sum the number of items in the linked list? a. public int sumIt(Node temp) { while (temp != null) { sum += temp.info; temp = temp.next; } return sum; } b. public int sumIt(Node temp) { while (temp != null) { sum += temp.info; } return sum;
} c. public int sumIt(Node temp) { while (temp != null) { sum++; temp = temp.next; } return sum; } d. public int sumIt(Node temp) { while (temp != head) { sum += temp.info; temp = temp.next; } return sum; } e. public int sumIt(Node temp) { while (temp != null) { if (next != null) sum += temp.info; temp = temp.next; } return sum; } ANS: A Answer B does not advance temp to reference the next Node, and is, therefore, an infinite loop. Answer C counts the number of items in the list but does not sum up the values of these items. Answer D has the wrong loop condition and answer E counts all of the items in the list except for the last one. Example Code Ch 13-4 Assume that a linked list consists of Node objects, where Node has two instance data, int info and Node next. The linked list stores in the info data, 20, 11, 13, 19, 12, 14 in that order. Assume that Node head references the first item in the list. 15. Refer to Example Code Ch 13-4: What will be returned by the following? return head.next.next.next.info; a. b. c. d. e.
20 11 13 19 12
ANS: D
The variable head references the first item, which stores 20, head.next references the second item, which stores 11, head.next.next references the third item, which stores 13, and head.next.next.next references the fourth item, which stores 19. 16. Refer to Example Code Ch 13-4: What will be returned by the following? return head.info; a. b. c. d. e.
20 11 13 19 12
ANS: A The variable head references the first item, so head.data is the instance data info of the first item which stores 20. 17. Refer to Example Code Ch 13-4: What will the following statement accomplish? head.next.next = head.next.next.next; a. b. c. d. e.
It will result in the list ending after 13. It will result in the value 13 being deleted from the list. It will result in the list ending after 19. It will result in the value 19 being deleted from the list. It will result in the list ending after 12.
ANS: B The reference head.next.next is of the second Node in the list's next instance data, or 11's next. By setting this Node's next field to be head.next.next.next, this Node now references the Node storing 19 rather than 13, so it deletes 13 from the list. 18. Refer to Example Code Ch 13-4: What is the result to the linked list of the following instructions? Assume that newNode is a Node, already constructed. newNode.data = 1; newNode.next = head.next; head.next = newNode; a. b. c. d. e.
The value 1 is inserted into the linked list before 20. The value 1 is inserted into the linked list after 20 and before 11. The value 1 is inserted into the linked list after 11 and before 13. The value 1 is inserted into the linked list after 13 and before 19. The value 1 is inserted into the linked list after 20 and the rest of the list is lost.
ANS: B The statement newNode.next = head.next; sets the new node's next field to equal the second item in the list, so the new node, which stores 1, is inserted before 11. The statement head.next = newNode resets the first Node's next field to reference the new node, so 1 is now inserted after 20 and before 11. 19. A variation of a linked list is a circular linked list where the last Node in the list has next = head rather than next = null. One problem with this type of list is that
a. it wastes memory space since head already points at the first Node, so the last one does not need to b. there is no ability to add a new Node at the end of the list since the last Node points at the first Node c. it is more difficult to traverse the list since the old terminating condition, (next == null), is no longer true for the last node d. a header Node for this type of list is more complex e. All of these ANS: C Answers A, B and D are not true. This list uses no more memory than an ordinary linked list; adding a Node at the end requires the same amount of effort as before, and a header Node would be no different than before. However, answer C is true: the decision of whether there is another Node in the list or not can no longer be determined by testing (next == null) since the last Node's next field is equal to head instead of null. 20. Which of the following is used to see the top item of a stack without removing it from the stack? a. b. c. d. e.
push pop peak see top
ANS: C The three commands associated with a stack are push, pop and peak. push adds a new element to the top of the stack, pop removes the top element off of the stack and peak returns the top of the stack without removing it. 21. One operation that we might want to implement on a stack and a queue is full, which determines if the data structure has room for another item to be added. This operation would be useful a. b. c. d. e.
only if the queue or stack is implemented using an array only if the queue or stack is implemented using a linked list only for a queue only for a stack None of these; a full operation is not useful at all
ANS: A Since the array is a static sized object, if it becomes filled, then any add type of operation, whether it is a list insert, a queue enqueue or a stack push, should be prevented. This can be determined by first checking to see if the structure is full or not. This is not necessary if the data structure is implemented using a linked list since we assume that there will always be dynamic memory available to add a new element. 22. What type of structure should be used to gain a last-in first-out access to data? a. b. c. d. e.
a vector an array a linked list a queue a stack
ANS: E The stack is a data structure that allows only a last-in first-out (LIFO) access. Queues offer only a first-in first-out (FIFO) access. The vector, array and linked list types all offer any form of access desired. 23. To simulate people waiting in a line, which data structure would you use? a. b. c. d. e.
a vector a set a list a queue a stack
ANS: D
The FIFO access of a queue is the same access of people waiting in line -- the first person in the line will be the first to leave the line (be helped, given access to whatever he/she was waiting for). So, simulations of any kind of line structure will use the queue data structure. 24. In a linked list in Java a. b. c. d. e.
the link is an object the link is a node the link is a reference the link is an int the link is a class
ANS: C In a linked list, the link is a reference to the next node. One follows the link by "dereferencing" -- that is, by examining the contents of the reference. Nodes are objects. Objects are instances of classes. The data portion of a node may well be an int, as well as any other types of data. 25. A linear data structure a. b. c. d. e.
always has more than one link per node is sometimes represented as a tree or a graph can have only a single link per node almost always is kept in sorted order, either ascending or descending None of these
ANS: C A linear data structure is one that, when you draw a picture of it, displays as a line of connected nodes. It is linear and it looks like a line. A simple list is an example of such a data structure so a linear data structure may have as few as one link per node. Data structures that display as trees or graphs are not linear; they are two-dimensional (at least). There is no requirement (or convention) that linear data structures be kept in any kind of order, sorted or otherwise. 26. A simple linear list a. b. c. d. e.
is an example of a degenerate tree is an example of a degenerate graph is an example of a degenerate digraph cannot be represented as a degenerate tree, graph, or digraph None of these
ANS: A
A simple linear list is directed, from its starting node to its end node. Neither graphs nor digraphs have a start node but, a tree does: the root of the tree. So, a simple linear list is an example of a degenerate tree, one which has a branching factor of one, with each node having but a single successor, beginning at the root, and ending at the single leaf (end node). 27. A dynamic data structure a. b. c. d. e.
almost always is implemented using lists of one sort or another is just a collection almost always is implemented using references (pointers) to objects can have a fixed size None of these
ANS: C A dynamic data structure is one that can grow and shrink during execution. In order to implement such a data structure in Java, one must use references (pointers) to objects. Java collections are but one set of examples of dynamic data structures provided by the Java libraries. Example Code Ch 13-5 Consider the following operations on a queue data structure that stores int values: Queue q = new Queue(); q.enqueue(3); q.enqueue(5); q.enqueue(9); System.out.println(q.dequeue()); // d1 q.enqueue(2); q.enqueue(4); System.out.println(q.dequeue()); // d2 System.out.println(q.dequeue()); // d3 q.enqueue(1); q.enqueue(8); 28. Refer to Example Code Ch 13-5: After this code executes, how many elements would remain in q? a. b. c. d. e.
0 4 5 6 7
ANS: B The constructor creates an initially empty queue. Each enqueue operation adds one int to the queue and each dequeue operation removes one int from the queue. There are 7 enqueue operations and 3 dequeue operations, leaving 4 int values in q at the end. 29. Refer to Example Code Ch 13-5: What value is returned by the last dequeue operation, denoted with a d3 as a comment. a. b. c. d. e.
3 5 9 2 4
ANS: C The dequeue operations remove the next item in the queue, so the dequeue in d1 removes 3, the dequeue in d2 removes 5 and the dequeue in d3 removes 9. 30. Refer to Example Code Ch 13-5: If we replace the System.out.println statements (denoted in comments as d1, d2 and d3) with the statement q.enqueue(q.dequeue()); q would contain which order of int values after all instructions have executed? a. b. c. d. e.
3, 5, 9, 2, 4, 1, 8 3, 5, 9, 1, 8, 2, 4 5, 9, 2, 4, 1, 8, 3 3, 2, 4, 5, 9, 1, 8 2, 4, 1, 8, 3, 5, 9
ANS: D The original order of int values in q is 3, 5, 9. At d1, the first item is dequeued and then enqueued resulting in 5, 9, 3. Two more enqueues result in 5, 9, 3, 2, 4. At d2 and d3, the first two items are dequeued and then enqueued resulting in 3, 2, 4, 5, 9. Finally, 1 and 8 are enqueued leaving q as 3, 2, 4, 5, 9, 1, 8. Example Code Ch 13-6 Assume a stack class stores int values. Consider the following sequence of instructions. Stack s = new Stack(); s.push(16); s.push(12); s.push(19); int x = s.pop(); s.push(5); s.push(9); s.push(4); int y = s.pop(); int z = s.pop(); 31. Refer to Example Code Ch 13-6: After the instructions execute, x has the value a. b. c. d. e.
16 12 19 0 None of these; the instruction int x = s.pop() results in an exception being thrown
ANS: C The stack offers a last-in first-out access, so at the point when s.pop() is first executed, the item removed is the last item pushed onto s, or 19. 32. Refer to Example Code Ch 13-6: After the instructions execute, z has the value a. b. c. d. e.
4 9 5 12 16
ANS: B
At that point that the int z = s.pop(); executes, a previous s.pop(); will have removed the most recently pushed item (4), so this pop removes the next most recently pushed item (9). PROBLEM Example Code Ch 13-1 The following is a class definition of a linked list Node: class Node { int info; Node next; } 1. Refer to Example Code Ch 13-1: Show the instructions required to create a linked list that is referenced by head and stores in order, the int values 3, 6 and 2. Assume that Node's constructor receives no parameters. ANS: Node head = new Node(); head.info = 3; head.next = new Node(); head.next.info = 6; head.next.next = new Node(); head.next.next.info = 2; head.next.next.next = null; 2. Refer to Example Code Ch 13-1: Assume that head references a linked list and stores in order, the int values 3, 2 and 6. Show the instructions needed to move the value 2 in front of the value 6 so that the list is now 3, 2 and 6. ANS: Node temp = head.next; head.next = head.next.next; head.next.next = temp; temp.next = null; 3. Refer to Example Code Ch 13-1: Assume that head references a linked list and stores in order, the int values 3, 6 and 2. Show the instructions needed to delete the Node with 3 so that head would reference the list 6 and 2. ANS: head = head.next; 4. Refer to Example Code Ch 13-1: Assume that head references a linked list, although we don't know what is currently stored in that list. Write a block of code using a try-catch block that will work through the entire linked list, printing each element out, stopping only when we have reached the end of the list because a NullPointerException is thrown. Once the Exception is thrown, output the number of elements found in the list. ANS: int count = 0;
try { Node temp = head; while (true) { System.out.println(temp.info); temp = temp.next; count++; } } catch (NullPointerException npe) { System.out.println("Number of elements in the list is " + count); } 5. A queue q stores int values. Show what q will look like after each of the following instructions is executed. q.enqueue(6); q.enqueue(12); q.enqueue(13); q.dequeue(); q.dequeue(); q.enqueue(19); q.enqueue(21); q.enqueue(22); q.dequeue(); q.enqueue(20); ANS: queue: q.enqueue(6); q.enqueue(12); q.enqueue(13); q.dequeue(); q.dequeue(); q.enqueue(19); q.enqueue(21); q.enqueue(22); q.dequeue(); q.enqueue(20);
Front --> Rear 6 6 12 6 12 13 12 13 13 13 19 13 19 21 13 19 21 22 19 21 22 19 21 22 20
6. A stack s stores int values. Show what s will look like after each of the following instructions is executed. s.push(5); s.push(1); s.push(4); s.push(3); s.pop(); s.push(2); s.pop(); s.pop(); s.push(8);
s.push(7); s.pop(); s.push(3); ANS: s.push(5); s.push(1); s.push(4); s.push(3); s.pop(); s.push(2); s.pop(); s.pop(); s.push(8); s.push(7); s.pop(); s.push(3);
Top --> Bottom 5 1 5 4 1 5 3 4 1 4 1 5 2 4 1 4 1 5 1 5 8 1 5 7 8 1 8 1 5 3 8 1
5 5
5 5
7. One use of a stack is to reverse the order of input. Write a method that reads a series of Strings from the keyboard (assume the Scanner class has been imported) and outputs the Strings in reverse order of how they were entered. The input will end with the String "end" but do not output the String "end". Assume that SStack is a stack that can store Strings. Remember to declare and instantiate your SStack in your method. ANS: public void reverseOrder() { SStack s = new SStack(); Scanner scanner = Scanner.create(System.in) String in = scanner.next(); while (!in.equals("end")) { s.push(in); in = scanner.next(); } while (!s.empty()) { System.out.println(s.pop()); } } 8. What is an ADT (Abstract Data Type) and why are ADTs considered to be abstract? ANS: An ADT is a collection of data and the particular operations that are allowed on that data. An ADT has a name, a domain of values, and a set of operations that can be performed. An ADT is considered to be abstract because the operations you can perform are separated from the underlying implementation; the details on how an ADT stores its data and accomplishes its methods are separate from the concept that it embodies.
9. An abstract data type not covered in detail in the chapter is the Set ADT. A Set is like a set as covered in Mathematics courses. For instance, a set of even numbers might be {2, 4, 8, 12, 18, 32}. List 6 operations that you might implement for a Set ADT. ANS: addElement, removeElement, isAnElementOf, intersect, union, subset. Others might include toString, superset, equals, compareTo, and difference. 10. Two abstract data types are the ordered list and the unordered list. Explain how these two ADTs are similar and how they differ. To answer this question, assume that you do not know how they are implemented (that is, whether they are implemented using an array or a linked list). ANS: The ordered list will require a mechanism to make sure that new elements are inserted in their appropriate place using some kind of ordering operation, whether this is an ordered insert or a sort. Since items are ordered, searching for and deleting an item might be simplified (for instance, if you are looking for a word in the dictionary and you have reached a word that is alphabetically beyond the word, then you know that you have gone too far or that the word is not in the dictionary). A deletion will have to maintain the ordering of the items in the list. In an unordered list, there is no order at all, so new items can be added at the end, simplifying the add/insert operation, and deleted items can be replaced by the last item in the list so that no shifting of elements is needed. Finally, in the unordered list, searching requires looking over every element until the item is found, or the end of the list is reached. 11. A double-ended queue, called a dequeue, is a queue that, instead of having single links in one direction, has a pair of links, one pointed in each direction. Dequeues allow one to "push" and "pop" information at either end. Is this ADT the same or different from a doubly linked list, as described in the textbook? ANS: This ADT is the same as a doubly linked list. Each node contains a pair of links, one pointed in each direction; information can be added or deleted at either end of the list; and nodes can store any kind of data. This illustrates the fact that data structures may go by many names, depending upon how one thinks about them. 12. What common exception(s) might arise when using an array? What common exception(s) might arise when using a linked list? ANS: In the array, an ArrayOutOfBoundsException or IndexOutOfBoundsException might arise if you use an array index that is either negative or larger than (or equal to) the size of the array. In the linked list, a NullPointerException will arise if you attempt to access an item that is equal to null. And, since the linked list uses dynamic memory, an OutOfMemoryException might also arise if you try to add to the list when additional memory is no longer available. 13. Challenge: Assume a function g(x) is defined as follows where x is an int parameter: g(x) = g(x - 1) * g (x - 3) if x is even and x > 3 = g(x - 2) if x is odd and x > 3 = x otherwise
Write a recursive method to compute g. In implementing a queue using an array, a problem might arise if the queue is implemented in such a way that items in the queue are inserted at the next available location and removed from the next leading position, but such that, once deleted, the emptied space is unused. The problem that arises is one where there is free space still in the array, but it is not usable because it is not at the end. Demonstrate this problem with a queue that is stored in an array of size 5 for the following instructions. Next, explain how you might resolve this problem. Queue q = new Queue(5); // assume the Queue constructor takes 5 as the size of the array q.enqueue(3); q.enqueue(4); q.enqueue(1); q.dequeue(); q.dequeue(); q.enqueue(6); q.enqueue(5); q.dequeue(); // at this point, there are only 2 items in the queue q.enqueue(7); // this enqueue can not occur, why?? ANS: Array index q.enqueue(3); q.enqueue(4); q.enqueue(1); q.dequeue(); q.dequeue(); q.enqueue(6); q.enqueue(5); q.dequeue(); q.enqueue(7);
0
1
//
2
3 3 3 3
4 4 4 4
1 1 1 1 1
6 6 5 6 5 7 cannot be added since 5 is in the last array element
To solve this problem of not being able to add to a non-full queue even though the last element in the queue is in the last available array location, we need to change the array into a circular array whereby the next element (7) can be added to the beginning of the array. This complicates the queue but is more memory efficient.