Java How to Program (early objects), 9E BY Paul Deitel Harvey Deitel
Email: Richard@qwconsultancy.com
1
Introduction to Computers and Java: Solutions
Man is still the most extraordinary computer of all. —John F. Kennedy
Good design is good business. —Thomas J. Watson, Founder of IBM
How wonderful it is that nobody need wait a single moment before starting to improve the world. —Anne Frank
Objectives In this chapter you’ll learn: Exciting recent developments in the computer field. ■ Computer hardware, software and networking basics. ■ The data hierarchy. ■ The different types of programming languages. ■ Basic object-technology concepts. ■ The importance of the Internet and the web. ■ A typical Java programdevelopment environment. ■ To test-drive a Java application. ■ Some key recent software technologies. ■ How computers can help you make a difference. ■
..
2
Chapter 1
Introduction to Computers and Java: Solutions
Self-Review Exercises 1.1
Fill in the blanks in each of the following statements: . a) The company that popularized personal computing was ANS: Apple. b) The computer that made personal computing legitimate in business and industry was . the ANS: IBM Personal Computer. . c) Computers process data under the control of sets of instructions called ANS: programs. , , , , d) The key logical units of the computer are the and . ANS: input unit, output unit, memory unit, central processing unit, arithmetic and logic unit, secondary storage unit. , and e) The three types of languages discussed in the chapter are . ANS: machine languages, assembly languages, high-level languages. f) The programs that translate high-level language programs into machine language are . called ANS: compilers. is a smartphone operating system based on the Linux kernel and Java. g) ANS: Android. software is generally feature complete and (supposedly) bug free, and ready h) for use by the community. ANS: Release candidate. which allows the dei) The Wii Remote, as well as many smartphones, use a(n) vice to respond to motion. ANS: accelerometer.
1.2
Fill in the blanks in each of the following sentences about the Java environment: a) The command from the JDK executes a Java application. ANS: java. command from the JDK compiles a Java program. b) The ANS: javac. file extension. c) A Java program file must end with the ANS: .java. d) When a Java program is compiled, the file produced by the compiler ends with the file extension. ANS: .class. that are executed by the Java e) The file produced by the Java compiler contains Virtual Machine. ANS: bytecodes.
1.3
Fill in the blanks in each of the following statements (based on Section 1.6): a) Objects have the property of —although objects may know how to communicate with one another across well-defined interfaces, they normally are not allowed to know how other objects are implemented. ANS: information hiding. , which contain fields and the set of b) Java programmers concentrate on creating methods that manipulate those fields and provide services to clients. ANS: classes. ..
Exercises
3
c) The process of analyzing and designing a system from an object-oriented point of view . is called ANS: object-oriented analysis and design (OOAD). , new classes of objects are derived by absorbing characteristics of existing d) With classes, then adding unique characteristics of their own. ANS: inheritance. is a graphical language that allows people who design software systems to use e) an industry-standard notation to represent them. ANS: The Unified Modeling Language (UML). of the object’s f) The size, shape, color and weight of an object are considered class. ANS: attributes.
Exercises 1.4
Fill in the blanks in each of the following statements: a) The logical unit of the computer that receives information from outside the computer . for use by the computer is the ANS: input unit. . b) The process of instructing the computer to solve a problem is called ANS: computer programming. is a type of computer language that uses Englishlike abbreviations for mac) chine-language instructions. ANS: Assembly language. is a logical unit of the computer that sends information which has already d) been processed by the computer to various devices so that it may be used outside the computer. ANS: The output unit. and are logical units of the computer that retain information. e) ANS: The memory unit, the secondary storage unit. is a logical unit of the computer that performs calculations. f) ANS: The arithmetic and logic unit (ALU). is a logical unit of the computer that makes logical decisions. g) ANS: The arithmetic and logic unit (ALU). languages are most convenient to the programmer for writing programs h) quickly and easily. ANS: High-level. . i) The only language a computer can directly understand is that computer’s ANS: machine language. is a logical unit of the computer that coordinates the activities of all the other j) logical units. ANS: The central processing unit (CPU).
1.5
Fill in the blanks in each of the following statements: is now used to develop large-scale enterprise applications, to enhance the a) functionality of web servers, to provide applications for consumer devices and for many other purposes. ANS: Java. initially became widely known as the development language of the UNIX opb) erating system. ANS: C. ..
4
Chapter 1
Introduction to Computers and Java: Solutions
c) The Web 2.0 company
is the fastest growing company ever.
ANS: Foursquare.
programming language was developed by Bjarne Stroustrup in the early d) The 1980s at Bell Laboratories. ANS: C++. 1.6
Fill in the blanks in each of the following statements: , , , a) Java programs normally go through five phases— and . ANS: edit, compile, load, verify, execute. provides many tools that support the software development process, b) A(n) such as editors for writing and editing programs, debuggers for locating logic errors in programs, and many other features. ANS: integrated development environment (IDE). , which executes Java programs. c) The command java invokes the ANS: Java Virtual Machine (JVM). is a software application that simulates a computer, but hides the underd) A(n) lying operating system and hardware from the programs that interact with it. ANS: virtual machine (VM). takes the .class files containing the program’s bytecodes and transfers e) The them to primary memory. ANS: class loader. examines bytecodes to ensure that they are valid. f) The ANS: bytecode verifier.
1.7
Explain the two compilation phases of Java programs. ANS: The two compilation phases that Java programs typically go through include one in which source code is translated into bytecodes which are portable across JVMs and a second in which the bytecodes are translated into machine language for the actual computer on which the program executes. In early Java versions, the JVM was simply an interpreter for Java bytecodes. This caused most Java programs to execute slowly because the JVM would interpret and execute one bytecode at a time. Today’s JVMs typically execute bytecodes using a combination of interpretation and so-called justin-time (JIT) compilation. In this process, The JVM analyzes the bytecodes as they are interpreted, searching for hot spots—parts of the bytecodes that execute frequently. For these parts, a just-in-time (JIT) compiler—known as the Java HotSpot compiler—translates the bytecodes into the underlying computer’s machine language. When the JVM encounters these compiled parts again, the faster machine-language code executes.
1.8 You are probably wearing on your wrist one of the world’s most common types of objects— a watch. Discuss how each of the following terms and concepts applies to the notion of a watch: object, attributes, behaviors, class, inheritance (consider, for example, an alarm clock), abstraction, modeling, messages, encapsulation, interface and information hiding. ANS: The entire watch is an object that is composed of many other objects (such as the moving parts, the band, the face, etc.) Watch attributes are time, color, band, style (digital or analog), etc. The behaviors of the watch include setting the time and getting the time. A watch can be considered a specific type of clock (as can an alarm clock). With that in mind, it is possible that a class called Clock could exist from which other classes such as watch and alarm clock could inherit the basic features in the clock. The watch is an abstraction of the mechanics needed to keep track of the time. The user of the watch does not need to know the mechanics of the watch in © 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Making a Difference
5
order to use it; the user only needs to know that the watch keeps the proper time. In this sense, the mechanics of the watch are encapsulated (hidden) inside the watch. The interface to the watch (its face and controls for setting the time) allows the user to set and get the time. The user is not allowed to directly touch the internal mechanics of the watch. All interaction with the internal mechanics is controlled by the interface to the watch. The data members stored in the watch are hidden inside the watch and the member functions (looking at the face to get the time and setting the time) provide the interface to the data.
Making a Difference Throughout the book we’ve included Making a Difference exercises in which you’ll be asked to work on problems that really matter to individuals, communities, countries and the world. For more information about worldwide organizations working to make a difference, and for related programming project ideas, visit our Making a Difference Resource Center at www.deitel.com/ makingadifference. 1.9 (Test Drive: Carbon Footprint Calculator) Some scientists believe that carbon emissions, especially from the burning of fossil fuels, contribute significantly to global warming and that this can be combatted if individuals take steps to limit their use of carbon-based fuels. Organizations and individuals are increasingly concerned about their “carbon footprints.” Websites such as TerraPass www.terrapass.com/carbon-footprint-calculator/
and Carbon Footprint www.carbonfootprint.com/calculator.aspx
provide carbon footprint calculators. Test-drive these calculators to determine your carbon footprint. Exercises in later chapters will ask you to program your own carbon footprint calculator. To prepare for this, research the formulas for calculating carbon footprints. 1.10 (Test Drive: Body Mass Index Calculator) By recent estimates, two-thirds of the people in the United States are overweight and about half of those are obese. This causes significant increases in illnesses such as diabetes and heart disease. To determine whether a person is overweight or obese, you can use a measure called the body mass index (BMI). The United States Department of Health and Human Services provides a BMI calculator at www.nhlbisupport.com/bmi/. Use it to calculate your own BMI. An exercise in Chapter 2 will ask you to program your own BMI calculator. To prepare for this, research the formulas for calculating BMI. 1.11 (Attributes of Hybrid Vehicles) In this chapter you learned the basics of classes. Now you’ll begin “fleshing out” aspects of a class called “Hybrid Vehicle.” Hybrid vehicles are becoming increasingly popular, because they often get much better mileage than purely gasoline-powered vehicles. Browse the web and study the features of four or five of today’s popular hybrid cars, then list as many of their hybrid-related attributes as you can. For example, common attributes include city-miles-pergallon and highway-miles-per-gallon. Also list the attributes of the batteries (type, weight, etc.). ANS:
• Manufacturer • Type of Hybrid—Battery hybrid (Hybrid Electric Vehicles), Plug-in hybrid, Fuel cell etc. • Driver feedback system—so the driver can monitor fuel efficiency based on their driving • Energy recovery—for example, regenerative breaking • Carbon footprint—tons of CO2 per year • Fuel capacity • City-miles-per-gallon © 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
6
Chapter 1
Introduction to Computers and Java: Solutions
• Highway-miles-per-gallon • Two-mode hybrid propulsion system • Engine size—V6, V8, etc. • Vehicle type—SUV, crossover, compact, mid-size, etc. • Seating capacity • Horse power • Drive train (front wheel drive, all wheel drive) • Top speed • Torque • Price 1.12 (Gender Neutrality) Many people want to eliminate sexism in all forms of communication. You’ve been asked to create a program that can process a paragraph of text and replace gender-specific words with gender-neutral ones. Assuming that you’ve been given a list of gender-specific words and their gender-neutral replacements (e.g., replace “wife” by “spouse,” “man” by “person,” “daughter” by “child” and so on), explain the procedure you’d use to read through a paragraph of text and manually perform these replacements. How might your procedure generate a strange term like “woperchild,” which is actually listed in the Urban Dictionary (www.urbandictionary.com)? In Chapter 4, you’ll learn that a more formal term for “procedure” is “algorithm,” and that an algorithm specifies the steps to be performed and the order in which to perform them. ANS: Search through the entire paragraph for a word such as “wife” and replace every occurrence with “spouse.” Repeat this searching process for every gender specific word in the list. You could accidentally get a word like “woperchild” if you are not careful about how you perform replacements. For example, the word “man” can be part of a larger word, like “woman.” So, replacing every occurrence of “man” can yield strange results. Consider the process of replacing “man” with “person” then replacing “son” with “child.” If you encounter the word “woman,” which contains the word “man,” you’d replace “man” with “person” resulting in the word “woperson.” In a subsequent pass you’d encounter “woperson” and replace “son” with “child” resulting in the “woperchild.” 1.13 (Privacy) Some online email services save all email correspondence for some period of time. Suppose a disgruntled employee of one of these online email services were to post all of the email correspondences for millions of people, including yours, on the Internet. Discuss the issues. 1.14 (Programmer Responsibility and Liability) As a programmer in industry, you may develop software that could affect people’s health or even their lives. Suppose a software bug in one of your programs were to cause a cancer patient to receive an excessive dose during radiation therapy and that the person is either severely injured or dies. Discuss the issues. 1.15 (2010 “Flash Crash”) An example of the consequences of our excessive dependency on computers was the so-called “flash crash” which occurred on May 6, 2010, when the U.S. stock market fell precipitously in a matter of minutes, wiping out trillions of dollars of investments, and then recovered within minutes. Use the Internet to investigate the causes of this crash and discuss the issues it raises.
..
2
Introduction to Java Applications: Solutions
What’s in a name? That which we call a rose By any other name would smell as sweet. —William Shakespeare
When faced with a decision, I always ask, “What would be the most fun?” —Peggy Walker
“Take some more tea,” the March Hare said to Alice, very earnestly. “I’ve had nothing yet," Alice replied in an offended tone: “so I can’t take more.” “You mean you can’t take less,” said the Hatter: “It’s very easy to take more than nothing.” —Lewis Carroll
Objectives In this chapter you’ll learn: To write simple Java applications. ■ To use input and output statements. ■ Java’s primitive types. ■ Basic memory concepts. ■ To use arithmetic operators. ■ The precedence of arithmetic operators. ■ To write decision-making statements. ■ To use relational and equality operators. ■
..
2
Chapter 2
Introduction to Java Applications: Solutions
Self-Review Exercises 2.1
Fill in the blanks in each of the following statements: begins the body of every method, and a(n) ends the body of a) A(n) every method. ANS: left brace ({), right brace (}). statement is used to make decisions. b) The ANS: if. begins an end-of-line comment. c) ANS: //. , and are called white space. d) ANS: Space characters, newlines and tabs. are reserved for use by Java. e) ANS: Keywords. . f) Java applications begin execution at method ANS: main. , and display information in a command wing) Methods dow. ANS: System.out.print, System.out.println and System.out.printf.
2.2
State whether each of the following is true or false. If false, explain why. a) Comments cause the computer to print the text after the // on the screen when the program executes. ANS: False. Comments do not cause any action to be performed when the program executes. They are used to document programs and improve their readability. b) All variables must be given a type when they are declared. ANS: True. c) Java considers the variables number and NuMbEr to be identical. ANS: False. Java is case sensitive, so these variables are distinct. d) The remainder operator (%) can be used only with integer operands. ANS: False. The remainder operator can also be used with noninteger operands in Java. e) The arithmetic operators *, /, %, + and - all have the same level of precedence. ANS: False. The operators *, / and % are on the same level of precedence, and the operators + and - are on a lower level of precedence.
2.3
Write statements to accomplish each of the following tasks: a) Declare variables c, thisIsAVariable, q76354 and number to be of type int. ANS: int c, thisIsAVariable, q76354, number;
or int c; int thisIsAVariable; int q76354; int number;
b) Prompt the user to enter an integer. ANS: System.out.print( "Enter an integer: " );
c) Input an integer and assign the result to int variable value. Assume Scanner variable input can be used to read a value from the keyboard. ANS: value = input.nextInt();
d) Print "This is a Java program" on one line in the command window. Use method System.out.println. ANS: System.out.println( "This is a Java program" );
..
Self-Review Exercises
3
e) Print "This is a Java program" on two lines in the command window. The first line should end with Java. Use method System.out.println. ANS: System.out.println( "This is a Java\nprogram" );
f) Print "This is a Java program" on two lines in the command window. The first line should end with Java. Use method System.out.printf and two %s format specifiers. ANS: System.out.printf( "%s\n%s\n", "This is a Java", "program" );
g) If the variable number is not equal to 7, display "The variable number is not equal to 7". ANS: if ( number != 7 ) System.out.println( "The variable number is not equal to 7" );
2.4
Identify and correct the errors in each of the following statements: a) if ( c < 7 ); System.out.println( "c is less than 7" );
ANS: Error: Semicolon after the right parenthesis of the condition ( c < 7 ) in the if.
Correction: Remove the semicolon after the right parenthesis. [Note: As a result, the output statement will execute regardless of whether the condition in the if is true.] b) if ( c => 7 ) System.out.println( "c is equal to or greater than 7" );
ANS: Error: The relational operator => is incorrect. Correction: Change => to >=.
2.5
Write declarations, statements or comments that accomplish each of the following tasks: a) State that a program will calculate the product of three integers. ANS: // Calculate the product of three integers
b) Create a Scanner called input that reads values from the standard input. ANS: Scanner input = new Scanner( System.in );
c) Declare the variables x, y, z and result to be of type int. ANS: int x; int y; int z; int result;
or int x, y, z, result;
d) Prompt the user to enter the first integer. ANS: System.out.print( "Enter first integer: " );
e) Read the first integer from the user and store it in the variable x. ANS: x = input.nextInt();
f) Prompt the user to enter the second integer. ANS: System.out.print( "Enter second integer: " );
g) Read the second integer from the user and store it in the variable y. ANS: y = input.nextInt();
h) Prompt the user to enter the third integer. ANS: System.out.print( "Enter third integer: " );
i) Read the third integer from the user and store it in the variable z. ANS: z = input.nextInt();
j) Compute the product of the three integers contained in variables x, y and z, and assign the result to the variable result. ANS: result = x * y * z;
k) Display the message "Product is" followed by the value of the variable result. ANS: System.out.printf( "Product is %d\n", result );
..
4
Chapter 2
Introduction to Java Applications: Solutions
2.6 Using the statements you wrote in Exercise 2.5, write a complete program that calculates and prints the product of three integers. ANS: The solution to Self-Review Exercise 2.6 is as follows: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
// Ex. 2.6: Product.java // Calculate the product of three integers. import java.util.Scanner; // program uses Scanner public class Product { public static void main( String[] args ) { // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); int x; // first number input by user int y; // second number input by user int z; // third number input by user int result; // product of numbers System.out.print( "Enter first integer: " ); // prompt for input x = input.nextInt(); // read first integer System.out.print( "Enter second integer: " ); // prompt for input y = input.nextInt(); // read second integer System.out.print( "Enter third integer: " ); // prompt for input z = input.nextInt(); // read third integer result = x * y * z; // calculate product of numbers System.out.printf( "Product is %d\n", result ); } // end method main } // end class Product
Enter first integer: 10 Enter second integer: 20 Enter third integer: 30 Product is 6000
Exercises NOTE: Solutions to the programming exercises are located in the ch02solutions folder. Each exercise has its own folder named ex02_## where ## is a two-digit number representing the exercise number. For example, exercise 2.14’s solution is located in the folder ex02_14. 2.7
Fill in the blanks in each of the following statements: are used to document a program and improve its readability. a) ANS: Comments. . b) A decision can be made in a Java program with a(n) ANS: if statement. statements. c) Calculations are normally performed by ANS: assignment statements. d) The arithmetic operators with the same precedence as multiplication are . ..
and
Exercises
5
ANS: division (/), remainder (%)
set of parene) When parentheses in an arithmetic expression are nested, the theses is evaluated first. ANS: innermost. f) A location in the computer’s memory that may contain different values at various times . throughout the execution of a program is called a(n) ANS: variable. 2.8
Write Java statements that accomplish each of the following tasks: a) Display the message "Enter an integer: ", leaving the cursor on the same line. ANS: System.out.print( "Enter an integer: " );
b) Assign the product of variables b and c to variable a. ANS: a = b * c;
c) State that a program performs a sample payroll calculation (i.e., use text that helps to document a program). ANS: // This program performs a simple payroll calculation.
2.9
State whether each of the following is true or false. If false, explain why. a) Java operators are evaluated from left to right. ANS: False. Some operators (e.g., assignment, =) evaluate from right to left. b) The following are all valid variable names: _under_bar_, m928134, t5, j7, her_sales$, his_$account_total, a, b$, c, z and z2. ANS: True. c) A valid Java arithmetic expression with no parentheses is evaluated from left to right. ANS: False. The expression is evaluated according to operator precedence. d) The following are all invalid variable names: 3g, 87, 67h2, h22 and 2h. ANS: False. Identifier h22 is a valid variable name.
2.10
Assuming that x = 2 and y = 3, what does each of the following statements display? a) System.out.printf( "x = %d\n", x ); ANS: x = 2
b) System.out.printf( "Value of %d + %d is %d\n", x, x, ( x + x ) ); ANS: Value of 2 + 2 is 4
c)
System.out.printf( "x =" );
ANS: x =
d) System.out.printf( "%d = %d\n", ( x + y ), ( y + x ) ); ANS: 5 = 5
2.11
Which of the following Java statements contain variables whose values are modified? a) p = i + j + k + 7; b) System.out.println( "variables whose values are modified" ); c) System.out.println( "a = 5" ); d) value = input.nextInt(); ANS: (a), (d).
2.12
Given that y = ax3 + 7, which of the following are correct Java statements for this equation? a) y = a * x * x * x + 7; b) y = a * x * x * ( x + 7 ); c) y = ( a * x ) * x * ( x + 7 ); d) y = ( a * x ) * x * x + 7; e) y = a * ( x * x * x ) + 7; f) y = a * x * ( x * x + 7 ); ANS: (a), (d), (e) ..
6
Chapter 2
Introduction to Java Applications: Solutions
2.13 State the order of evaluation of the operators in each of the following Java statements, and show the value of x after each statement is performed: a) x = 7 + 3 * 6 / 2 - 1; ANS: *, /, +, -; Value of x is 15. b) x = 2 % 2 + 2 * 2 - 2 / 2; ANS: %, *, /, +, -; Value of x is 3. c) x = ( 3 * 9 * ( 3 + ( 9 * 3 / ( 3 ) ) ) ); ANS: x = ( 3 * 9 * ( 3 + ( 9 * 3 / ( 3 ) ) ) ); 4
5
3
1
2
Value of x is 324. 2.19
What does the following code print? System.out.println( "*\n**\n***\n****\n*****" );
ANS:
* ** *** **** *****
2.20
What does the following code print? System.out.println( "*" ); System.out.println( "***" ); System.out.println( "*****" ); System.out.println( "****" ); System.out.println( "**" );
ANS:
* *** ***** **** **
2.21
What does the following code print? System.out.print( "*" ); System.out.print( "***" ); System.out.print( "*****" ); System.out.print( "****" ); System.out.println( "**" );
ANS:
***************
..
Exercises 2.22
What does the following code print? System.out.print( "*" ); System.out.println( "***" ); System.out.println( "*****" ); System.out.print( "****" ); System.out.println( "**" );
ANS:
**** ***** ******
2.23
What does the following code print? System.out.printf( "%s\n%s\n%s\n", "*", "***", "*****" );
ANS:
* *** *****
..
7
Introduction to Classes, Objects, Methods and Strings: Solutions
3 Nothing can have value without being an object of utility. —Karl Marx
Your public servants serve you right. —Adlai E. Stevenson
You’ll see something new. Two things. And I call them Thing One and Thing Two. —Dr. Theodor Seuss Geisel
Objectives In this chapter you’ll learn:
..
■
How to declare a class and use it to create an object.
■
How to implement a class’s behaviors as methods.
■
How to implement a class’s attributes as instance variables and properties.
■
How to call an object’s methods to make them perform their tasks.
■
What instance variables of a class and local variables of a method are.
■
How to use a constructor to initialize an object’s data.
■
The differences between primitive and reference types.
2
Chapter 3
Introduction to Classes, Objects, Methods and Strings: Solutions
Self-Review Exercises 3.1
Fill in the blanks in each of the following: must be stored in a file that a) Each class declaration that begins with keyword has exactly the same name as the class and ends with the .java file-name extension. ANS: public. in a class declaration is followed immediately by the class’s name. b) Keyword ANS: class. requests memory from the system to store an object, then calls the c) Keyword corresponding class’s constructor to initialize the object. ANS: new. and a(n) . d) Each parameter must specify both a(n) ANS: type, name. e) By default, classes that are compiled in the same directory are considered to be in the . same package, known as the ANS: default package. f) When each object of a class maintains its own copy of an attribute, the field that repre. sents the attribute is also known as a(n) ANS: instance variable. g) Java provides two primitive types for storing floating-point numbers in memory: and . ANS: float, double. floating-point numbers. h) Variables of type double represent ANS: double-precision. returns a double value. i) Scanner method ANS: nextDouble. . j) Keyword public is an access ANS: modifier. indicates that a method will not return a value. k) Return type ANS: void. reads characters until it encounters a newline character, l) Scanner method then returns those characters as a String. ANS: nextLine. . m) Class String is in package ANS: java.lang. is not required if you always refer to a class with its fully qualified class n) A(n) name. ANS: import declaration. is a number with a decimal point, such as 7.33, 0.0975 or 1000.12345. o) A(n) ANS: floating-point number. floating-point numbers. p) Variables of type float represent ANS: single-precision. is used to output values of type float or double. q) The format specifier ANS: %f. types and types. r) Types in Java are divided into two categories— ANS: primitive, reference.
..
Self-Review Exercises
3
3.2
State whether each of the following is true or false. If false, explain why. a) By convention, method names begin with an uppercase first letter, and all subsequent words in the name begin with a capital first letter. ANS: False. By convention, method names begin with a lowercase first letter and all subsequent words in the name begin with a capital first letter. b) An import declaration is not required when one class in a package uses another in the same package. ANS: True. c) Empty parentheses following a method name in a method declaration indicate that the method does not require any parameters to perform its task. ANS: True. d) Variables or methods declared with access modifier private are accessible only to methods of the class in which they are declared. ANS: True. e) A primitive-type variable can be used to invoke a method. ANS: False. A primitive-type variable cannot be used to invoke a method—a reference to an object is required to invoke the object’s methods. f) Variables declared in the body of a particular method are known as instance variables and can be used in all methods of the class. ANS: False. Such variables are called local variables and can be used only in the method in which they are declared. g) Every method’s body is delimited by left and right braces ({ and }). ANS: True. h) Primitive-type local variables are initialized by default. ANS: False. Primitive-type instance variables are initialized by default. Each local variable must explicitly be assigned a value. i) Reference-type instance variables are initialized by default to the value null. ANS: True. j) Any class that contains public static void main( String[] args ) can be used to execute an application. ANS: True. k) The number of arguments in the method call must match the number of parameters in the method declaration’s parameter list. ANS: True. l) Floating-point values that appear in source code are known as floating-point literals and are type float by default. ANS: False. Such literals are of type double by default.
3.3
What is the difference between a local variable and a field? ANS: A local variable is declared in the body of a method and can be used only from the point at which it is declared through the end of the method declaration. A field is declared in a class, but not in the body of any of the class’s methods. Also, fields are accessible to all methods of the class. (We’ll see an exception to this in Chapter 8, Classes and Objects: A Deeper Look: Solutions.)
3.4 Explain the purpose of a method parameter. What is the difference between a parameter and an argument? ANS: A parameter represents additional information that a method requires to perform its task. Each parameter required by a method is specified in the method’s declaration. An argument is the actual value for a method parameter. When a method is called, the argument values are passed to the corresponding parameters of the method so that it can perform its task. ..
4
Chapter 3
Introduction to Classes, Objects, Methods and Strings: Solutions
Exercises NOTE: Solutions to the programming exercises are located in the ch03solutions folder. Each exercise has its own folder named ex03_## where ## is a two-digit number representing the exercise number. For example, exercise 3.11’s solution is located in the folder ex03_11. 3.5
(Keyword new) What’s the purpose of keyword new? Explain what happens when you use it. ANS: The purpose of keyword new is to create an object of a class. When keyword new is used in an application, first a new object of the class to the right of new is created, then the class’s constructor is called to initialize the object.
3.6 (Default Constructors) What is a default constructor? How are an object’s instance variables initialized if a class has only a default constructor? ANS: A default constructor is provided by the compiler when you do not specify any constructors in the class. When a class has only the default constructor, its instance variables are initialized to their default values. Variables of types char, byte, short, int, long, float and double are initialized to 0, variables of type boolean to false, and reference-type variables to null. 3.7
(Instance Variables) Explain the purpose of an instance variable. ANS: A class provides an instance variable (or several instance variables) when each object
of the class must maintain information separately from all other objects of the class. For example, a class called Account that represents a bank account provides an instance variable to represent the balance of the account. Each Account object maintains its own balance but does not know the balances of the bank’s other accounts. 3.8 (Using Classes Without Importing Them) Most classes need to be imported before they can be used in an application. Why is every application allowed to use classes System and String without first importing them? ANS: Classes System and String are both in package java.lang, which is implicitly imported into every Java source-code file. 3.9 (Using a Class Without Importing It) Explain how a program could use class Scanner without importing it. ANS: If every use of a class’s name in a program is fully qualified, there is no need to import the class. A class’s fully qualified name consists of the class’s package followed by the class name. For example, a program could use class Scanner without importing it if every use of Scanner in the program were specified as java.util.Scanner. 3.10 (set and get Methods) Explain why a class might provide a set method and a get method for an instance variable. ANS: An instance variable is typically declared private in a class so that only the methods of the class in which the instance variable is declared can manipulate it. This prevents the variable from being modified accidentally by a class in another part of the program. In some cases, it may be necessary for an application to modify the private data. For example, the owner of a bank account should be able to deposit or withdraw funds and check the account’s balance. A class’s designer can provide public set and get methods that enable an application to specify the value for, or retrieve the value of, a particular object’s private instance variable.
..
4
Control Statements: Part I, Solutions
Let’s all move one place on. —Lewis Carroll
The wheel is come full circle. —William Shakespeare
How many apples fell on Newton’s head before he took the hint! —Robert Frost
Objectives In this chapter you’ll learn: Basic problem-solving techniques. ■ To develop algorithms through the process of topdown, stepwise refinement. ■ To use the if and if…else selection statements to choose among alternative actions. ■ To use the while repetition statement to execute statements in a program repeatedly. ■ To use counter-controlled repetition and sentinelcontrolled repetition. ■ To use the compound assignment, increment and decrement operators. ■ The portability of primitive data types. ■
..
2
Chapter 4
Control Statements: Part I, Solutions
Self-Review Exercises 4.1
Fill in the blanks in each of the following statements: , a) All programs can be written in terms of three types of control structures: and . ANS: sequence, selection, repetition. statement is used to execute one action when a condition is true and b) The another when that condition is false. ANS: if…else. repetition. c) Repeating a set of instructions a specific number of times is called ANS: counter-controlled (or definite). d) When it’s not known in advance how many times a set of statements will be repeated, value can be used to terminate the repetition. a(n) ANS: sentinel, signal, flag or dummy. structure is built into Java—by default, statements execute in the order e) The they appear. ANS: sequence. f) Instance variables of types char, byte, short, int, long, float and double are all given by default. the value ANS: 0 (zero). language—it requires all variables to have a type. g) Java is a(n) ANS: strongly typed. to a variable, first the variable is incremented by h) If the increment operator is 1, then its new value is used in the expression. ANS: prefixed.
4.2
State whether each of the following is true or false. If false, explain why. a) An algorithm is a procedure for solving a problem in terms of the actions to execute and the order in which they execute. ANS: True. b) A set of statements contained within a pair of parentheses is called a block. ANS: False. A set of statements contained within a pair of braces ({ and }) is called a block. c) A selection statement specifies that an action is to be repeated while some condition remains true. ANS: False. A repetition statement specifies that an action is to be repeated while some condition remains true. d) A nested control statement appears in the body of another control statement. ANS: True. e) Java provides the arithmetic compound assignment operators +=, -=, *=, /= and %= for abbreviating assignment expressions. ANS: True. f) The primitive types (boolean, char, byte, short, int, long, float and double) are portable across only Windows platforms. ANS: False. The primitive types (boolean, char, byte, short, int, long, float and double) are portable across all computer platforms that support Java. g) Specifying the order in which statements (actions) execute in a program is called program control. ANS: True. h) The unary cast operator (double) creates a temporary integer copy of its operand. ANS: False. The unary cast operator (double) creates a temporary floating-point copy of its operand. i) Instance variables of type boolean are given the value true by default. ..
Self-Review Exercises
3
ANS: False. Instance variables of type boolean are given the value false by default. j) Pseudocode helps a programmer think out a program before attempting to write it in a programming language. ANS: True.
4.3
Write four different Java statements that each add 1 to integer variable x. ANS: x = x + 1; x += 1; ++x; x++;
4.4
Write Java statements to accomplish each of the following tasks: a) Use one statement to assign the sum of x and y to z, then increment x by 1. ANS: z = x++ + y;
b) Test whether variable count is greater than 10. If it is, print "Count is greater than 10". ANS: if ( count > 10 ) System.out.println( "Count is greater than 10" );
c) Use one statement to decrement the variable x by 1, then subtract it from variable total and store the result in variable total. ANS: total -= --x;
d) Calculate the remainder after q is divided by divisor, and assign the result to q. Write this statement in two different ways. ANS: q %= divisor; q = q % divisor;
4.5
Write a Java statement to accomplish each of the following tasks: a) Declare variables sum and x to be of type int. ANS: int sum; int x;
b) Assign 1 to variable x. ANS: x = 1;
c) Assign 0 to variable sum. ANS: sum = 0;
d) Add variable x to variable sum, and assign the result to variable sum. ANS: sum += x; or sum = sum + x; e) Print "The sum is: ", followed by the value of variable sum. ANS: System.out.printf( "The sum is: %d\n", sum );
4.6 Combine the statements that you wrote in Exercise 4.5 into a Java application that calculates and prints the sum of the integers from 1 to 10. Use a while statement to loop through the calculation and increment statements. The loop should terminate when the value of x becomes 11. ANS: The program is as follows: 1 2 3 4 5 6 7 8 9 10 11 12
// Exercise 4.6: Calculate.java // Calculate the sum of the integers from 1 to 10 public class Calculate { public static void main( String[] args ) { int sum; int x; x = 1; // initialize x to 1 for counting sum = 0; // initialize sum to 0 for totaling
..
4
13 14 15 16 17 18 19 20 21
Chapter 4
Control Statements: Part I, Solutions
while ( x <= 10 ) // while x is less than or equal to 10 { sum += x; // add x to sum ++x; // increment x } // end while System.out.printf( "The sum is: %d\n", sum ); } // end main } // end class Calculate
The sum is: 55
4.7 Determine the value of the variables in the statement product *= x++; after the calculation is performed. Assume that all variables are type int and initially have the value 5. ANS: product = 25, x = 6 4.8
Identify and correct the errors in each of the following sets of code: a) while ( c <= 5 ) { product *= c; ++c;
ANS: Error: The closing right brace of the while statement’s body is missing.
Correction: Add a closing right brace after the statement ++c;. b) if ( gender == 1 ) System.out.println( "Woman" ); else; System.out.println( "Man" );
ANS: Error: The semicolon after else results in a logic error. The second output statement
will always be executed. Correction: Remove the semicolon after else. 4.9
What is wrong with the following while statement? while ( z >= 0 ) sum += z;
ANS: The value of the variable z is never changed in the while statement. Therefore, if the
loop-continuation condition ( z >= 0 ) is true, an infinite loop is created. To prevent an infinite loop from occurring, z must be decremented so that it eventually becomes less than 0.
Exercises NOTE: Solutions to the programming exercises are located in the ch04solutions folder. Each exercise has its own folder named ex04_## where ## is a two-digit number representing the exercise number. For example, exercise 4.17’s solution is located in the folder ex04_17. 4.10 Compare and contrast the if single-selection statement and the while repetition statement. How are these two statements similar? How are they different? ANS: The if single-selection statement and the while repetition statement both perform an action (or set of actions) based on whether a condition is true or false. However, if the condition is true, the if single-selection statement performs the action(s) once, whereas the while repetition statement repeatedly performs the action(s) until the condition becomes false. ..
Exercises
5
4.11 Explain what happens when a Java program attempts to divide one integer by another. What happens to the fractional part of the calculation? How can a programmer avoid that outcome? ANS: Dividing two integers results in integer division—any fractional part of the calculation is lost (i.e., truncated). For example, 7 ÷ 4, which yields 1.75 in conventional arithmetic, truncates to 1 in integer arithmetic, rather than rounding to 2. To obtain a floating-point result from dividing integer values, a programmer must temporarily treat these values as floating-point numbers in the calculation by using the unary cast operator (double). As long as the (double) cast operator is applied to any variable in the calculation, the calculation will yield a double result which can be assigned to a double variable. 4.12
Describe the two ways in which control statements can be combined. ANS: Control statements can be “attached” (that is, stacked) to one another by connecting the exit point of one to the entry point of the next. Control statements also may be nested by placing one inside another.
4.13 What type of repetition would be appropriate for calculating the sum of the first 100 positive integers? What type would be appropriate for calculating the sum of an arbitrary number of positive integers? Briefly describe how each of these tasks could be performed. ANS: Counter-controlled repetition would be appropriate for calculating the sum of the first 100 positive integers because the number of repetitions is known in advance. The program that performs this task could use a while repetition statement with a counter variable that takes on the values 1 to 100. The program could then add the current counter value to the total variable in each repetition of the loop. Sentinelcontrolled repetition would be appropriate for calculating the sum of an arbitrary number of positive integers. The program that performs this task could use a sentinel value of –1 to mark the end of data entry. The program could use a while repetition statement that totals positive integers from the user until the user enters the sentinel value. 4.14
What is the difference between preincrementing and postincrementing a variable? ANS: Preincrementing a variable causes it to be incremented by 1, and then the new value of the variable is used in the expression in which it appears. Postincrementing a variable causes the current value of the variable to be used in the expression in which it appears, and then the variable’s value is incremented by 1. Preincrementing and postincrementing a variable have the same effect when the incrementing operation appears in a statement by itself.
4.15 Identify and correct the errors in each of the following pieces of code. [Note: There may be more than one error in each piece of code.] a) if ( age >= 65 ); System.out.println( "Age is greater than or equal to 65" ); else System.out.println( "Age is less than 65 )";
ANS: The semicolon at the end of the if condition should be removed. The closing double
quote of the second System.out.println should be inside the closing parenthesis. b) int x = 1, total; while ( x <= 10 ) { total += x; ++x; }
ANS: The variable total should be initialized to zero.
..
6
Chapter 4 c)
Control Statements: Part I, Solutions
while ( x <= 100 ) total += x; ++x;
ANS: The two statements should be enclosed in braces to properly group them into the
body of the while; otherwise the loop will be an infinite loop. d) while ( y > 0 ) { System.out.println( y ); ++y;
ANS: The ++ operator should be changed to --; otherwise the loop will be an infinite loop
if y starts with a value greater than 0. The closing brace for the while loop is missing. 4.16 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
What does the following program print?
// Exercise 4.16: Mystery.java public class Mystery { public static void main( String[] args ) { int y; int x = 1; int total = 0; while ( x <= 10 ) { y = x * x; System.out.println( y ); total += y; ++x; } // end while System.out.printf( "Total is %d\n", total ); } // end main } // end class Mystery
ANS:
1 4 9 16 25 36 49 64 81 100 Total is 385
..
Exercises 4.25 1 2 3 4 5 6 7 8 9 10 11 12 13 14
What does the following program print?
// Exercise 4.25: Mystery2.java public class Mystery2 { public static void main( String[] args ) { int count = 1; while ( count <= 10 ) { System.out.println( count % 2 == 1 ? "****" : "++++++++" ); ++count; } // end while } // end main } // end class Mystery2
ANS:
**** ++++++++ **** ++++++++ **** ++++++++ **** ++++++++ **** ++++++++
4.26 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
What does the following program print?
// Exercise 4.26: Mystery3.java public class Mystery3 { public static void main( String[] args ) { int row = 10; int column; while ( row >= 1 ) { column = 1; while ( column <= 10 ) { System.out.print( row % 2 == 1 ? "<" : ">" ); ++column; } // end while --row; System.out.println(); } // end while } // end main } // end class Mystery3
..
7
8
Chapter 4
Control Statements: Part I, Solutions
ANS: >>>>>>>>>> <<<<<<<<<< >>>>>>>>>> <<<<<<<<<< >>>>>>>>>> <<<<<<<<<< >>>>>>>>>> <<<<<<<<<< >>>>>>>>>> <<<<<<<<<<
4.27 (Dangling-else Problem) Determine the output for each of the given sets of code when x is 9 and y is 11 and when x is 11 and y is 9. Note that the compiler ignores the indentation in a Java program. Also, the Java compiler always associates an else with the immediately preceding if unless told to do otherwise by the placement of braces ({}). On first glance, the programmer may not be sure which if a particular else matches—this situation is referred to as the “dangling-else problem.” We’ve eliminated the indentation from the following code to make the problem more challenging. [Hint: Apply the indentation conventions you’ve learned.] a) if ( x < 10 ) if ( y > 10 ) System.out.println( "*****" ); else System.out.println( "#####" ); System.out.println( "$$$$$" );
ANS:
When: ***** $$$$$
x = 9, y = 11
When: $$$$$
x = 11, y = 9
b) if ( x < 10 ) { if ( y > 10 ) System.out.println( "*****"
);
} else { System.out.println( "#####" ); System.out.println( "$$$$$" ); }
..
Exercises
9
ANS:
When: *****
x = 9, y = 11
When: ##### $$$$$
x = 11, y = 9
4.28 (Another Dangling-else Problem) Modify the given code to produce the output shown in each part of the problem. Use proper indentation techniques. Make no changes other than inserting braces and changing the indentation of the code. The compiler ignores indentation in a Java program. We’ve eliminated the indentation from the given code to make the problem more challenging. [Note: It’s possible that no modification is necessary for some of the parts.] if ( y == 8 ) if ( x == 5 ) System.out.println( "@@@@@" ); else System.out.println( "#####" ); System.out.println( "$$$$$" ); System.out.println( "&&&&&" );
a) Assuming that x = 5 and y = 8, the following output is produced: @@@@@ $$$$$ &&&&&
ANS: if ( y == 8 ) if ( x == 5 ) System.out.println( "@@@@@" ); else System.out.println( "#####" ); System.out.println( "$$$$$" ); System.out.println( "&&&&&" );
b) Assuming that x = 5 and y = 8, the following output is produced: @@@@@
ANS: if ( y == 8 ) if ( x == 5 ) System.out.println( "@@@@@" ); else
{ System.out.println( "#####" ); System.out.println( "$$$$$" ); System.out.println( "&&&&&" ); }
c) Assuming that x = 5 and y = 8, the following output is produced: @@@@@ &&&&&
..
10
Chapter 4
Control Statements: Part I, Solutions
ANS: if ( y == 8 ) if ( x == 5 ) System.out.println( "@@@@@" ); else { System.out.println( "#####" ); System.out.println( "$$$$$" ); } System.out.println( "&&&&&" );
d) Assuming that x = 5 and y = 7, the following output is produced. [Note: The last three output statements after the else are all part of a block.] ##### $$$$$ &&&&&
ANS: if ( y == 8 ) if ( x == 5 ) System.out.println( "@@@@@" ); else { System.out.println( "#####" ); System.out.println( "$$$$$" ); System.out.println( "&&&&&" );
}
4.33 (Multiples of 2 with an Infinite Loop) Write an application that keeps displaying in the command window the multiples of the integer 2—namely, 2, 4, 8, 16, 32, 64, and so on. Your loop should not terminate (i.e., it should create an infinite loop). What happens when you run this program? ANS: The program quickly produces values that are outside the range that can be stored in an int variable, then continues looping, but prints 0s. [The source code for this exercises is located in the ch04solutions\ex04_33 folder.] 4.34 What is wrong with the following statement? Provide the correct statement to add one to the sum of x and y. System.out.println( ++(x + y) );
ANS: ++ can be applied only to a variable—not to an expression with multiple terms. The
correct statement is System.out.println( x + y + 1 ); cd.
..
5
Control Statements: Part 2, Solutions
Let’s all move one place on. —Lewis Carroll
The wheel is come full circle. —William Shakespeare
How many apples fell on Newton’s head before he took the hint! —Robert Frost
All the evolution we know of proceeds from the vague to the definite. —Charles Sanders Peirce
Objectives In this chapter you’ll learn:
..
■
The essentials of countercontrolled repetition.
■
To use the for and do…while repetition statements to execute statements in a program repeatedly.
■
To understand multiple selection using the switch selection statement.
■
To use the break and continue program control statements to alter the flow of control.
■
To use the logical operators to form complex conditional expressions in control statements.
2
Chapter 5
Control Statements: Part 2, Solutions
Self-Review Exercises 5.1
(Fill in the Blanks) Fill in the blanks in each of the following statements: statements are used for counter-controlled repetition and a) Typically, statements for sentinel-controlled repetition. ANS: for, while. executing b) The do…while statement tests the loop-continuation condition the loop’s body; therefore, the body always executes at least once. ANS: after. statement selects among multiple actions based on the possible values c) The of an integer variable or expression. ANS: switch. statement, when executed in a repetition statement, skips the remaining d) The statements in the loop body and proceeds with the next iteration of the loop. ANS: continue. operator can be used to ensure that two conditions are both true before e) The choosing a certain path of execution. ANS: && (conditional AND). , the program f) If the loop-continuation condition in a for header is initially does not execute the for statement’s body. ANS: false. g) Methods that perform common tasks and do not require objects are called methods. ANS: static.
5.2
(True/False Questions) State whether each of the following is true or false. If false, explain why. a) The default case is required in the switch selection statement. ANS: False. The default case is optional. If no default action is needed, then there is no need for a default case. b) The break statement is required in the last case of a switch selection statement. ANS: False. The break statement is used to exit the switch statement. The break statement is not required for the last case in a switch statement. c) The expression ( ( x > y ) && ( a < b ) ) is true if either x > y is true or a < b is true. ANS: False. Both of the relational expressions must be true for the entire expression to be true when using the && operator. d) An expression containing the || operator is true if either or both of its operands are true. ANS: True. e) The comma (,) formatting flag in a format specifier (e.g., %,20.2f) indicates that a value should be output with a thousands separator. ANS: True. f) To test for a range of values in a switch statement, use a hyphen (–) between the start and end values of the range in a case label. ANS: False. The switch statement does not provide a mechanism for testing ranges of values, so every value that must be tested should be listed in a separate case label. g) Listing cases consecutively with no statements between them enables the cases to perform the same set of statements. ANS: True.
5.3 (Write a Statement) Write a Java statement or a set of Java statements to accomplish each of the following tasks: a) Sum the odd integers between 1 and 99, using a for statement. Assume that the integer variables sum and count have been declared. ..
Self-Review Exercises
3
ANS: sum = 0; for ( count = 1; count <= 99; count += 2 ) sum += count;
b) Calculate the value of 2.5 raised to the power of 3, using the pow method. ANS: double result = Math.pow( 2.5, 3 ); c) Print the integers from 1 to 20, using a while loop and the counter variable i. Assume that the variable i has been declared, but not initialized. Print only five integers per line. [Hint: Use the calculation i % 5. When the value of this expression is 0, print a newline character; otherwise, print a tab character. Assume that this code is an application. Use the System.out.println() method to output the newline character, and use the System.out.print( '\t' ) method to output the tab character.] ANS: i = 1; while ( i <= 20 ) { System.out.print( i ); if ( i % 5 == 0 ) System.out.println(); else System.out.print( '\t' ); ++i; }
d) Repeat part (c), using a for statement. ANS: for ( i = 1; i <= 20; i++ ) { System.out.print( i ); if ( i % 5 == 0 ) System.out.println(); else System.out.print( '\t' ); }
5.4 (Find the Error) Find the error in each of the following code segments, and explain how to correct it: a) i = 1; while ( i <= 10 ); i++; }
ANS: Error: The semicolon after the while header causes an infinite loop, and there is a
missing left brace. Correction: Replace the semicolon by a {, or remove both the ; and the }. b) for ( k = 0.1; k != 1.0; k += 0.1 ) System.out.println( k );
ANS: Error: Using a floating-point number to control a for statement may not work, because
floating-point numbers are represented only approximately by most computers. Correction: Use an integer, and perform the proper calculation in order to get the values you desire: ..
4
Chapter 5
Control Statements: Part 2, Solutions for ( k = 1; k != 10; k++ ) System.out.println( (double) k / 10 );
c)
switch ( n ) { case 1: System.out.println( "The number is 1" ); case 2: System.out.println( "The number is 2" ); break; default: System.out.println( "The number is not 1 or 2" ); break; }
ANS: Error: The missing code is the break statement in the statements for the first case.
Correction: Add a break statement at the end of the statements for the first case. Note that this omission is not necessarily an error if you want the statement of case 2: to execute every time the case 1: statement executes. d) The following code should print the values 1 to 10: n = 1; while ( n < 10 ) System.out.println( n++ );
ANS: Error: An improper relational operator is used in the while’s continuation condition.
Correction: Use <= rather than <, or change 10 to 11.
Exercises NOTE: Solutions to the programming exercises are located in the ch05solutions folder. Each exercise has its own folder named ex05_## where ## is a two-digit number representing the exercise number. For example, exercise 5.11’s solution is located in the folder ex05_11. 5.5
Describe the four basic elements of counter-controlled repetition. ANS: Counter-controlled repetition requires a control variable (or loop counter), an initial value of the control variable, an increment (or decrement) by which the control variable is modified each time through the loop, and a loop-continuation condition that determines whether looping should continue.
5.6
Compare and contrast the while and for repetition statements. ANS: The while and for repetition statements repeatedly execute a statement or set of statements as long as a loop-continuation condition remains true. Both statements execute their bodies zero or more times. The for repetition statement specifies the counter-controlled-repetition details in its header, whereas the control variable in a while statement normally is initialized before the loop and incremented in the loop's body. Typically, for statements are used for counter-controlled repetition, and while statements are used for sentinel-controlled repetition. However, while and for can each be used for either repetition type.
5.7 Discuss a situation in which it would be more appropriate to use a do…while statement than a while statement. Explain why. ANS: If you want some statement or set of statements to execute at least once, then repeat based on a condition, a do…while is more appropriate than a while (or a for). A do…while statement tests the loop-continuation condition after executing the loop’s body; therefore, the body always executes at least once. A while tests the loop-con..
Exercises
5
tinuation condition before executing the loop’s body, so the program would need to include the statement(s) required to execute at least once both before the loop and in the body of the loop. Using a do…while avoids this duplication of code. Suppose a program needs to obtain an integer value from the user, and the integer value entered must be positive for the program to continue. In this case, a do…while’s body could contain the statements required to obtain the user input, and the loop-continuation condition could determine whether the value entered is less than 0. If so, the loop would repeat and prompt the user for input again. This would continue until the user entered a value greater than or equal to zero. Once this criterion was met, the loopcontinuation condition would become false, and the loop would terminate, allowing the program to continue past the loop. This process is often called validating input. 5.8
Compare and contrast the break and continue statements. ANS: The break and continue statements alter the flow of control through a control statement. The break statement, when executed in one of the repetition statements, causes immediate exit from that statement. Execution continues with the first statement after the control statement. In contrast, the continue statement, when executed in a repetition statement, skips the remaining statements in the loop body and proceeds with the next iteration of the loop. In while and do…while statements, the program evaluates the loop-continuation test immediately after the continue statement executes. In a for statement, the increment expression executes, then the program evaluates the loop-continuation test.
5.9
Find and correct the error(s) in each of the following segments of code: a) For ( i = 100, i >= 1, i++ ) System.out.println( i );
ANS: The F in for should be lowercase. Semicolons should be used in the for header in-
stead of commas. ++ should be --. 1 2 3 4 5 6 7 8 9 10 11
// Exercise 5.9a: PartA.java public class PartA { public static void main( String args[] ) { int i; For ( i = 100, i >= 1, i++ ) System.out.println( i ); } // end main } // end class PartA
PartA.java:8: ';' expected For ( i = 100, i >= 1, i++ ) ^ 1 error
..
6
1 2 3 4 5 6 7 8 9 10 11
Chapter 5
Control Statements: Part 2, Solutions
// Exercise 5.9a Solution: PartACorrected.java public class PartACorrected { public static void main( String args[] ) { int i; for ( i = 100; i >= 1; i-- ) System.out.println( i ); } // end main } // end class PartACorrected
100 99 98 . . . 3 2 1
b) The following code should print whether integer value is odd or even: switch ( value % 2 ) { case 0: System.out.println( "Even integer" ); case 1: System.out.println( "Odd integer" ); }
ANS: A break statement should be placed in case 0:.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// Exercise 5.9b: PartB.java public class PartB { public static void main( String args[] ) { int value = 8; switch ( value % 2 ) { case 0: System.out.println( "Even integer" ); case 1: System.out.println( "Odd integer" ); } // end main } // end class PartB
Even integer Odd integer
..
Exercises
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// Exercise 5.9b Solution: PartBCorrected.java public class PartBCorrected { public static void main( String args[] ) { int value = 8; switch ( value % 2 ) { case 0: System.out.println( "Even integer" ); break; case 1: System.out.println( "Odd integer" ); } } // end main } // end class PartBCorrected
Even integer
c) The following code should output the odd integers from 19 to 1: for ( i = 19; i >= 1; i += 2 ) System.out.println( i );
ANS: The += operator in the for header should be -=.
1 2 3 4 5 6 7 8 9 10 11
// Exercise 5.9c: PartC.java public class PartC { public static void main( String args[] ) { int i; for ( i = 19; i >= 1; i += 2 ) System.out.println( i ); } // end main } // end class PartC
19 21 23 25 27 29 . . .
..
7
8
1 2 3 4 5 6 7 8 9 10 11
Chapter 5
Control Statements: Part 2, Solutions
// Exercise 5.9c Solution: PartCCorrected.java public class PartCCorrected { public static void main( String args[] ) { int i; for ( i = 19; i >= 1; i -= 2 ) System.out.println( i ); } // end main } // end class PartCCorrected
19 17 15 13 11 9 7 5 3 1
d) The following code should output the even integers from 2 to 100: counter = 2; do { System.out.println( counter ); counter += 2; } While ( counter < 100 );
ANS: The W in while should be lowercase. < should be <=.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Exercise 5.9d: PartD.java public class PartD { public static void main( String args[] ) { int counter; counter = 2; do { System.out.println( counter ); counter += 2; } While ( counter < 100 ); } // end main } // end class PartD
..
Exercises
PartD.java:14: while expected } While ( counter < 100 ); ^ PartD.java:14: ')' expected } While ( counter < 100 ); ^ 2 errors
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Exercise 5.9d Solution: PartDCorrected.java public class PartDCorrected { public static void main( String args[] ) { int counter; counter = 2; do { System.out.println( counter ); counter += 2; } while ( counter <= 100 ); } // end main } // end class PartDCorrected
2 4 6 . . . 96 98 100
5.10 1 2 3 4 5 6 7 8 9 10 11 12 13 14
What does the following program do?
// Exercise 5.10: Printing.java public class Printing { public static void main( String[] args ) { for ( int i = 1; i <= 10; i++ ) { for ( int j = 1; j <= 5; j++ ) System.out.print( '@' ); System.out.println(); } // end outer for } // end main } // end class Printing
..
9
10
Chapter 5
Control Statements: Part 2, Solutions
ANS:
@@@@@ @@@@@ @@@@@ @@@@@ @@@@@ @@@@@ @@@@@ @@@@@ @@@@@ @@@@@
5.13 (Factorials) Factorials are used frequently in probability problems. The factorial of a positive integer n (written n! and pronounced “n factorial”) is equal to the product of the positive integers from 1 to n. Write an application that calculates the factorials of 1 through 20. Use type long. Display the results in tabular format. What difficulty might prevent you from calculating the factorial of 100? ANS: The value of 100! far exceeds the maximum value that can be stored in a long. For calculations involving large integer values, you can use class java.math.BigInteger instead. [See the code for this solution in the ch05solutions\ex05_13 folder.] 5.19
Assume that i = 1, j = 2, k = 3 and m = 2. What does each of the following statements print? a) System.out.println( i == 1 ); ANS: true. b) System.out.println( j == 3 ); ANS: false. c) System.out.println( ( i >= 1 ) && ( j < 4 ) ); ANS: true. d) System.out.println( ( m <= 99 ) & ( k < m ) ); ANS: false. e) System.out.println( ( j >= i ) || ( k == m ) ); ANS: true. f) System.out.println( ( k + m < j ) | ( 3 - j >= k ) ); ANS: false. g) System.out.println( !( k > m ) ); ANS: false.
(Calculating the Value of π) Calculate the value of π from the infinite series 4 4 4 4 4 π = 4 – --- + --- – --- + --- – ------ + … 3 5 7 9 11 Print a table that shows the value of π approximated by computing the first 200,000 terms of this series. How many terms do you have to use before you first get a value that begins with 3.14159? ANS: [Note: The program starts to converge around 3.14159 at 136121 terms.]
5.20
5.26 A criticism of the break statement and the continue statement is that each is unstructured. Actually, these statements can always be replaced by structured statements, although doing so can be awkward. Describe in general how you’d remove any break statement from a loop in a program and replace it with some structured equivalent. [Hint: The break statement exits a loop from the body of the loop. The other way to exit is by failing the loop-continuation test. Consider using in the loop-continuation test a second test that indicates “early exit because of a ‘break’ condition.”]
..
Exercises
11
Use the technique you develop here to remove the break statement from the application in Fig. 5.12. ANS: A loop can be written without a break by placing in the loop-continuation test a second test that indicates “early exit because of a ‘break’ condition.” Alternatively, the break can be replaced by a statement that makes the original loop-continuation test immediately false, so that the loop terminates. [See the code for this solution in the ch05solutions\ex05_26 folder.] 5.27
What does the following program segment do? for ( i = 1; i <= 5; i++ ) { for ( j = 1; j <= 3; j++ ) { for ( k = 1; k <= 4; k++ ) System.out.print( '*' ); System.out.println(); } // end inner for System.out.println(); } // end outer for
ANS:
**** **** **** **** **** **** **** **** **** **** **** **** **** **** ****
5.28 Describe in general how you’d remove any continue statement from a loop in a program and replace it with some structured equivalent. Use the technique you develop here to remove the continue statement from the program in Fig. 5.13. ANS: A loop can be rewritten without a continue statement by moving all the code that appears in the body of the loop after the continue statement to an if statement that tests for the opposite of the continue condition. Thus, the code that was originally after the continue statement executes only when the if statement’s conditional expression is true (i.e., the “continue” condition is false). When the “continue” condition is true, the body of the if does not execute and the program “continues” to the next iteration of the loop by not executing the remaining code in the loop’s body. [See the code for this solution in the ch05solutions\ex05_28 folder.] ..
6
Methods: A Deeper Look, Solutions
E pluribus unum. (One composed of many.) —Virgil
O! call back yesterday, bid time return. —William Shakespeare
Call me Ishmael. —Herman Melville
Answer me in one word. —William Shakespeare
There is a point at which methods devour themselves. —Frantz Fanon
Objectives In this chapter you’ll learn: How static methods and fields are associated with classea rather than objects. ■ How the method call/return mechanism is supported by the method-call stack. ■ How packages group related classes. ■ How to use random-number generation to implement game-playing applications. ■ How the visibility of declarations is limited to specific regions of programs. ■ What method overloading is and how to create overloaded methods. ■
Self-Review Exercises
2
Self-Review Exercises Fill in the blanks in each of the following statements: . a) A method is invoked with a(n) ANS: method call. b) A variable known only within the method in which it’s declared is called a(n) . ANS: local variable. statement in a called method can be used to pass the value of an exc) The pression back to the calling method. ANS: return. indicates that a method does not return a value. d) The keyword ANS: void. e) Data can be added or removed only from the of a stack. ANS: top. data structures—the last item pushed (inserted) on f) Stacks are known as the stack is the first item popped (removed) from the stack. ANS: last-in, first-out (LIFO). , g) The three ways to return control from a called method to a caller are and . ANS: return; or return expression; or encountering the closing right brace of a method. produces random numbers. h) An object of class ANS: Random. i) The program-execution stack contains the memory for local variables on each invocation of a method during a program’s execution. This data, stored as a portion of the proor of the method call. gram-execution stack, is known as the ANS: activation record, stack frame. j) If there are more method calls than can be stored on the program-execution stack, an occurs. error known as a(n) ANS: stack overflow. of a declaration is the portion of a program that can refer to the entity k) The in the declaration by name. ANS: scope. l) It’s possible to have several methods with the same name that each operate on different . types or numbers of arguments. This feature is called method ANS: method overloading. stack. m) The program-execution stack is also referred to as the ANS: method call. 6.2 For the class Craps in Fig. 6.9, state the scope of each of the following entities: ANS: class body. a) the variable randomNumbers. b) the variable die1. ANS: block that defines method rollDice’s body. c) the method rollDice. ANS: class body. d) the method play. ANS: class body. e) the variable sumOfDice. ANS: block that defines method play’s body. 6.3 Write an application that tests whether the examples of the Math class method calls shown in Fig. 6.2 actually produce the indicated results. 6.1
3
Chapter 6
Methods: A Deeper Look, Solutions
ANS: The following solution demonstrates the Math class methods in Fig. 6.2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
// Exercise 6.3: MathTest.java // Testing the Math class methods. public class MathTest { public static void main( String[] args ) { System.out.printf( "Math.abs( 23.7 ) = %f\n", Math.abs( 23.7 ) ); System.out.printf( "Math.abs( 0.0 ) = %f\n", Math.abs( 0.0 ) ); System.out.printf( "Math.abs( -23.7 ) = %f\n", Math.abs( -23.7 ) ); System.out.printf( "Math.ceil( 9.2 ) = %f\n", Math.ceil( 9.2 ) ); System.out.printf( "Math.ceil( -9.8 ) = %f\n", Math.ceil( -9.8 ) ); System.out.printf( "Math.cos( 0.0 ) = %f\n", Math.cos( 0.0 ) ); System.out.printf( "Math.exp( 1.0 ) = %f\n", Math.exp( 1.0 ) ); System.out.printf( "Math.exp( 2.0 ) = %f\n", Math.exp( 2.0 ) ); System.out.printf( "Math.floor( 9.2 ) = %f\n", Math.floor( 9.2 ) ); System.out.printf( "Math.floor( -9.8 ) = %f\n", Math.floor( -9.8 ) ); System.out.printf( "Math.log( Math.E ) = %f\n", Math.log( Math.E ) ); System.out.printf( "Math.log( Math.E * Math.E ) = %f\n", Math.log( Math.E * Math.E ) ); System.out.printf( "Math.max( 2.3, 12.7 ) = %f\n", Math.max( 2.3, 12.7 ) ); System.out.printf( "Math.max( -2.3, -12.7 ) = %f\n", Math.max( -2.3, -12.7 ) ); System.out.printf( "Math.min( 2.3, 12.7 ) = %f\n", Math.min( 2.3, 12.7 ) ); System.out.printf( "Math.min( -2.3, -12.7 ) = %f\n", Math.min( -2.3, -12.7 ) ); System.out.printf( "Math.pow( 2.0, 7.0 ) = %f\n", Math.pow( 2.0, 7.0 ) ); System.out.printf( "Math.pow( 9.0, 0.5 ) = %f\n", Math.pow( 9.0, 0.5 ) ); System.out.printf( "Math.sin( 0.0 ) = %f\n", Math.sin( 0.0 ) ); System.out.printf( "Math.sqrt( 900.0 ) = %f\n", Math.sqrt( 900.0 ) ); System.out.printf( "Math.tan( 0.0 ) = %f\n", Math.tan( 0.0 ) ); } // end main } // end class MathTest
Math.abs( 23.7 ) = 23.700000 Math.abs( 0.0 ) = 0.000000 Math.abs( -23.7 ) = 23.700000 Math.ceil( 9.2 ) = 10.000000 Math.ceil( -9.8 ) = -9.000000 Math.cos( 0.0 ) = 1.000000 Math.exp( 1.0 ) = 2.718282 Math.exp( 2.0 ) = 7.389056 Math.floor( 9.2 ) = 9.000000 Math.floor( -9.8 ) = -10.000000 Math.log( Math.E ) = 1.000000 Math.log( Math.E * Math.E ) = 2.000000 Math.max( 2.3, 12.7 ) = 12.700000 Math.max( -2.3, -12.7 ) = -2.300000 Math.min( 2.3, 12.7 ) = 2.300000 Math.min( -2.3, -12.7 ) = -12.700000 Math.pow( 2.0, 7.0 ) = 128.000000 Math.pow( 9.0, 0.5 ) = 3.000000 Math.sin( 0.0 ) = 0.000000 Math.sqrt( 900.0 ) = 30.000000 Math.tan( 0.0 ) = 0.000000
Self-Review Exercises 6.4
4
Give the method header for each of the following methods: a) Method hypotenuse, which takes two double-precision, floating-point arguments side1 and side2 and returns a double-precision, floating-point result. ANS: double hypotenuse( double side1, double side2 )
b) Method smallest, which takes three integers x, y and z and returns an integer. ANS: int smallest( int x, int y, int z )
c) Method instructions, which does not take any arguments and does not return a value. [Note: Such methods are commonly used to display instructions to a user.] ANS: void instructions()
d) Method intToFloat, which takes an integer argument number and returns a floatingpoint result. ANS: float intToFloat( int number )
6.5
Find the error in each of the following program segments. Explain how to correct the error. a) void g() { System.out.println( "Inside method g" ); void h() { System.out.println( "Inside method h" ); } }
ANS: Error: Method h is declared within method g.
Correction: Move the declaration of h outside the declaration of g. b) int sum( int x, int y ) { int result; result = x + y; }
ANS: Error: The method is supposed to return an integer, but does not.
Correction: Delete the variable result, and place the statement return x + y;
in the method, or add the following statement at the end of the method body: return result;
c)
void f( float a ); { float a; System.out.println( a ); }
ANS: Error: The semicolon after the right parenthesis of the parameter list is incorrect, and
the parameter a should not be redeclared in the method. Correction: Delete the semicolon after the right parenthesis of the parameter list, and delete the declaration float a;. d) void product() { int a = 6, b = 5, c = 4, result; result = a * b * c; System.out.printf( "Result is %d\n", result ); return result; }
5
Chapter 6
Methods: A Deeper Look, Solutions
ANS: Error: The method returns a value when it’s not supposed to.
Correction: Change the return type from void to int. 6.6 Write a complete Java application to prompt the user for the double radius of a sphere, and call method sphereVolume to calculate and display the volume of the sphere. Use the following statement to calculate the volume: double volume = ( 4.0 / 3.0 ) * Math.PI * Math.pow( radius, 3 )
ANS: The following solution calculates the volume of a sphere, using the radius entered by
the user: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
// Exercise 6.6: Sphere.java // Calculate the volume of a sphere. import java.util.Scanner;
1 2 3 4 5 6 7 8 9 10 11 12
// Exercise 6.6: SphereTest.java // Calculate the volume of a sphere.
public class Sphere { // obtain radius from user and display volume of sphere public void determineSphereVolume() { Scanner input = new Scanner( System.in ); System.out.print( "Enter radius of sphere: " ); double radius = input.nextDouble(); System.out.printf( "Volume is %f\n", sphereVolume( radius ) ); } // end method determineSphereVolume
// calculate and return sphere volume public double sphereVolume( double radius ) { double volume = ( 4.0 / 3.0 ) * Math.PI * Math.pow( radius, 3 ); return volume; } // end method sphereVolume } // end class Sphere
public class SphereTest { // application starting point public static void main( String[] args ) { Sphere mySphere = new Sphere(); mySphere.determineSphereVolume(); } // end main } // end class SphereTest
Enter radius of sphere: 4 Volume is 268.082573
Exercises
6
Exercises NOTE: Solutions to the programming exercises are located in the ch06solutions folder. Each exercise has its own folder named ex06_## where ## is a two-digit number representing the exercise number. For example, exercise 6.8’s solution is located in the folder ex06_08. 6.7
What is the value of x after each of the following statements is executed? a) x = Math.abs( 7.5 ); ANS: 7.5 b) x = Math.floor( 7.5 ); ANS: 7.0 c) x = Math.abs( 0.0 ); ANS: 0.0 d) x = Math.ceil( 0.0 ); ANS: 0.0 e) x = Math.abs( -6.4 ); ANS: 6.4 f) x = Math.ceil( -6.4 ); ANS: -6.0 g) x = Math.ceil( -Math.abs( -8 + Math.floor( -5.5 ) ) ); ANS: -14.0
6.11
Answer each of the following questions: a) What does it mean to choose numbers “at random”? ANS: Every number has an equal chance of being chosen at any time. b) Why is the nextInt method of class Random useful for simulating games of chance? ANS: Because it produces a series of random numbers. c) Why is it often necessary to scale or shift the values produced by a Random object? ANS: To produce random numbers in a specific range. d) Why is computerized simulation of real-world situations a useful technique? ANS: It enables more accurate predictions of random events, such as cars arriving at toll booths and people arriving in lines at a supermarket. The results of a simulation can help determine how many toll booths to have open or how many cashiers to have open at specified times.
6.12
Write statements that assign random integers to the variable n in the following ranges: a) 1 ≤ n ≤ 2 ANS: n = 1 + randomNumbers.nextInt( 2 ); b) 1 ≤ n ≤ 100 ANS: n = 1 + randomNumbers.nextInt( 100 ); c) 0 ≤ n ≤ 9 ANS: n = randomNumbers.nextInt( 10 ); d) 1000 ≤ n ≤ 1112 ANS: n = 1000 + randomNumbers.nextInt( 113 ); e) –1 ≤ n ≤ 1 ANS: n = -1 + randomNumbers.nextInt( 3 ); f) –3 ≤ n ≤ 11 ANS: n = -3 + randomNumbers.nextInt( 15 ); ANS: [Note: See the test program in the ch06solutions\ex06_12 folder.]
6.13 For each of the following sets of integers, write a single statement that will display a number at random from the set:
7
Chapter 6
Methods: A Deeper Look, Solutions
a) 2, 4, 6, 8, 10. ANS: System.out.println( 2 + randomNumbers.nextInt( 5 ) * 2 );
b) 3, 5, 7, 9, 11. ANS: System.out.println( 3 + randomNumbers.nextInt( 5 ) * 2 );
c) 6, 10, 14, 18, 22. ANS: System.out.println( 6 + randomNumbers.nextInt( 5 ) * 4 ); ANS: [Note: See the test program in the ch06solutions\ex06_12 folder.]
7
Arrays and ArrayLists: Solutions
Begin at the beginning, … and go on till you come to the end: then stop. —Lewis Carroll
Now go, write it before them in a table, and note it in a book. —Isaiah 30:8
To go beyond is as wrong as to fall short. —Confucius l
Objectives In this chapter you’ll learn: What arrays are. ■ To use arrays to store data in and retrieve data from lists and tables of values. ■ To declare arrays, initialize arrays and refer to individual elements of arrays. ■ To iterate through arrays with the enhanced for statement. ■ To pass arrays to methods. ■ To declare and manipulate multidimensional arrays. ■ To use variable-length argument lists. ■ To read command-line arguments into a program. ■ To perform common array manipulations with the methods of class Arrays. ■ To use class ArrayList to manipulate a dynamically resizable array-like data structure. ■
2
Chapter 7
Arrays and ArrayLists: Solutions
Self-Review Exercises 7.1
Fill in the blank(s) in each of the following statements: . a) Lists and tables of values can be stored in ANS: arrays. (called elements or components) containing values that b) An array is a group of . all have the same ANS: variables, type. allows programmers to iterate through the elements in an array without c) The using a counter. ANS: enhanced for statement. . d) The number used to refer to a particular array element is called the element’s ANS: index (or subscript or position number). e) An array that uses two indices is referred to as a(n) array. ANS: two-dimensional. to walk through double array numbers. f) Use the enhanced for statement ANS: for ( double d : numbers ). . g) Command-line arguments are stored in ANS: an array of Strings, called args by convention. to receive the total number of arguments in a command h) Use the expression line. Assume that command-line arguments are stored in String[] args. ANS: args.length. . i) Given the command java MyClass test, the first command-line argument is ANS: test. in the parameter list of a method indicates that the method can receive j) A(n) a variable number of arguments. ANS: ellipsis (...)
7.2
Determine whether each of the following is true or false. If false, explain why. a) An array can store many different types of values. ANS: False. An array can store only values of the same type. b) An array index should normally be of type float. ANS: False. An array index must be an integer or an integer expression. c) An individual array element that is passed to a method and modified in that method will contain the modified value when the called method completes execution. ANS: For individual primitive-type elements of an array: False. A called method receives and manipulates a copy of the value of such an element, so modifications do not affect the original value. If the reference of an array is passed to a method, however, modifications to the array elements made in the called method are indeed reflected in the original. For individual elements of a reference type: True. A called method receives a copy of the reference of such an element, and changes to the referenced object will be reflected in the original array element. d) Command-line arguments are separated by commas. ANS: False. Command-line arguments are separated by white space.
7.3
Perform the following tasks for an array called fractions: a) Declare a constant ARRAY_SIZE that is initialized to 10. ANS: final int ARRAY_SIZE = 10; b) Declare an array with ARRAY_SIZE elements of type double, and initialize the elements to 0. ANS: double[] fractions = new double[ ARRAY_SIZE ];
c) Refer to array element 4. ANS: fractions[ 4 ]
Exercises
3
d) Assign the value 1.667 to array element 9. ANS: fractions[ 9 ] = 1.667;
e) Assign the value 3.333 to array element 6. ANS: fractions[ 6 ] = 3.333;
f) Sum all the elements of the array, using a for statement. Declare the integer variable x as a control variable for the loop. ANS: double total = 0.0; for ( int x = 0; x < fractions.length; x++ ) total += fractions[ x ];
7.4
Perform the following tasks for an array called table: a) Declare and create the array as an integer array that has three rows and three columns. Assume that the constant ARRAY_SIZE has been declared to be 3. ANS: int[][] table = new int[ ARRAY_SIZE ][ ARRAY_SIZE ];
b) How many elements does the array contain? ANS: Nine.
c) Use a for statement to initialize each element of the array to the sum of its indices. Assume that the integer variables x and y are declared as control variables. ANS: for ( int x = 0; x < table.length; x++ ) for ( int y = 0; y < table[ x ].length; y++ ) table[ x ][ y ] = x + y;
7.5
Find and correct the error in each of the following program segments: a) final int ARRAY_SIZE = 5; ARRAY_SIZE = 10;
ANS: Error: Assigning a value to a constant after it has been initialized.
Correction: Assign the correct value to the constant in a final int ARRAY_SIZE declaration or declare another variable. b) Assume int[] b = new int[ 10 ]; for ( int i = 0; i <= b.length; i++ ) b[ i ] = 1;
ANS: Error: Referencing an array element outside the bounds of the array (b[10]).
Correction: Change the <= operator to <. c) Assume int[][] a = { { 1, 2 }, { 3, 4 } }; a[ 1, 1 ] = 5;
ANS: Error: Array indexing is performed incorrectly.
Correction: Change the statement to a[ 1 ][ 1 ] = 5;.
Exercises NOTE: Solutions to the programming exercises are located in the ch07solutions folder. Each exercise has its own folder named ex07_## where ## is a two-digit number representing the exercise number. For example, exercise 7.10’s solution is located in the folder ex07_10. 7.6
Fill in the blanks in each of the following statements: a) One-dimensional array p contains four elements. The names of those elements are , , and . ANS: p[ 0 ], p[ 1 ], p[ 2 ], and p[ 3 ]
b) Naming an array, stating its type and specifying the number of dimensions in the array the array. is called ANS: declaring
4
Chapter 7
Arrays and ArrayLists: Solutions
c) In a two-dimensional array, the first index identifies the of an element and the of an element. second index identifies the ANS: row, column rows, columns and elements. d) An m-by-n array contains ANS: m, n, m · n e) The name of the element in row 3 and column 5 of array d is . ANS: d[ 3 ][ 5 ] 7.7
Determine whether each of the following is true or false. If false, explain why. a) To refer to a particular location or element within an array, we specify the name of the array and the value of the particular element. ANS: False. The name of the array and the index are specified. b) An array declaration reserves space for the array. ANS: False. Arrays must be dynamically allocated with new in Java. c) To indicate that 100 locations should be reserved for integer array p, the programmer writes the declaration p[ 100 ];
ANS: False. The correct declaration is int p[] = new int[ 100 ];
d) An application that initializes the elements of a 15-element array to zero must contain at least one for statement. ANS: False. Numeric arrays are automatically initialized to zero. Also, a member initializer list can be used. e) An application that totals the elements of a two-dimensional array must contain nested for statements. ANS: False. It is possible to total the elements of a two-dimensional array with nested while statements, nested do…while statements or even individual totaling statements. 7.8
Write Java statements to accomplish each of the following tasks: a) Display the value of element 6 of array f. ANS: System.out.print( f[ 6 ] ); b) Initialize each of the five elements of one-dimensional integer array g to 8. ANS: int g[] = { 8, 8, 8, 8, 8 ); c) Total the 100 elements of floating-point array c. ANS: for ( int k = 0; k < c.length; k++ ) total += c[ k ];
1 2 3 4 5 6 7 8 9 10 11 12 13
// Exercise 7.8c Solution: PartC.java public class PartC { public static void main( String args[] ) { double c[] = new double[ 100 ]; double total = 0; // c) for ( int k = 0; k < c.length; k++ ) total += c[ k ]; } // end main } // end class PartC
Exercises
5
d) Copy 11-element array a into the first portion of array b, which contains 34 elements. ANS: for ( int j = 0; j < a.length; j++ ) b[ j ] = a[ j ];
1 2 3 4 5 6 7 8 9 10 11 12 13
// Exercise 7.8d Solution: PartD.java public class PartD { public static void main( String args[] ) { double a[] = new double[ 11 ]; double b[] = new double[ 34 ]; // d) for ( int j = 0; j < a.length; j++ ) b[ j ] = a[ j ]; } // end main } // end class PartD
e) Determine and display the smallest and largest values contained in 99-element floatingpoint array w. ANS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Exercise 7.8e Solution: PartE.java public class PartE { public static void main( String args[] ) { double w[] = new double[ 99 ]; double small = w[ 0 ]; double large = w[ 0 ]; // e) for ( int i = 0; i < w.length; i++ ) if ( w[ i ] < small ) small = w[ i ]; else if ( w[ i ] > large ) large = w[ i ]; System.out.printf( "%f } // end main } // end class PartE
0.000000
7.9
%f\n", small, large );
0.000000
Consider a two-by-three integer array t. a) Write a statement that declares and creates t. ANS: int t[][] = new int[ 2 ][ 3 ]; b) How many rows does t have? ANS: two.
6
Chapter 7
Arrays and ArrayLists: Solutions
c) How many columns does t have? ANS: three. d) How many elements does t have? ANS: six. e) Write the access expressions for all the elements in row 1 of t. ANS: t[ 1 ][ 0 ], t[ 1 ][ 1 ], t[ 1 ][ 2 ] f) Write the access expressions for all the elements in column 2 of t. ANS: t[ 0 ][ 2 ], t[ 1 ][ 2 ] g) Write a single statement that sets the element of t in row 0 and column 1 to zero. ANS: t[ 0 ][ 1 ] = 0; h) Write individual statements to initialize each element of t to zero. ANS: t[ 0 ][ 0 ] = 0; t[ 0 ][ 1 ] = 0; t[ 0 ][ 2 ] = 0; t[ 1 ][ 0 ] = 0; t[ 1 ][ 1 ] = 0; t[ 1 ][ 2 ] = 0; i) Write a nested for statement that initializes each element of t to zero. ANS: for ( int j = 0; j < t.length; j++ ) for ( int k = 0; k < t[ j ].length; k++ ) t[ j ][ k ] = 0; j) Write a nested for statement that inputs the values for the elements of t from the user. ANS: for ( int j = 0; j < t.length; j++ ) for ( int k = 0; k < t[ j ].length; k++ ) t[ j ][ k ] = input.nextInt();
k) Write a series of statements that determines and displays the smallest value in t. ANS: int smallest = t[ 0 ][ 0 ]; for ( int j = 0; j < t.length; j++ ) for ( int k = 0; k < t[ j ].length; k++ ) if ( t[ x ][ y ] < smallest ) smallest = t[ x ][ y ]; System.out.println( smallest );
l) Write a single printf statement that displays the elements of the first row of t. ANS: System.out.printf( “%d %d %d\n", t[ 0 ][ 0 ], t[ 0 ][ 1 ], t[ 0 ][ 2 ] ); m) Write a statement that totals the elements of the third column of t. Do not use repetition. ANS: int total = t[ 0 ][ 2 ] + t[ 1 ][ 2 ]; n) Write a series of statements that displays the contents of t in tabular format. List the column indices as headings across the top, and list the row indices at the left of each row. ANS: System.out.println( "\t0\t1\t2\n" ); for ( int e = 0; e < t.length; e++ ) { System.out.print( e ); for ( int r = 0; r < t[ e ].length; r++ ) System.out.printf( "\t%d", t[ e ][ r ] );
Exercises
System.out.println(); } // end for
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
// Exercise 7.9 Solution: Array.java import java.util.Scanner; public class Array { public static void main( String args[] ) { Scanner input = new Scanner( System.in ); // a) int t[][] = new int[ 2 ][ 3 ]; // g) t[ 0 ][ 1 ] = 0; // h) t[ 0 ][ 0 ] = 0; t[ 0 ][ 1 ] = 0; t[ 0 ][ 2 ] = 0; t[ 1 ][ 0 ] = 0; t[ 1 ][ 1 ] = 0; t[ 1 ][ 2 ] = 0; // i) for ( int j = 0; j < t.length; j++ ) for ( int k = 0; k < t[ j ].length; k++ ) t[ j ][ k ] = 0; // j) for ( int j = 0; j < t.length; j++ ) for ( int k = 0; k < t[ j ].length; k++ ) t[ j ][ k ] = input.nextInt(); // k) int small = t[ 0 ][ 0 ]; for ( int j = 0; j < t.length; j++ ) for ( int k = 0; k < t[ j ].length; k++ ) if ( t[ j ][ k ] < small ) small = t[ j ][ k ]; System.out.println( small ); // l) System.out.printf( "%d %d %d\n", t[ 0 ][ 0 ], t[ 0 ][ 1 ], t[ 0 ][ 2 ] ); // m int total = t[ 0 ][ 2 ] + t[ 1 ][ 2 ];
7
8 51 52 53 54 55 56 57 58 59 60 61 62 63
Chapter 7
Arrays and ArrayLists: Solutions
// n System.out.println( "\t0\t1\t2\n" ); for ( int e = 0; e < t.length; e++ ) { System.out.print( e ); for ( int r = 0; r < t[ e ].length; r++ ) System.out.printf( "\t%d", t[ e ][ r ] ); System.out.println(); } // end for } // end main } // end class Array
1 2 3 4 5 6 1 1 2 3 0
1
2
0 1
1 4
2 5
3 6
7.11
Write statements that perform the following one-dimensional-array operations: a) Set the 10 elements of integer array counts to zero. ANS: for ( int u = 0; u < counts.length; u++ ) counts[ u ] = 0; b) Add one to each of the 15 elements of integer array bonus. ANS: for ( int v = 0; v < bonus.length; v++ ) bonus[ v ]++;
c) Display the five values of integer array bestScores in column format. ANS: for ( int w = 0; w < bestScores.length; w++ ) System.out.println( bestScores[ w ] );
7.13 Label the elements of three-by-five two-dimensional array sales to indicate the order in which they are set to zero by the following program segment: for ( int row = 0; row < sales.length; row++ ) { for ( int col = 0; col < sales[ row ].length; col++ ) { sales[ row ][ col ] = 0; } }
ANS: sales[ 0 ][ 0 ], sales[ 0 ][ 1 ], sales[ 0 ][ 2 ], sales[ 0 ][ 3 ], sales[ 0 ][ 4 ], sales[ 1 ][ 0 ], sales[ 1 ][ 1 ], sales[ 1 ][ 2 ], sales[ 1 ][ 3 ], sales[ 1 ][ 4 ], sales[ 2 ][ 0 ], sales[ 2 ][ 1 ], sales[ 2 ][ 2 ], sales[ 2 ][ 3 ], sales[ 2 ][ 4 ]
Special Section: Building Your Own Computer
9
Special Section: Building Your Own Computer In the next several problems, we take a temporary diversion from the world of high-level language programming to “peel open” a computer and look at its internal structure. We introduce machinelanguage programming and write several machine-language programs. To make this an especially valuable experience, we then build a computer (through the technique of software-based simulation) on which you can execute your machine-language programs. 7.35 (Machine-Language Programming) Let’s create a computer called the Simpletron. As its name implies, it’s a simple, but powerful, machine. The Simpletron runs programs written in the only language it directly understands: Simpletron Machine Language (SML). The Simpletron contains an accumulator—a special register in which information is put before the Simpletron uses that information in calculations or examines it in various ways. All the information in the Simpletron is handled in terms of words. A word is a signed four-digit decimal number, such as +3364, -1293, +0007 and -0001. The Simpletron is equipped with a 100-word memory, and these words are referenced by their location numbers 00, 01, …, 99. Before running an SML program, we must load, or place, the program into memory. The first instruction (or statement) of every SML program is always placed in location 00. The simulator will start executing at this location. Each instruction written in SML occupies one word of the Simpletron’s memory (and hence instructions are signed four-digit decimal numbers). We shall assume that the sign of an SML instruction is always plus, but the sign of a data word may be either plus or minus. Each location in the Simpletron’s memory may contain an instruction, a data value used by a program or an unused (and hence undefined) area of memory. The first two digits of each SML instruction are the operation code specifying the operation to be performed. SML operation codes are summarized in Fig. 7.33.
Operation code
Meaning
Input/output operations: final int READ = 10;
final int WRITE = 11;
Read a word from the keyboard into a specific location in memory. Write a word from a specific location in memory to the screen.
Load/store operations: final int LOAD = 20;
final int STORE = 21;
Load a word from a specific location in memory into the accumulator. Store a word from the accumulator into a specific location in memory.
Arithmetic operations: final int ADD = 30;
final int SUBTRACT = 31;
final int DIVIDE = 32;
Add a word from a specific location in memory to the word in the accumulator (leave the result in the accumulator). Subtract a word from a specific location in memory from the word in the accumulator (leave the result in the accumulator). Divide a word from a specific location in memory into the word in the accumulator (leave result in the accumulator).
Fig. 7.33 | Simpletron Machine Language (SML) operation codes. (Part 1 of 2.)
10
Chapter 7
Arrays and ArrayLists: Solutions
Operation code
Meaning
final int MULTIPLY = 33;
Multiply a word from a specific location in memory by the word in the accumulator (leave the result in the accumulator).
Transfer-of-control operations: final int BRANCH = 40; final int BRANCHNEG = 41;
final int BRANCHZERO = 42;
final int HALT = 43;
Branch to a specific location in memory. Branch to a specific location in memory if the accumulator is negative. Branch to a specific location in memory if the accumulator is zero. Halt. The program has completed its task.
Fig. 7.33 | Simpletron Machine Language (SML) operation codes. (Part 2 of 2.) The last two digits of an SML instruction are the operand—the address of the memory location containing the word to which the operation applies. Let’s consider several simple SML programs. The first SML program (Fig. 7.34) reads two numbers from the keyboard and computes and displays their sum. The instruction +1007 reads the first number from the keyboard and places it into location 07 (which has been initialized to 0). Then instruction +1008 reads the next number into location 08. The load instruction, +2007, puts the first number into the accumulator, and the add instruction, +3008, adds the second number to the number in the accumulator. All SML arithmetic instructions leave their results in the accumulator. The store instruction, +2109, places the result back into memory location 09, from which the write instruction, +1109, takes the number and displays it (as a signed four-digit decimal number). The halt instruction, +4300, terminates execution.
Location
Number
Instruction
00 01 02 03 04 05 06 07 08 09
+1007
(Read A) (Read B) (Load A) (Add B) (Store C) (Write C) (Halt) (Variable A) (Variable B) (Result C)
+1008 +2007 +3008 +2109 +1109 +4300 +0000 +0000 +0000
Fig. 7.34 | SML program that reads two integers and computes their sum.
Special Section: Building Your Own Computer
11
The second SML program (Fig. 7.35) reads two numbers from the keyboard and determines and displays the larger value. Note the use of the instruction +4107 as a conditional transfer of control, much the same as Java’s if statement.
Location
Number
Instruction
00 01 02 03 04 05 06 07 08 09 10
+1009
(Read A) (Read B) (Load A) (Subtract B) (Branch negative to 07) (Write A) (Halt) (Write B) (Halt) (Variable A) (Variable B)
+1010 +2009 +3110 +4107 +1109 +4300 +1110 +4300 +0000 +0000
Fig. 7.35 | SML program that reads two integers and determines the larger. Now write SML programs to accomplish each of the following tasks: a) Use a sentinel-controlled loop to read 10 positive numbers. Compute and display their sum. ANS: Note: This program terminates when a negative number is input. The problem statement should state that only positive numbers should be input. 00
+1009
(Read Value)
01
+2009
(Load Value)
02
+4106
(Branch negative to 06)
03
+3008
(Add Sum)
04
+2108
(Store Sum)
05
+4000
(Branch 00)
06
+1108
(Write Sum)
07
+4300
(Halt)
08
+0000
(Storage for Sum)
09
+0000
(Storage for Value)
b) Use a counter-controlled loop to read seven numbers, some positive and some negative, and compute and display their average. ANS: 00
+2018
(Load Counter)
01
+3121
(Subtract Termination)
02
+4211
(Branch zero to 11)
03
+2018
(Load Counter)
12
Chapter 7
Arrays and ArrayLists: Solutions
04
+3019
(Add Increment)
05
+2118
(Store Counter)
06
+1017
(Read Value)
07
+2016
(Load Sum)
08
+3017
(Add Value)
09
+2116
(Store Sum)
10
+4000
(Branch 00)
11
+2016
(Load Sum)
12
+3218
(Divide Counter)
13
+2120
(Store Result)
14
+1120
(Write Result)
15
+4300
(Halt)
16
+0000
(Variable Sum)
17
+0000
(Variable Value)
18
+0000
(Variable Counter)
19
+0001
(Variable Increment)
20
+0000
(Variable Result)
21
+0007
(Variable Termination)
c) Read a series of numbers, and determine and display the largest number. The first number read indicates how many numbers should be processed. ANS: 00
+1017
(Read Endvalue)
01
+2018
(Load Counter)
02
+3117
(Subtract Endvalue)
03
+4215
(Branch zero to 15)
04
+2018
(Load Counter)
05
+3021
(Add Increment)
06
+2118
(Store Counter)
07
+1019
(Read Value)
08
+2020
(Load Largest)
09
+3119
(Subtract Value)
10
+4112
(Branch negative to 12)
11
+4001
(Branch 01)
12
+2019
(Load Value)
13
+2120
(Store Largest)
14
+4001
(Branch 01)
15
+1120
(Write Largest)
16
+4300
(Halt)
17
+0000
(Variable EndValue)
18
+0000
(Variable Counter)
19
+0000
(Variable Value)
20
+0000
(Variable Largest)
21
+0001
(Variable Increment)
8 Instead of this absurd division into sexes, they ought to class people as static and dynamic. —Evelyn Waugh
Is it a world to hide virtues in? —William Shakespeare
But what, to serve our private ends, Forbids the cheating of our friends? —Charles Churchill
This above all: to thine own self be true. —William Shakespeare
Don’t be “consistent,” but be simply true. Oliver Wendell Holmes, Jr.
Objectives In this chapter you’ll learn: Encapsulation and data hiding. ■ To use keyword this. ■ To use static variables and methods. ■ To import static members of a class. ■ To use the enum type to create sets of constants with unique identifiers. ■ To declare enum constants with parameters. ■ To organize classes in packages to promote reuse. ■
Classes and Objects: A Deeper Look, Solutions
Self-Review Exercises
2
Self-Review Exercises 8.1
Fill in the blanks in each of the following statements: specia) When compiling a class in a package, the javac command-line option fies where to store the package and causes the compiler to create the package’s directories if they do not exist. ANS: -d. is similar to method System.out.printf, but reb) String class static method turns a formatted String rather than displaying a String in a command window. ANS: format. c) If a method contains a local variable with the same name as one of its class’s fields, the the field in that method’s scope. local variable ANS: shadows. d) The method is called by the garbage collector just before it reclaims an object’s memory. ANS: finalize. declaration specifies one class to import. e) A(n) ANS: single-type-import. . f) If a class declares constructors, the compiler will not create a(n) ANS: default constructor. method is called implicitly when an object appears in code where g) An object’s a String is needed. ANS: toString. or . h) Get methods are commonly called ANS: accessor methods, query methods. method tests whether a condition is true or false. i) A(n) ANS: predicate. that returns an j) For every enum, the compiler generates a static method called array of the enum’s constants in the order in which they were declared. ANS: values. relationship. k) Composition is sometimes referred to as a(n) ANS: has-a. declaration contains a comma-separated list of constants. l) A(n) ANS: enum. variable represents classwide information that is shared by all the objects m) A(n) of the class. ANS: static. declaration imports one static member. n) A(n) ANS: single static import. states that code should be granted only the amount of privilege and access o) The that it needs to accomplish its designated task. ANS: principle of least privilege. specifies that a variable is not modifiable. p) Keyword ANS: final. in a Java source-code file, and it must precede all other q) There can be only one declarations and statements in the file. ANS: package declaration. declaration imports only the classes that the program uses from a particr) A(n) ular package. ANS: type-import-on-demand.
3
Chapter 8
Oliver Wendell Holmes, Jr.
s) The compiler uses a(n) to locate the classes it needs in the classpath. ANS: class loader. option to t) The classpath for the compiler and JVM can be specified with the environment variable. the javac or java command, or by setting the ANS: -classpath, CLASSPATH. because they typically change a value. u) Set methods are commonly called ANS: mutator methods. imports all static members of a class. v) A(n) ANS: static import on demand. or . w) The public methods of a class are also known as the class’s ANS: public services, public interface.
Exercises NOTE: Solutions to the programming exercises are located in the ch08solutions folder. Each exercise has its own folder named ex08_## where ## is a two-digit number representing the exercise number. For example, exercise 8.4’s solution is located in the folder ex08_04. 8.2
Explain the notion of package access in Java. Explain the negative aspects of package access. ANS: Package access allows a class, method, or variable to be accessible within the same package. Package access does not promote good OOP when applied to an instance variable because it destroys the notion of information hiding.
8.3
What happens when a return type, even void, is specified for a constructor? ANS: It is treated as a method and is not considered to be a constructor.
Object-Oriented Programming: Inheritance, Solutions
9 Say not you know another entirely, till you have divided an inheritance with him. —Johann Kasper Lavater
This method is to define as the number of a class the class of all classes similar to the given class. —Bertrand Russell
Objectives In this chapter you’ll learn: How inheritance promotes software reusability. ■ The notions of superclasses and subclasses and the relationship between them. ■ To use keyword extends to create a class that inherits attributes and behaviors from another class. ■ To use access modifier protected to give subclass methods access to superclass members. ■ To access superclass members with super. ■ How constructors are used in inheritance hierarchies. ■ The methods of class Object, the direct or indirect superclass of all classes. ■
Self-Review Exercises
2
Self-Review Exercises 9.1
Fill in the blanks in each of the following statements: is a form of software reusability in which new classes acquire the members a) of existing classes and embellish those classes with new capabilities. ANS: Inheritance. members can be accessed in the superclass declaration and b) A superclass’s in subclass declarations. ANS: public and protected. relationship, an object of a subclass can also be treated as an object c) In a(n) of its superclass. ANS: is-a or inheritance. relationship, a class object has references to objects of other classes d) In a(n) as members. ANS: has-a or composition. relationship with its subclasses. e) In single inheritance, a class exists in a(n) ANS: hierarchical. members are accessible anywhere that the program has a reff) A superclass’s erence to an object of that superclass or to an object of one of its subclasses. ANS: public. is called implicitly g) When an object of a subclass is instantiated, a superclass or explicitly. ANS: constructor. keyword. h) Subclass constructors can call superclass constructors via the ANS: super.
9.2
State whether each of the following is true or false. If a statement is false, explain why. a) Superclass constructors are not inherited by subclasses. ANS: True. b) A has-a relationship is implemented via inheritance. ANS: False. A has-a relationship is implemented via composition. An is-a relationship is implemented via inheritance. c) A Car class has an is-a relationship with the SteeringWheel and Brakes classes. ANS: False. This is an example of a has-a relationship. Class Car has an is-a relationship with class Vehicle. d) When a subclass redefines a superclass method by using the same signature, the subclass is said to overload that superclass method. ANS: False. This is known as overriding, not overloading—an overloaded method has the same name, but a different signature.
Exercises NOTE: Solutions to the programming exercises are located in the ch09solutions folder. Each exercise has its own folder named ex09_## where ## is a two-digit number representing the exercise number. For example, exercise 9.3’s solution is located in the folder ex09_03.
3
Chapter 9
Object-Oriented Programming: Inheritance, Solutions
9.4 Discuss the ways in which inheritance promotes software reuse, saves time during program development and helps prevent errors. ANS: Inheritance allows developers to create subclasses that reuse code declared already in a superclass. Avoiding the duplication of common functionality between several classes by building a class inheritance hierarchy can save developers a considerable amount of time. Similarly, placing common functionality in a single superclass, rather than duplicating the code in multiple unrelated classes, helps prevent the same errors from appearing in multiple source-code files. If errors occur in the common functionality of the superclass, the software developer needs to modify only the superclass’s. 9.5 Draw an inheritance hierarchy for students at a university similar to the hierarchy shown in Fig. 9.2. Use Student as the superclass of the hierarchy, then extend Student with classes UndergraduateStudent and GraduateStudent. Continue to extend the hierarchy as deep (i.e., as many levels) as possible. For example, Freshman, Sophomore, Junior and Senior might extend UndergraduateStudent, and DoctoralStudent and MastersStudent might be subclasses of GraduateStudent. After drawing the hierarchy, discuss the relationships that exist between the classes. [Note: You do not need to write any code for this exercise.] ANS:
Student
UndergraduateStudent
Freshman
Sophomore
GraduateStudent
Senior
DoctoralStudent
MastersStudent
Junior
This hierarchy contains many is-a (inheritance) relationships. An UndergraduateStudent is a Student. A GraduateStudent is a Student, too. Each of the classes Freshman, Sophomore, Junior
and Senior is an UndergraduateStudent and is a Student. Each of the classes DoctoralStudent and MastersStudent is a GraduateStudent and is a Student. Note that there could be many more classes. For example, GraduateStudent could have subclasses like LawStudent, BusinessStudent, MedicalStudent, etc.
Exercises
4
9.6 The world of shapes is much richer than the shapes included in the inheritance hierarchy of Fig. 9.3. Write down all the shapes you can think of—both two-dimensional and three-dimensional—and form them into a more complete Shape hierarchy with as many levels as possible. Your hierarchy should have class Shape at the top. Classes TwoDimensionalShape and ThreeDimensionalShape should extend Shape. Add additional subclasses, such as Quadrilateral and Sphere, at their correct locations in the hierarchy as necessary. ANS: [Note: Solutions may vary.]
Shape
TwoDimensionalShape
Quadrilateral
Ellipse
Trapezoid
Circle
Triangle
Sphere
Cone
Dodecahedron
Parallelogram
Rhombus
ThreeDimensionalShape
Cube
Cylinder
Prism
Tetrahedron
Rectangle
Square
9.7 Some programmers prefer not to use protected access, because they believe it breaks the encapsulation of the superclass. Discuss the relative merits of using protected access vs. using private access in superclasses. ANS: private instance variables are hidden in the subclass and are accessible only through the public or protected methods of the superclass. Using protected access enables the subclass to manipulate the protected members without using the access methods of the superclass. This makes the code more brittle, because changes to the superclass might require changes to the subclasses. If the superclass instance variables are private, the methods of the superclass must be used to access the data. This encapsulation makes the code easier to maintain, modify and debug.
Object-Oriented Programming: Polymorphism, Solutions
10 One Ring to rule them all, One Ring to find them, One Ring to bring them all and in the darkness bind them. —John Ronald Reuel Tolkien
General propositions do not decide concrete cases. —Oliver Wendell Holmes
A philosopher of imposing stature doesn’t think in a vacuum. Even his most abstract ideas are, to some extent, conditioned by what is or is not known in the time when he lives. —Alfred North Whitehead
Why art thou cast down, O my soul? —Psalms 42:5
Objectives In this chapter you’ll learn: The concept of polymorphism. ■ To use overridden methods to effect polymorphism. ■ To distinguish between abstract and concrete classes. ■ To declare abstract methods to create abstract classes. ■ How polymorphism makes systems extensible and maintainable. ■ To determine an object’s type at execution time. ■ To declare and implement interfaces. ■
Self-Review Exercises
2
Self-Review Exercises 10.1
Fill in the blanks in each of the following statements: class. a) If a class contains at least one abstract method, it’s a(n) ANS: abstract. classes. b) Classes from which objects can be instantiated are called ANS: concrete. involves using a superclass variable to invoke methods on superclass and subc) class objects, enabling you to “program in the general.” ANS: Polymorphism. d) Methods that are not interface methods and that do not provide implementations must . be declared using keyword ANS: abstract. e) Casting a reference stored in a superclass variable to a subclass type is called . ANS: downcasting.
10.2
State whether each of the statements that follows is true or false. If false, explain why. a) All methods in an abstract class must be declared as abstract methods. ANS: False. An abstract class can include methods with implementations and abstract methods. b) Invoking a subclass-only method through a subclass variable is not allowed. ANS: False. Trying to invoke a subclass-only method with a superclass variable is no allowed. c) If a superclass declares an abstract method, a subclass must implement that method. ANS: False. Only a concrete subclass must implement the method. d) An object of a class that implements an interface may be thought of as an object of that interface type. ANS: True.
Exercises NOTE: Solutions to the programming exercises are located in the ch10solutions folder. Each exercise has its own folder named ex10_## where ## is a two-digit number representing the exercise number. For example, exercise 10.8’s solution is located in the folder ex10_08. 10.3 How does polymorphism enable you to program “in the general” rather than “in the specific”? Discuss the key advantages of programming “in the general.” ANS: Polymorphism enables you to concentrate on the common operations that are applied to objects of all the classes in a hierarchy. The general processing capabilities can be separated from any code that is specific to each class. Those general portions of the code can accommodate new classes without modification. In some polymorphic applications, only the code that creates the objects needs to be modified to extend the system with new classes. 10.4 What are abstract methods? Describe the circumstances in which an abstract method would be appropriate. ANS: An abstract method is one with keyword abstract in its declaration. Abstract methods do not provide implementations. Each concrete subclass of an abstract superclass must provide concrete implementations of the superclass’s abstract methods. An abstract method is appropriate when it does not make sense to provide an implementation for a method in a superclass (i.e., some additional subclass-specific data is required to implement the method in a meaningful manner).
3
Chapter 10
Object-Oriented Programming: Polymorphism, Solutions
10.5
How does polymorphism promote extensibility? ANS: Software that invokes polymorphic behavior is independent of the object types to which messages are sent as long as those types are in the same inheritance hierarchy. New object types that can respond to existing method calls can be incorporated into a system without requiring modification of the base system, except that client code that instantiates new objects must be modified to accommodate new types.
10.6 Discuss four ways in which you can assign superclass and subclass references to variables of superclass and subclass types. ANS: 1) Assigning a superclass reference to a superclass variable. 2) Assigning a subclass reference to a subclass variable. 3) Assigning a subclass object’s reference to a superclass variable is safe, because the subclass object is an object of its superclass. However, this reference can be used to refer only to superclass members. If this code refers to subclass-only members through the superclass variable, the compiler reports errors. 4) Attempting to assign a superclass object’s reference to a subclass variable is a compilation error. To avoid this error, the superclass reference must be downcast to a subclass type explicitly. At execution time, if the object to which the reference refers is not a subclass object, an exception will occur. The instanceof operator can be used to ensure that such a cast is performed only if the object is a subclass object. 10.7 Compare and contrast abstract classes and interfaces. Why would you use an abstract class? Why would you use an interface? ANS: An abstract class describes the general notion of what it means to be an object of that class. Abstract classes are incomplete—they normally contain data and one or more methods that are declared abstract because the methods cannot be implemented in a general sense. Abstract classes can contain implemented methods. Objects of an abstract class cannot be instantiated. Subclasses must declare the “missing pieces”—implementations of the abstract methods that are appropriate for each specific subclass. Abstract class references can refer to objects of any of the classes below the abstract class in an inheritance hierarchy and therefore can be used to process any such objects polymorphically. An interface also describes abstract functionality that can be implemented by objects of any number of classes. Classes that implement an interface can be unrelated, whereas concrete subclasses of the same abstract superclass are all related to one other by way of a shared superclass. An interface is often used when disparate (i.e., unrelated) classes need to provide common functionality (i.e., methods) or use common constants. An interface can also be used in place of an abstract class when there are no default implementation details (i.e., method implementations and instance variables) to inherit. When a class implements an interface, it establishes an isa relationship with the interface type, just as a subclass participates in an is-a relationship with its superclass. Therefore, interface references can be used to evoke polymorphic behavior, just as an abstract superclass reference can.
11
Exception Handling: Solutions
It is common sense to take a method and try it. If it fails, admit it frankly and try another. But above all, try something. —Franklin Delano Roosevelt
O! throw away the worser part of it, And live the purer with the other half. —William Shakespeare
If they’re running and they don’t look where they’re going I have to come out from somewhere and catch them. —Jerome David Salinger
Objectives In this chapter you’ll learn: What exceptions are and how they’re handled. ■ When to use exception handling. ■ To use try blocks to delimit code in which exceptions might occur. ■ To throw exceptions to indicate a problem. ■ To use catch blocks to specify exception handlers. ■ To use the finally block to release resources. ■ The exception class hierarchy. ■ To create user-defined exceptions. ■
..
2
Chapter 11
Exception Handling: Solutions
Self-Review Exercises 11.1
List five common examples of exceptions. ANS: Memory exhaustion, array index out of bounds, arithmetic overflow, division by zero, invalid method parameters.
11.2 Give several reasons why exception-handling techniques should not be used for conventional program control. ANS: (a) Exception handling is designed to handle infrequently occurring situations that often result in program termination, not situations that arise all the time. (b) Flow of control with conventional control structures is generally clearer and more efficient than with exceptions. (c) The additional exceptions can get in the way of genuine error-type exceptions. It becomes more difficult for you to keep track of the larger number of exception cases. 11.3 Why are exceptions particularly appropriate for dealing with errors produced by methods of classes in the Java API? ANS: It’s unlikely that methods of classes in the Java API could perform error processing that would meet the unique needs of all users. 11.4
What is a “resource leak”? ANS: A “resource leak” occurs when an executing program does not properly release a resource when it’s no longer needed.
11.5 If no exceptions are thrown in a try block, where does control proceed to when the try block completes execution? ANS: The catch blocks for that try statement are skipped, and the program resumes execution after the last catch block. If there is a finally block, it’s executed first; then the program resumes execution after the finally block. 11.6
Give a key advantage of using catch( Exception exceptionName ). ANS: The form catch( Exception exceptionName ) catches any type of exception thrown in a try block. An advantage is that no thrown Exception can slip by without being caught. You can then decide to handle the exception or possibly rethrow it.
11.7
Should a conventional application catch Error objects? Explain. ANS: Errors are usually serious problems with the underlying Java system; most programs will not want to catch Errors because they will not be able to recover from them.
11.8
What happens if no catch handler matches the type of a thrown object? ANS: This causes the search for a match to continue in the next enclosing try statement. If there is a finally block, it will be executed before the exception goes to the next enclosing try statement. If there are no enclosing try statements for which there are matching catch blocks and the exceptions are declared (or unchecked), a stack trace is printed and the current thread terminates early. If the exceptions are checked, but not caught or declared, compilation errors occur.
11.9
What happens if several catch blocks match the type of the thrown object? ANS: The first matching catch block after the try block is executed.
11.10 Why would a programmer specify a superclass type as the type in a catch block? ANS: This enables a program to catch related types of exceptions and process them in a uniform manner. However, it’s often useful to process the subclass types individually for more precise exception handling.
..
Exercises
3
11.11 What is the key reason for using finally blocks? ANS: The finally block is the preferred means for releasing resources to prevent resource leaks. 11.12 What happens when a catch block throws an Exception? ANS: First, control passes to the finally block if there is one. Then the exception will be processed by a catch block (if one exists) associated with an enclosing try block (if one exists). 11.13 What does the statement throw exceptionReference do in a catch block? ANS: It rethrows the exception for processing by an exception handler of an enclosing try statement, after the finally block of the current try statement executes. 11.14 What happens to a local reference in a try block when that block throws an Exception? ANS: The reference goes out of scope. If the referenced object becomes unreachable, the object can be garbage collected.
Exercises NOTE: Solutions to the programming exercises are located in the ch11solutions folder. Each exercise has its own folder named ex11_## where ## is a two-digit number representing the exercise number. For example, exercise 11.17’s solution is located in the folder ex11_17. 11.15 (Exceptional Conditions) List the various exceptional conditions that have occurred in programs throughout this text so far. List as many additional exceptional conditions as you can. For each of these, describe briefly how a program typically would handle the exception by using the exception-handling techniques discussed in this chapter. Typical exceptions include division by zero and array index out of bounds. ANS: A few examples are: Division by zero—catch the exception, inform user of the attempt to divide by zero. Array subscript out of bounds—catch the exception, print an error message telling the user what index was being referenced incorrectly, and exit the program in a controlled manner. Bad cast—catch the exception and either cast it to the proper type if that can be determined, or print an error message indicating what the bad cast was, and exit the program. Invalid input—catch the exception and inform the user that the input cannot be converted to the proper type. 11.16 (Exceptions and Constructor Failure) Until this chapter, we’ve found dealing with errors detected by constructors to be a bit awkward. Explain why exception handling is an effective means for dealing with constructor failure. ANS: A thrown exception passes to the outside world the information about the failed constructor and the responsibility to deal with the failure. Exceptions thrown in constructors cause objects built as part of the object being constructed to be marked for eventual garbage collection.
..
14
GUI Components: Part 1, Solutions
Do you think I can listen all day to such stuff? —Lewis Carroll
Even a minor event in the life of a child is an event of that child’s world and thus a world event. —Gaston Bachelard
You pays your money and you takes your choice. —Punch
Objectives In this chapter you’ll learn: ■
Design principles of graphical user interfaces (GUIs).
■
How to use Java’s elegant, cross-platform Nimbus lookand-feel.
■
To build GUIs and handle events generated by user interactions with GUIs.
■
To understand the packages containing GUI components, event-handling classes and interfaces.
■
To create and manipulate buttons, labels, lists, text fields and panels.
■
To handle mouse events and keyboard events.
■
To use layout managers to arrange GUI components
2
Chapter 14
GUI Components: Part 1, Solutions
Self-Review Exercises 14.1
Fill in the blanks in each of the following statements: is called when the mouse is moved with no buttons pressed and an a) Method event listener is registered to handle the event. ANS: mouseMoved. text. b) Text that cannot be modified by the user is called ANS: uneditable (read-only). arranges GUI components in a Container. c) A(n) ANS: layout manager. . d) The add method for attaching GUI components is a method of class ANS: Container. . e) GUI is an acronym for ANS: graphical user interface. is used to specify the layout manager for a container. f) Method ANS: setLayout. method call and followed by g) A mouseDragged method call is preceded by a(n) method call. a(n) ANS: mousePressed, mouseReleased. contains methods that display message dialogs and input dialogs. h) Class ANS: JOptionPane. i) An input dialog capable of receiving input from the user is displayed with method of class . ANS: showInputDialog, JOptionPane. of j) A dialog capable of displaying a message to the user is displayed with method . class ANS: showMessageDialog, JOptionPane. . k) Both JTextFields and JTextAreas directly extend class ANS: JTextComponent.
14.2
Determine whether each statement is true or false. If false, explain why. a) BorderLayout is the default layout manager for a JFrame’s content pane. ANS: True. b) When the mouse cursor is moved into the bounds of a GUI component, method mouseOver is called. ANS: False. Method mouseEntered is called. c) A JPanel cannot be added to another JPanel. ANS: False. A JPanel can be added to another JPanel, because JPanel is an indirect subclass of Component. So, a JPanel is a Component. Any Component can be added to a Container. d) In a BorderLayout, two buttons added to the NORTH region will be placed side by side. ANS: False. Only the last button added will be displayed. Remember that only one component should be added to each region in a BorderLayout. e) A maximum of five components can be added to a BorderLayout. ANS: True. [Note: Panels containing multiple components can be added to each region.] f) Inner classes are not allowed to access the members of the enclosing class. ANS: False. Inner classes have access to all members of the enclosing class declaration. g) A JTextArea’s text is always read-only. ANS: False. JTextAreas are editable by default. h) Class JTextArea is a direct subclass of class Component. ANS: False. JTextArea derives from class JTextComponent.
Exercises 14.3
3
Find the error(s) in each of the following statements, and explain how to correct it (them): a) buttonName = JButton( "Caption" ); ANS: new is needed to create an object. // create references b) JLabel aLabel, JLabel; ANS: JLabel is a class name and cannot be used as a variable name. c) txtField = new JTextField( 50, "Default Text" ); ANS: The arguments passed to the constructor are reversed. The String must be passed first. d) setLayout( new BorderLayout() ); button1 = new JButton( "North Star" ); button2 = new JButton( "South Pole" ); add( button1 ); add( button2 );
ANS: BorderLayout has been set, and components are being added without specifying the
region, so both are added to the center region. Proper add statements might be add( button1, BorderLayout.NORTH ); add( button2, BorderLayout.SOUTH );
Exercises NOTE: Solutions to the programming exercises are located in the ch14solutions folder. Each exercise has its own folder named ex14_## where ## is a two-digit number representing the exercise number. For example, exercise 14.12’s solution is located in the folder ex14_12. At the end of this PDF we list compilation issues for exercise code compiled with Java SE 7. 14.4
Fill in the blanks in each of the following statements: . a) The JTextField class directly extends class ANS: JTextComponent. attaches a GUI component to a container. b) Container method ANS: add. is called when a mouse button is released (without moving the c) Method mouse). ANS: mouseClicked. class is used to create a group of JRadioButtons. d) The ANS: ButtonGroup.
14.5
Determine whether each statement is true or false. If false, explain why. a) Only one layout manager can be used per Container. ANS: True. b) GUI components can be added to a Container in any order in a BorderLayout. ANS: True. c) JRadioButtons provide a series of mutually exclusive options (i.e., only one can be true at a time). ANS: True. d) Graphics method setFont is used to set the font for text fields. ANS: False. Component method setFont is used. e) A JList displays a scrollbar if there are more items in the list than can be displayed. ANS: False. A JList never provides a scrollbar. f) A Mouse object has a method called mouseDragged. ANS: False. A Mouse object is not provided by Java.
4
Chapter 14
GUI Components: Part 1, Solutions
14.6
Determine whether each statement is true or false. If false, explain why. a) A JPanel is a JComponent. ANS: True. b) A JPanel is a Component. ANS: True. c) A JLabel is a Container. ANS: True. d) A JList is a JPanel. ANS: False. A JList is a JComponent. e) An AbstractButton is a JButton. ANS: False. A JButton is an AbstractButton. f) A JTextField is an Object. ANS: True. g) ButtonGroup is a subclass of JComponent. ANS: False. ButtonGroup inherits from Object.
14.7
Find any errors in each of the following lines of code, and explain how to correct them. a) import javax.swing.JFrame ANS: Semicolon is missing after the class name. b) panelObject.GridLayout( 8, 8 ); // set GridLayout ANS: The GridLayout constructor cannot be used in this manner. The correct statement should be: panelObject.getContentPane().setLayout( new GridLayout( 8, 8 ) );
c)
container.setLayout( new FlowLayout( FlowLayout.DEFAULT ) );
ANS: Class FlowLayout does not contain static constant DEFAULT.
d) container.add( eastButton, EAST );
// BorderLayout
ANS: EAST should be BorderLayout.EAST.
Java SE 7 Compilation Issues 14.15 This exercise compiles with warnings, because, as of Java SE 7, JList is a generic class. For the 10th edition, we’ll update this solution to use the new version of JList.
15 One picture is worth ten thousand words. —Chinese proverb
Treat nature in terms of the cylinder, the sphere, the cone, all in perspective. —Paul Cézanne
Colors, like features, follow the changes of the emotions. —Pablo Picasso
Nothing ever becomes real till it is experienced—even a proverb is no proverb to you till your life has illustrated it. —John Keats
Objectives In this chapter you’ll learn: To understand graphics contexts and graphics objects. ■ To manipulate colors and fonts. ■ To use methods of class Graphics to draw various shapes. ■ To use methods of class Graphics2D from the Java 2D API to draw various shapes. ■ To specify Paint and Stroke characteristics of shapes displayed with Graphics2D. ■
Graphics and Java 2D™: Solutions
Self-Review Exercises
2
Self-Review Exercises 15.1
Fill in the blanks in each of the following statements: of class sets the characteristics of a line used to a) In Java 2D, method draw a shape. ANS: setStroke, Graphics2D. helps specify the fill for a shape such that the fill gradually changes from b) Class one color to another. ANS: GradientPaint. method of class Graphics draws a line between two points. c) The ANS: drawLine. , and . d) RGB is short for ANS: red, green, blue. e) Font sizes are measured in units called . ANS: points. helps specify the fill for a shape using a pattern drawn in a Bufferedf) Class Image. ANS: TexturePaint.
15.2
State whether each of the following is true or false. If false, explain why. a) The first two arguments of Graphics method drawOval specify the center coordinate of the oval. ANS: False. The first two arguments specify the upper-left corner of the bounding rectangle. b) In the Java coordinate system, x-coordinates increase from left to right and y-coordinates from top to bottom. ANS: True. c) Graphics method fillPolygon draws a filled polygon in the current color. ANS: True. d) Graphics method drawArc allows negative angles. ANS: True. e) Graphics method getSize returns the size of the current font in centimeters. ANS: False. Font sizes are measured in points. f) Pixel coordinate (0, 0) is located at the exact center of the monitor. ANS: False. The coordinate (0,0) corresponds to the upper-left corner of a GUI component on which drawing occurs.
15.3 Find the error(s) in each of the following and explain how to correct them. Assume that g is a Graphics object. a) g.setFont( "SansSerif" ); ANS: The setFont method takes a Font object as an argument—not a String. // clear rectangle at (x, y) b) g.erase( x, y, w, h ); ANS: The Graphics class does not have an erase method. The clearRect method should be used. c) Font f = new Font( "Serif", Font.BOLDITALIC, 12 ); ANS: Font.BOLDITALIC is not a valid font style. To get a bold italic font, use Font.BOLD + Font.ITALIC. d) g.setColor( 255, 255, 0 ); // change color to yellow ANS: Method setColor takes a Color object as an argument, not three integers.
3
Chapter 15
Graphics and Java 2D™: Solutions
Exercises NOTE: Solutions to the programming exercises are located in the ch15solutions folder. Each exercise has its own folder named ex15_## where ## is a two-digit number representing the exercise number. For example, exercise 15.17’s solution is located in the folder ex15_17. 15.4
15.5
Fill in the blanks in each of the following statements: of the Java 2D API is used to draw ovals. a) Class ANS: Ellipse2D. b) Methods draw and fill of class Graphics2D require an object of type argument. ANS: Shape. c) The three constants that specify font style are , and ANS: Font.PLAIN, Font.BOLD and Font.ITALIC. sets the painting color for Java 2D shapes. d) Graphics2D method ANS: setColor.
as their .
State whether each of the following is true or false. If false, explain why. a) Graphics method drawPolygon automatically connects the endpoints of the polygon. ANS: True. b) Graphics method drawLine draws a line between two points. ANS: True. c) Graphics method fillArc uses degrees to specify the angle. ANS: True. d) In the Java coordinate system, values on the y-axis increase from left to right. ANS: False. In the Java coordinate system, values on the y-axis increase from top to bottom. e) Graphics inherits directly from class Object. ANS: True. f) Graphics is an abstract class. ANS: True. g) The Font class inherits directly from class Graphics. ANS: False. Class Font inherits directly from class Object.
Strings, Characters and Regular Expressions: Solutions
16 The chief defect of Henry King Was chewing little bits of string. —Hilaire Belloc
Vigorous writing is concise. A sentence should contain no unnecessary words, a paragraph no unnecessary sentences. —William Strunk, Jr.
I have made this letter longer than usual, because I lack the time to make it short. —Blaise Pascal
Objectives In this chapter you’ll learn: ■
To create and manipulate immutable character-string objects of class String.
■
To create and manipulate mutable character-string objects of class StringBuilder.
■
To create and manipulate objects of class Character.
■
To break a String object into tokens using String method split.
■
To use regular expressions to validate String data entered into an application.
Self-Review Exercises
2
Self-Review Exercises 16.1
State whether each of the following is true or false. If false, explain why. a) When String objects are compared using ==, the result is true if the Strings contain the same values. ANS: False. String objects are compared using operator == to determine whether they are the same object in memory. b) A String can be modified after it’s created. ANS: False. String objects are immutable and cannot be modified after they are created. StringBuilder objects can be modified after they are created.
16.2
For each of the following, write a single statement that performs the indicated task: a) Compare the string in s1 to the string in s2 for equality of contents. ANS: s1.equals( s2 )
b) Append the string s2 to the string s1, using +=. ANS: s1 += s2;
c) Determine the length of the string in s1. ANS: s1.length()
Exercises NOTE: Solutions to the programming exercises are located in the ch16solutions folder. Each exercise has its own folder named ex16_## where ## is a two-digit number representing the exercise number. For example, exercise 16.17’s solution is located in the folder ex16_17.
17 I can only assume that a “Do Not File” document is filed in a “Do Not File” file. —Senator Frank Church Senate Intelligence Subcommittee Hearing, 1975
Consciousness … does not appear to itself chopped up in bits. … A “river” or a “stream” are the metaphors by which it is most naturally described. —William James
Objectives In this chapter you’ll learn: To create, read, write and update files. ■ To retrieve information about files and directories. ■ The Java input/output stream class hierarchy. ■ The differences between text files and binary files. ■ To use classes Scanner and Formatter to process text files. ■ To use classes FileInputStream and FileOutputStream to read from and write to files. ■ To use classes ObjectInputStream and ObjectOutputStream to read objects from and write objects to files. ■ To use a JFileChooser dialog. ■
Files, Streams and Object Serialization: Solutions
Self-Review Exercises
2
Self-Review Exercises 17.1
Determine whether each of the following statements is true or false. If false, explain why. a) You must explicitly create the stream objects System.in, System.out and System.err. ANS: False. These three streams are created for you when a Java application begins executing. b) When reading data from a file using class Scanner, if you wish to read data in the file multiple times, the file must be closed and reopened to read from the beginning of the file. ANS: True. c) Method exists of class File returns true if the name specified as the argument to the File constructor is a file or directory in the specified path. ANS: True. d) Binary files are human readable in a text editor. ANS: False. Text files are human readable in a text editor. Binary files might be human readable, but only if the bytes in the file represent ASCII characters. e) An absolute path contains all the directories, starting with the root directory, that lead to a specific file or directory. ANS: True. f) Class Formatter contains method printf, which enables formatted data to be output to the screen or to a file. ANS: False. Class Formatter contains method format, which enables formatted data to be output to the screen or to a file.
17.2
Complete the following tasks, assuming that each applies to the same program: a) Write a statement that opens file "oldmast.txt" for input—use Scanner variable inOldMaster. ANS: Scanner inOldMaster = new Scanner( new File( "oldmast.txt" ) );
b) Write a statement that opens file "trans.txt" for input—use Scanner variable inTransaction. ANS: Scanner inTransaction = new Scanner( new File( "trans.txt" ) );
c) Write a statement that opens file "newmast.txt" for output (and creation)—use formatter variable outNewMaster. ANS: Formatter outNewMaster = new Formatter( "newmast.txt" );
d) Write the statements needed to read a record from the file "oldmast.txt". Use the data to create an object of class AccountRecord—use Scanner variable inOldMaster. Assume that class AccountRecord is the same as the AccountRecord class in Fig. 17.5. ANS: AccountRecord account = new AccountRecord(); account.setAccount( inOldMaster.nextInt() ); account.setFirstName( inOldMaster.next() ); account.setLastName( inOldMaster.next() ); account.setBalance( inOldMaster.nextDouble() );
e) Write the statements needed to read a record from the file "trans.txt". The record is an object of class TransactionRecord—use Scanner variable inTransaction. Assume that class TransactionRecord contains method setAccount (which takes an int) to set the account number and method setAmount (which takes a double) to set the amount of the transaction. ANS: TransactionRecord transaction = new Transaction(); transaction.setAccount( inTransaction.nextInt() ); transaction.setAmount( inTransaction.nextDouble() );
3
Chapter 17
Files, Streams and Object Serialization: Solutions
f) Write a statement that outputs a record to the file "newmast.txt". The record is an object of type AccountRecord—use Formatter variable outNewMaster. ANS: outNewMaster.format( "%d %s %s %.2f\n", account.getAccount(), account.getFirstName(), account.getLastName(), account.getBalance() );
17.3
Complete the following tasks, assuming that each applies to the same program: a) Write a statement that opens file "oldmast.ser" for input—use ObjectInputStream variable inOldMaster to wrap a FileInputStream object. ANS: ObjectInputStream inOldMaster = new ObjectInputStream( new FileInputStream( "oldmast.ser" ) );
b) Write a statement that opens file "trans.ser" for input—use ObjectInputStream variable inTransaction to wrap a FileInputStream object. ANS: ObjectInputStream inTransaction = new ObjectInputStream( new FileInputStream( "trans.ser" ) );
c) Write a statement that opens file "newmast.ser" for output (and creation)—use ObjectOutputStream variable outNewMaster to wrap a FileOutputStream. ANS: ObjectOutputStream outNewMaster = new ObjectOutputStream( new FileOutputStream( "newmast.ser" ) );
d) Write a statement that reads a record from the file "oldmast.ser". The record is an object of class AccountRecordSerializable—use ObjectInputStream variable inOldMaster. Assume class AccountRecordSerializable is the same as the AccountRecordSerializable class in Fig. 17.16. ANS: accountRecord = ( AccountRecordSerializable ) inOldMaster.readObject();
e) Write a statement that reads a record from the file "trans.ser". The record is an object of class TransactionRecord—use ObjectInputStream variable inTransaction. ANS: transactionRecord = ( TransactionRecord ) inTransaction.readObject();
f) Write a statement that outputs a record of type AccountRecordSerializable to the file "newmast.ser"—use ObjectOutputStream variable outNewMaster. ANS: outNewMaster.writeObject( newAccountRecord );
17.4
Find the error in each block of code and show how to correct it. a) Assume that account, company and amount are declared. ObjectOutputStream outputStream; outputStream.writeInt( account ); outputStream.writeChars( company ); outputStream.writeDouble( amount );
ANS: Error: The file was not opened before the attempt to output data to the stream.
Correction: Open a file for output by creating a new ObjectOutputStream object that wraps a FileOutputStream object. b) The following statements should read a record from the file "payables.txt". The Scanner variable inPayable should be used to refer to this file. Scanner inPayable = new Scanner( new File( "payables.txt" ) ); PayablesRecord record = ( PayablesRecord ) inPayable.readObject();
ANS: Error: This example uses text files with a Scanner; there is no object serialization. As
a result, method readObject cannot be used to read that data from the file. Each piece of data must be read separately, then used to create a PayablesRecord object. Correction: Use methods of inPayable to read each piece of the PayablesRecord object.
Exercises
4
Exercises NOTE: Solutions to the programming exercises are located in the ch17solutions folder. Each exercise has its own folder named ex17_## where ## is a two-digit number representing the exercise number. For example, exercise 17.5’s solution is located in the folder ex17_05.
18
Recursion: Solutions
We must learn to explore all the options and possibilities that confront us in a complex and rapidly changing world. —James William Fulbright
O! thou hast damnable iteration, and art indeed able to corrupt a saint. —William Shakespeare
It's a poor sort of memory that only works backwards. —Lewis Carroll
Life can only be understood backwards; but it must be lived forwards. —Soren Kierkegaard
Objectives In this chapter you’ll learn: The concept of recursion. ■ How to write and use recursive methods. ■ How to determine the base case and recursion step in a recursive algorithm. ■ How recursive method calls are handled by the system. ■ The differences between recursion and iteration, and when to use each. ■ What the geometric shapes called fractals are and how to draw them using recursion. ■ What recursive backtracking is and why it’s an effective problem-solving technique. ■
2
Chapter 18
Recursion: Solutions
Self-Review Exercises 18.1
State whether each of the following is true or false. If false, explain why. a) A method that calls itself indirectly is not an example of recursion. ANS: False. A method that calls itself in this manner is an example of indirect recursion. b) Recursion can be efficient in computation because of reduced memory-space usage. ANS: False. Recursion can be inefficient in computation because of multiple method calls and memory-space usage. c) When a recursive method is called to solve a problem, it actually is capable of solving only the simplest case(s), or base case(s). ANS: True. d) To make recursion feasible, the recursion step in a recursive solution must resemble the original problem, but be a slightly larger version of it. ANS: False. To make recursion feasible, the recursion step in a recursive solution must resemble the original problem, but be a slightly smaller version of it.
18.2
is needed to terminate recursion. A a) recursion step b) break statement c) void return type d) base case ANS: d) base case
18.3
The first call to invoke a recursive method is a) not recursive b) recursive c) the recursion step d) none of the above ANS: a) not recursive
18.4
Each time a fractal’s pattern is applied, the fractal is said to be at a new a) width b) height c) level d) volume ANS: c) level
18.5
Iteration and recursion each involve a a) repetition statement b) termination test c) counter variable d) none of the above ANS: b) termination test
18.6
Fill in the blanks in each of the following statements: a) The ratio of successive Fibonacci numbers converges on a constant value of 1.618…, a or the . number that has been called the ANS: golden ratio, golden mean. b) Iteration normally uses a repetition statement, whereas recursion normally uses a(n) statement. ANS: selection. property—when subdivided into parts, each is a reducedc) Fractals have a(n) size copy of the whole. ANS: self-similar.
.
.
.
Exercises
3
Exercises NOTE: Solutions to the programming exercises are located in the ch18solutions folder. Each exercise has its own folder named ex18_## where ## is a two-digit number representing the exercise number. For example, exercise 18.17’s solution is located in the folder ex18_17. 18.7 1 2 3 4 5 6 7
What does the following code do?
public int mystery( int a, int b ) { if ( b == 1 ) return a; else return a + mystery( a, b - 1 ); } // end method mystery
ANS: The method adds a to itself b times, which in essence multiplies the values a and b,
recursively. 18.8 Find the error(s) in the following recursive method, and explain how to correct it (them). This method should find the sum of the values from 0 to n. 1 2 3 4 5 6 7
public int sum( int n ) { if ( n == 0 ) return 0; else return n + sum( n ); } // end method sum
ANS: The code above will result in infinite recursion, unless the value initially passed to the method is 0 (the base case). There is no code to make the recursive call on line 6 sim-
pler than the previous call. The call on line 6 should decrease n by 1.
4
Chapter 18
Recursion: Solutions
18.12 What does the following program do? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Exercise 18.12 Solution: MysteryClass.java public class MysteryClass { public static int mystery( int[] array2, int size ) { if ( size == 1 ) return array2[ 0 ]; else return array2[ size - 1 ] + mystery( array2, size - 1 ); } // end method mystery public static void main( String[] args ) { int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int result = mystery( array, array.length ); System.out.printf( "Result is: %d\n", result ); } // end method main } // end class MysteryClass
ANS: This code totals the values in an array.
18.13 What does the following program do? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Exercise 18.13 Solution: SomeClass.java public class SomeClass { public static String someMethod( int[] array2, int x ) { if ( x < array2.length ) return String.format( "%s%d ", someMethod( array2, x + 1 ), array2[ x ] ); else return ""; } // end method someMethod public static void main( String[] args ) { int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; String results = someMethod( array, 0 ); System.out.println( results ); } // end main } // end class SomeClass
ANS: This code displays the values in an array backwards.
19 With sobs and tears he sorted out Those of the largest size … —Lewis Carroll
Attempt the end, and never stand to doubt; Nothing’s so hard, but search will find it out. —Robert Herrick
’Tis in my memory lock’d, And you yourself shall keep the key of it. —William Shakespeare
It is an immutable law in business that words are words, explanations are explanations, promises are promises — but only performance is reality. —Harold S. Green
Objectives In this chapter you’ll learn: ■
To search for a given value in an array using linear search and binary search.
■
To sort arrays using the iterative selection and insertion sort algorithms.
■
To sort arrays using the recursive merge sort algorithm.
■
To determine the efficiency of searching and sorting algorithms.
Searching, Sorting and Big O: Solutions
Self-Review Exercises
2
Self-Review Exercises 19.1
Fill in the blanks in each of the following statements: times as long to run a) A selection sort application would take approximately on a 128-element array as on a 32-element array. ANS: 16, because an O(n2) algorithm takes 16 times as long to sort four times as much information. . b) The efficiency of merge sort is ANS: O(n log n).
19.2 What key aspect of both the binary search and the merge sort accounts for the logarithmic portion of their respective Big Os? ANS: Both of these algorithms incorporate “halving”—somehow reducing something by half. The binary search eliminates from consideration one-half of the array after each comparison. The merge sort splits the array in half each time it’s called. 19.3 In what sense is the insertion sort superior to the merge sort? In what sense is the merge sort superior to the insertion sort? ANS: The insertion sort is easier to understand and to program than the merge sort. The merge sort is far more efficient [O(n log n)] than the insertion sort [O(n2)]. 19.4 In the text, we say that after the merge sort splits the array into two subarrays, it then sorts these two subarrays and merges them. Why might someone be puzzled by our statement that “it then sorts these two subarrays”? ANS: In a sense, it does not really sort these two subarrays. It simply keeps splitting the original array in half until it provides a one-element subarray, which is, of course, sorted. It then builds up the original two subarrays by merging these one-element arrays to form larger subarrays, which are then merged, and so on.
Exercises NOTE: Solutions to the programming exercises are located in the ch19solutions folder. Each exercise has its own folder named ex19_## where ## is a two-digit number representing the exercise number. For example, exercise 19.10’s solution is located in the folder ex19_10. 19.5 (Bubble Sort) Implement bubble sort—another simple yet inefficient sorting technique. It’s called bubble sort or sinking sort because smaller values gradually “bubble” their way to the top of the array (i.e., toward the first element) like air bubbles rising in water, while the larger values sink to the bottom (end) of the array. The technique uses nested loops to make several passes through the array. Each pass compares successive pairs of elements. If a pair is in increasing order (or the values are equal), the bubble sort leaves the values as they are. If a pair is in decreasing order, the bubble sort swaps their values in the array. The first pass compares the first two elements of the array and swaps their values if necessary. It then compares the second and third elements in the array. The end of this pass compares the last two elements in the array and swaps them if necessary. After one pass, the largest element will be in the last index. After two passes, the largest two elements will be in the last two indices. Explain why bubble sort is an O(n2) algorithm. ANS: Bubble sort contains two nested for loops. The outer for loop (lines 24–33) iterates over data.length - 1 passes. The inner for loop (lines 27–32) iterates over data.length - 1 elements in the array. When loops are nested, the respective orders are multiplied. This is because for each of O(n) iterations of the outside loop, there are O(n) iterations of the inner loop. This results in a total Big O of O(n2).
20
Generic Collections: Solutions
I think this is the most extraordinary collection of talent, of human knowledge, that has ever been gathered together at the White House— with the possible exception of when Thomas Jefferson dined alone. —John F. Kennedy
Journey over all the universe in a map. —Miguel de Cervantes
Not by age but by capacity is wisdom acquired. —Titus Maccius Plautus
Objectives In this chapter you’ll learn: What collections are. ■ To use class Arrays for array manipulations. ■ The type-wrapper classes that enable programs to process primitive data values as objects. ■ To use the pre-built generic data structures of the collections framework. ■ To use iterators to “walk through” a collection. ■ To use persistent hash tables manipulated with objects of class Properties. ■ To use synchronization and modifiability wrappers. ■
2
Chapter 20
Generic Collections: Solutions
Self-Review Exercises 20.1
Fill in the blanks in each of the following statements: is used to iterate through a collection and can remove elements from the a) A(n) collection during the iteration. ANS: Iterator. . b) An element in a List can be accessed by using the element’s ANS: index. occurs when the c) Assuming that myArray contains references to Double objects, statement "myArray[ 0 ] = 1.25;" executes. ANS: autoboxing. and provide the capabilities of arraylike data structures d) Java classes that can resize themselves dynamically. ANS: ArrayList, Vector. the size of the Vece) If you do not specify a capacity increment, the system will tor each time additional capacity is needed. ANS: double. to create a collection that offers only read-only access to othf) You can use a(n) ers while allowing read/write access to yourself. ANS: unmodifiable wrapper. occurs when the g) Assuming that myArray contains references to Double objects, statement "double number = myArray[ 0 ];" executes. ANS: auto-unboxing. of Collections determines whether two collections have elements h) Algorithm in common. ANS: disjoint.
20.2
Determine whether each statement is true or false. If false, explain why. a) Values of primitive types may be stored directly in a collection. ANS: False. Autoboxing occurs when adding a primitive type to a collection, which means the primitive type is converted to its corresponding type-wrapper class. b) A Set can contain duplicate values. ANS: False. A Set cannot contain duplicate values. c) A Map can contain duplicate keys. ANS: False. A Map cannot contain duplicate keys. d) A LinkedList can contain duplicate values. ANS: True. e) Collections is an interface. ANS: False. Collections is a class; Collection is an interface. f) Iterators can remove elements. ANS: True. g) With hashing, as the load factor increases, the chance of collisions decreases. ANS: False. As the load factor increases, fewer slots are available relative to the total number of slots, so the chance of a collision increases. h) A PriorityQueue permits null elements. ANS: False. Attempting to insert a null element causes a NullPointerException.
Execises NOTE: Solutions to the programming exercises are located in the ch20solutions folder. Each exercise has its own folder named ex20_## where ## is a two-digit number represent-
Execises
3
ing the exercise number. For example, exercise 20.17’s solution is located in the folder ex20_17. 20.3
Define each of the following terms: a) Collection ANS: Interface Collection is the root interface in the collection hierarchy from which interfaces Set, Queue and List are derived. b) Collections ANS: Class Collections provides static methods that manipulate collections polymorphically. These methods implement algorithms for searching, sorting, and so on. c) Comparator ANS: An interface that specifies how collections objects are ordered. d) List ANS: An interface implemented by ordered collections that allow duplicate elements (sequences), such as ArrayList, LinkedList and Vector. e) load factor ANS: The ratio of the number of occupied cells in a hash table to the size of the hash table. f) collision ANS: A situation where two different keys hash into the same cell. g) space/time trade-off in hashing ANS: When the load factor is increased, the result is better memory utilization. However, the program runs slower due to increased hashing collisions. h) HashMap ANS: Java utilities package class that enables programmers to use a hash table to store key/ value pairs. Unlike Hashtable, it is not synchronized and permits null keys and values.
20.4
Explain briefly the operation of each of the following methods of class Vector: a) add ANS: Appends the specified element to the end of this Vector. b) set ANS: Replaces the element at the specified position. c) remove ANS: Removes the first occurrence of an element from the Vector. d) removeAllElements ANS: Removes all Vector elements and sets its size to zero. e) removeElementAt ANS: Removes the element at the specified position. f) firstElement ANS: Returns a reference to the first element in the Vector. g) lastElement ANS: Returns a reference to the last element in the Vector. h) contains ANS: Determines whether a Vector contains a specified object. i) indexOf ANS: Returns the position of the first occurrence of a specified object, or -1 if the object does not occur in the Vector. j) size ANS: The current number of elements in the Vector. k) capacity ANS: The number of elements available for storage (used and unused).
4
Chapter 20
Generic Collections: Solutions
20.5 Explain why inserting additional elements into a Vector object whose current size is less than its capacity is a relatively fast operation and why inserting additional elements into a Vector object whose current size is at capacity is a relatively slow operation. ANS: A Vector whose current size is less than its capacity has memory available. Insertions are fast because new memory does not need to be allocated. A Vector that is at its capacity must have its memory reallocated and the existing values copied into it. 20.6 By extending class Vector, Java’s designers were able to create class Stack quickly. What are the negative aspects of this use of inheritance, particularly for class Stack? ANS: Operations can be performed on Stack objects that are not normally allowed, which can lead to corruption of the stack. For example, Vector method insertElementAt should not be performed on Stack. 20.7
Briefly answer the following questions: a) What is the primary difference between a Set and a Map? ANS: Maps contain both the key and the value, and Sets contain only values. Sets contain unique values; Maps contain unique keys but may contain duplicated values. b) What happens when you add a primitive type (e.g., double) value to a collection? ANS: Autoboxing occurs when a primitive type value is added to a collection. For example, a double primitive type value is converted to an object of its wrapper class Double. c) Can you print all the elements in a collection without using an Iterator? If yes, how? ANS: Yes, the elements in a collection can be printed by iterating through the collection with the enhanced for statement. Alternatively, you can use the collection’s toString method.
20.8
Explain briefly the operation of each of the following Iterator-related methods: a) iterator ANS: Returns an Iterator for a collection. b) hasNext ANS: Determines whether a collection has another element. c) next ANS: Returns the next element in a collection.
20.9
Explain briefly the operation of each of the following methods of class HashMap: a) put ANS: Adds a key/value pair into the HashMap. b) get ANS: Locates the value associated with the specified key. c) isEmpty ANS: Returns a boolean value indicating whether or not the HashMap is empty. d) containsKey ANS: Determines whether specified key is in the HashMap. e) keySet ANS: Returns a Set of the keys in the HashMap.
20.10 Determine whether each of the following statements is true or false. If false, explain why. a) Elements in a Collection must be sorted in ascending order before a binarySearch may be performed. ANS: True. b) Method first gets the first element in a TreeSet. ANS: True. c) A List created with Arrays method asList is resizable. ANS: False. The List is fixed length.
Execises 20.11 Explain the operation of each of the following methods of the Properties class: a) load ANS: Reads the contents from a specified InputStream. b) store ANS: Writes the contents to a specified OutputStream. c) getProperty ANS: Returns the value associated with a key. d) list ANS: Displays the contents of a Properties object to the specified output stream.
5
21
Generic Classes and Methods
Every man of genius sees the world at a different angle from his fellows. —Havelock Ellis
…our special individuality, as distinguished from our generic humanity. —Oliver Wendell Holmes, Sr.
Born under one law, to another bound. —Lord Brooke
Objectives In this chapter you’ll learn: To create generic methods that perform identical tasks on arguments of different types. ■ To create a generic Stack class that can be used to store objects of any class or interface type. ■ To understand how to overload generic methods with nongeneric methods or with other generic methods. ■ To understand raw types and how they help achieve backward compatibility. ■ To use wildcards when precise type information about a parameter is not required in the method body. ■
2
Chapter 21
Generic Classes and Methods
Self-Review Exercises 21.1
State whether each of the following is true or false. If false, explain why. a) A generic method cannot have the same method name as a nongeneric method. ANS: False. Generic and nongeneric methods can have the same method name. A generic method can overload another generic method with the same method name but different method parameters. A generic method also can be overloaded by providing nongeneric methods with the same method name and number of arguments. b) All generic method declarations have a type-parameter section that immediately precedes the method name. ANS: False. All generic method declarations have a type-parameter section that immediately precedes the method’s return type. c) A generic method can be overloaded by another generic method with the same method name but different method parameters. ANS: True. d) A type parameter can be declared only once in the type-parameter section but can appear more than once in the method’s parameter list. ANS: True. e) Type-parameter names among different generic methods must be unique. ANS: False. Type-parameter names among different generic methods need not be unique. f) The scope of a generic class’s type parameter is the entire class except its static members. ANS: True.
21.2
Fill in the blanks in each of the following: and enable you to specify, with a single method declaration, a set of a) related methods, or with a single class declaration, a set of related types, respectively. ANS: Generic methods, generic classes. . b) A type-parameter section is delimited by ANS: angle brackets (< and >). can be used to specify the method’s argument types, to c) A generic method’s specify the method’s return type and to declare variables within the method. ANS: type parameters. d) The statement "Stack objectStack = new Stack();" indicates that objectStack stores . ANS: a raw type. . e) In a generic class declaration, the class name is followed by a(n) ANS: type-parameter section. specifies that the upper bound of a wildcard is type T. f) The syntax ANS: ? extends T.
Exercises NOTE: Solutions to the programming exercises are located in the ch21solutions folder. Each exercise has its own folder named ex21_## where ## is a two-digit number representing the exercise number. For example, exercise 21.8’s solution is located in the folder ex21_08. 21.3
Explain the use of the following notation in a Java program: public class Array< T > { }
ANS: This notation declares a generic class named Array with a single type parameter T.
Exercises
3
21.4 Write a simple generic version of method isEqualTo that compares its two arguments with the equals method and returns true if they are equal and false otherwise. Use this generic method in a program that calls isEqualTo with a variety of built-in types, such as Object or Integer. What result do you get when you attempt to run this program? ANS: For classes that override the equals method, the program will compare the objects based on their contents. For example, the Integer class’s equals method would compare the contents of two Integer objects. For classes that do not override the equals method, the program will compare the objects based on their references, not their contents. 21.9
How can generic methods be overloaded? ANS: A generic method may be overloaded in several ways. Generic methods can be overloaded by other generic methods that specify the same method name but different method parameters. Generic methods can also be overloaded by non-generic methods that have the same method name and number of parameters.
21.10 The compiler performs a matching process to determine which method to call when a method is invoked. Under what circumstances does an attempt to make a match result in a compiletime error? ANS: If the compiler cannot match the method call made to either a non-generic method or a generic method, or if the matching process results in multiple matches with no matches more specific than the others at compile time, the compiler generates an error. 21.11 Explain why a Java program might use the statement ArrayList< Employee > workerList = new ArrayList< Employee >();
ANS: When creating objects from a generic class, it is necessary to provide a type argument
(or possibly several type arguments) to instantiate the objects with actual types. The above statement would be used to create an ArrayList object that stores Employee objects. The compiler can then perform type checking to ensure that the code uses the ArrayList of Employees properly.
22 Much that I bound, I could not free; Much that I freed returned to me. —Lee Wilson Dodd
‘Will you walk a little faster?’ said a whiting to a snail, ‘There’s a porpoise close behind us, and he’s treading on my tail.’ —Lewis Carroll
There is always room at the top. —Daniel Webster
Push on—keep moving. —Thomas Morton
I’ll turn over a new leaf. —Miguel de Cervantes
Objectives In this chapter you’ll learn: ■
To form linked data structures using references, selfreferential classes, recursion and generics.
■
To create and manipulate dynamic data structures, such as linked lists, queues, stacks and binary trees.
■
Various important applications of linked data structures.
■
How to create reusable data structures with classes, inheritance and composition.
Custom Generic Data Structures: Solutions
Self-Review Exercises
2
Self-Review Exercises 22.1
Fill in the blanks in each of the following statements: class is used to form dynamic data structures that can grow and shrink a) A selfat execution time. ANS: referential. is a constrained version of a linked list in which nodes can be inserted b) A(n) and deleted only from the start of the list. ANS: stack. c) A method that does not alter a linked list, but simply looks at it to determine whether method. it’s empty, is referred to as a(n) ANS: predicate. data structure because the first nodes inserted d) A queue is referred to as a(n) are the first ones removed. ANS: first-in, first-out (FIFO). . e) The reference to the next node in a linked list is referred to as a(n) ANS: link. . f) Automatically reclaiming dynamically allocated memory in Java is called ANS: garbage collection. is a constrained version of a linked list in which nodes can be inserted g) A(n) only at the end of the list and deleted only from the start of the list. ANS: queue. is a nonlinear, two-dimensional data structure that contains nodes with h) A(n) two or more links. ANS: tree. data structure because the last node inserted is the i) A stack is referred to as a(n) first node removed. ANS: last-in, first-out (LIFO). tree contain two link members. j) The nodes of a(n) ANS: binary. node. k) The first node of a tree is the ANS: root. or of that node. l) Each link in a tree node refers to a(n) ANS: child or subtree. node. m) A tree node that has no children is called a(n) ANS: leaf. n) The three traversal algorithms we mentioned in the text for binary search trees are , and . ANS: inorder, preorder, postorder.
22.2
What are the differences between a linked list and a stack? ANS: It’s possible to insert a node anywhere in a linked list and remove a node from anywhere in a linked list. Nodes in a stack may be inserted only at the top of the stack and removed only from the top.
22.3
What are the differences between a stack and a queue? ANS: A queue is a FIFO data structure that has references to both its head and its tail, so that nodes may be inserted at the tail and deleted from the head. A stack is a LIFO data structure that has a single reference to the stack’s top, where both insertion and deletion of nodes are performed.
3
Chapter 22
Custom Generic Data Structures: Solutions
22.4 Perhaps a more appropriate title for this chapter would have been Reusable Data Structures. Comment on how each of the following entities or concepts contributes to the reusability of data structures: a) classes ANS: Classes allow us to instantiate as many data structure objects of a certain type (i.e., class) as we wish. b) inheritance ANS: Inheritance enables a subclass to reuse the functionality from a superclass. Public and protected methods of a superclass can be accessed through a subclass to eliminate duplicate logic. c) composition ANS: Composition enables a class to reuse code by storing a reference to an instance of another class in a field. Public methods of the instance can be called by methods in the class that contains the reference. 22.5 Manually provide the inorder, preorder and postorder traversals of the binary search tree of Fig. 22.20.
49 28 18 11
19
83 40 32
44
71 69
72
97 92
99
Fig. 22.20 | Binary search tree with 15 nodes. ANS: The inorder traversal is 11 18 19 28 32 40 44 49 69 71 72 83 92 97 99
The preorder traversal is 49 28 18 11 19 40 32 44 83 71 69 72 97 92 99
The postorder traversal is 11 19 18 32 44 40 28 69 72 71 92 99 97 83 49
Exercises NOTE: Solutions to the programming exercises are located in the ch22solutions folder. Each exercise has its own folder named ex22_## where ## is a two-digit number representing the exercise number. For example, exercise 22.17’s solution is located in the folder ex22_17. 22.18 (Duplicate Elimination) In this chapter, we saw that duplicate elimination is straightforward when creating a binary search tree. Describe how you’d perform duplicate elimination when using only a one-dimensional array. Compare the performance of array-based duplicate elimination with the performance of binary-search-tree-based duplicate elimination.
Exercises
4
ANS: First, sort the array—this makes all the duplicates be adjacent. Then, walk through
the array with a source and destination index, copying only the first of a sequence of duplicates from the source to the destination. Once the source index reaches the end of the array, remove the elements after the destination index from the array. This yields the same efficiency as inserting them into a balanced binary search tree. 22.27 (Lists and Queues without Tail References) Our implementation of a linked list (Fig. 22.3) used both a firstNode and a lastNode. The lastNode was useful for the insertAtBack and removeFromBack methods of the List class. The insertAtBack method corresponds to the enqueue method of the Queue class. Rewrite the List class so that it does not use a lastNode. Thus, any operations on the tail of a list must begin searching the list from the front. Does this affect our implementation of the Queue class (Fig. 22.13)? ANS: The interface of the List class was not changed—just its implementation. Therefore, the Queue class does not need to be changed other than changing the import statements to point to the different List class. The performance of the Queue will be adversely affected because adding to the end of the List is now linear in the number of elements instead of constant time. 22.28 (Performance of Binary Tree Sorting and Searching) One problem with the binary tree sort is that the order in which the data is inserted affects the shape of the tree—for the same collection of data, different orderings can yield binary trees of dramatically different shapes. The performance of the binary tree sorting and searching algorithms is sensitive to the shape of the binary tree. What shape would a binary tree have if its data were inserted in increasing order? in decreasing order? What shape should the tree have to achieve maximal searching performance? ANS: If the data were inserted in increasing or decreasing order, the tree would consist of only right children or only left children, respectively. Essentially, the tree would be a sorted linked list. To achieve maximum performance, the depth of the tree should be minimized—in other words, all non-leaf nodes except for the last row should have two children.
23 Observe due measure, for right timing is in all things the most important factor. —Hesiod
Painting is only a bridge linking the painter’s mind with that of the viewer. —Eugene Delacroix
The direction in which education starts a man will determine his future in life. —Plato
Objectives In this chapter you’ll learn: What applets are and how they’re used in web pages. ■ To observe some of Java’s exciting capabilities through the JDK’s demonstration applets. ■ To write simple applets. ■ To write a simple HyperText Markup Language (HTML) document to load an applet into an applet container and execute the applet. ■ Applet life-cycle methods. ■ About the sandbox security model for running downloaded code safely. ■ What Java Web Start is and how to use it to download, install and run applets outside of the web browser. ■
Applets and Java Web Start: Solutions
2
Chapter 23
Applets and Java Web Start: Solutions
Self-Review Exercise 23.1
Fill in the blanks in each of the following: , and a) Java applets begin execution with a series of three method calls: . ANS: init, start, paint. method is invoked for an applet each time a browser’s user leaves an b) The XHTML page on which the applet resides. ANS: stop. . c) Every applet should extend class ANS: JApplet (or Applet). or a browser can be used to execute a Java applet. d) The ANS: appletviewer. e) The method is called each time the user of a browser revisits the XHTML page on which an applet resides. ANS: start. file. f) To load an applet into a browser, you must first define a(n) ANS: XHTML. is called once when an applet begins execution. g) Method ANS: init. is invoked to draw on an applet. h) Method ANS: paint. is invoked for an applet when the browser removes it from memory. i) Method ANS: destroy. and XHTML tags specify that an applet should be loaded into j) The an applet container and executed. ANS: <applet>, </applet>. is a framework for running downloaded programs outside the browser. k) ANS: Java Web Start. document provides the information that Java Web Start needs to downl) A(n) load and run a program. ANS: Java Network Launch Protocol (JNLP). enables you to manage the Java Web Start programs on your system. m) The ANS: Java Cache Viewer.
Exercises NOTE: Solutions to the programming exercises are located in the ch23solutions folder. Each exercise has its own folder named ex23_## where ## is a two-digit number representing the exercise number. For example, exercise 23.10’s solution is located in the folder ex23_10.
24 The wheel that squeaks the loudest … gets the grease. —John Billings (Henry Wheeler Shaw)
We’ll use a signal I have tried and found far-reaching and easy to yell. Waa-hoo! —Zane Grey
There is a natural hootchykootchy motion to a goldfish. —Walt Disney
Between the motion and the act falls the shadow. —Thomas Stearns Eliot
Objectives In this chapter you’ll learn: ■
How to get, display and scale images.
■
How to create animations from sequences of images.
■
How to create image maps that can sense when the cursor is over them.
■
How to get, play, loop and stop sounds using an AudioClip.
■
How to play video using interface Player.
Multimedia: Applets and Applications, Solutions
2
Chapter 24
Multimedia: Applets and Applications, Solutions
Self-Review Exercises 24.1
Fill in the blanks in each of the following statements: displays an image on an applet. a) Graphics method ANS: drawImage. b) Java provides two mechanisms for playing sounds in an applet—the Applet’s play method and the play method of the interface. ANS: AudioClip. is an image that has hot areas that the user can click to accomplish a task c) A(n) such as loading a web page. ANS: image map. of class ImageIcon displays the ImageIcon’s image. d) Method ANS: paintIcon. e) Java supports several image formats, including , and . ANS: Graphics Interchange Format (GIF), Joint Photographic Experts Group (JPEG), Portable Network Graphics (PNG). class’s static lookup method obtains a reference to the Filef) The JNLP OpenService. ANS: ServiceManager.
24.2
Determine whether each of the following statements is true or false. If false, explain why. a) A sound is marked for garbage collection after it plays via the play method of class Applet. ANS: True. b) Class ImageIcon provides constructors that allow an ImageIcon object to be initialized only with an image from the local computer. ANS: False. ImageIcon can load images from the Internet as well. c) Method play of class AudioClip continuously loops an audio clip. ANS: False. Method play of class AudioClip plays an audio clip once. Method loop of class AudioClip continuously loops an audio clip. d) The Java Image I/O API is used for adding 3D graphics to a Java application. ANS: False. The Java 3D API is used for creating and modifying 3D graphics. The Java Image I/O API is used for reading from and outputting images to files. e) Applet method getDocumentBase returns, as an object of class URL, the location on the Internet of the HTML file that invoked the applet. ANS: True. f) FileOpenService methods openFileDialog and openMultiFileDialog return a FileContents object and an array of FileContents objects, respectively. ANS: True.
Exercises NOTE: Solutions to the programming exercises are located in the ch24solutions folder. Each exercise has its own folder named ex24_## where ## is a two-digit number representing the exercise number. For example, exercise 24.10’s solution is located in the folder ex24_10. 24.3
Describe how to make an animation “browser friendly.” ANS: Begin the animation with the start method of class Timer and suspend/terminate the animation in the stop method of class Timer. The animation should stop when the user switches web pages. If the user returns to the web page with the animation, the animation should be restarted.
Exercises
3
24.4
Describe the Java methods for playing and manipulating audio clips. ANS: Class Applet method play and the AudioClip interface method play both load the sound and play it once. AudioClip method loop continuously loops the audio clip in the background. AudioClip method stop terminates an audio clip that is currently playing.
24.5
Explain how image maps are used. List several examples of their use. ANS: Image maps are used to create interactive web pages that: a) load different web pages based on user choice, b) show descriptive messages for images within the image maps, c) define regions for an image, when the mouse enters the image region, display the image, d) when the mouse clicks an image region, link the user to the URL associated with the image.
25
GUI Components: Part 2, Solutions
An actor entering through the door, you’ve got nothing. But if he enters through the window, you’ve got a situation. —Billy Wilder
...the force of events wakes slumberous talents. —Edward Hoagland
You and I would see more interesting photography if they would stop worrying, and instead, apply horse-sense to the problem of recording the look and feel of their own era. —Jessie Tarbox Beals
Objectives In this chapter you’ll learn: ■
To create and manipulate sliders, menus, pop-up menus and windows.
■
To programatically change the look-and-feel of a GUI, using Swing’s pluggable lookand-feel.
■
To create a multipledocument interface with JDesktopPane and JInternalFrame.
■
To use additional layout managers.
2
Chapter 25
GUI Components: Part 2, Solutions
Self-Review Exercises 25.1
Fill in the blanks in each of the following statements: class is used to create a menu object. a) The ANS: JMenu. method of class JMenu places a separator bar in a menu. b) The ANS: addSeparator. method of interface . c) JSlider events are handled by the ANS: stateChanged, ChangeListener. is set to CENTER by default. d) The GridBagConstraints instance variable ANS: anchor.
25.2
State whether each of the following is true or false. If false, explain why. a) When the programmer creates a JFrame, a minimum of one menu must be created and added to the JFrame. ANS: False. A JFrame does not require any menus. b) The variable fill belongs to the GridBagLayout class. ANS: False. The variable fill belongs to the GridBagConstraints class. c) Drawing on a GUI component is performed with respect to the (0, 0) upper-left corner coordinate of the component. ANS: True. d) The default layout for a Box is BoxLayout. ANS: True.
25.3
Find the error(s) in each of the following and explain how to correct the error(s). a) JMenubar b; ANS: JMenubar should be JMenuBar. b) mySlider = JSlider( 1000, 222, 100, 450 ); ANS: The first argument to the constructor should be either SwingConstants.HORIZONTAL or SwingConstants.VERTICAL, and the keyword new must be used after the = operator. Also, the minimum value should be less than the maximum and the initial value should be in range. c) gbc.fill = GridBagConstraints.NORTHWEST; // set fill ANS: The constant should be either BOTH, HORIZONTAL, VERTICAL or NONE. d) // override to paint on a customized Swing component public void paintcomponent( Graphics g ) { g.drawString( "HELLO", 50, 50 ); } // end method paintComponent
ANS: paintcomponent should be paintComponent, and the method should call super.paintComponent( g ) as its first statement.
e)
// create a JFrame and display it JFrame f = new JFrame( "A Window" ); f.setVisible( true );
ANS: The JFrame’s setSize method must also be called to establish the size of the window.
Exercises NOTE: Solutions to the programming exercises are located in the ch25solutions folder. Each exercise has its own folder named ex25_## where ## is a two-digit number representing the exercise number. For example, exercise 25.14’s solution is located in the folder ex25_14.
Exercises
3
25.4
Fill in the blanks in each of the following statements: . a) A JMenuItem that is a JMenu is called a(n) ANS: submenu. attaches a JMenuBar to a JFrame. b) Method ANS: setJMenuBar. has a default BoxLayout. c) Container class ANS: Box. manages a set of child windows declared with class JInternalFrame. d) A(n) ANS: JDesktopPane.
25.5
State whether each of the following is true or false. If false, explain why. a) Menus require a JMenuBar object so they can be attached to a JFrame. ANS: True. b) BoxLayout is the default layout manager for a JFrame. ANS: False. BorderLayout is the default layout manager for JFrame. c) JApplets can contain menus. ANS: True.
25.6
Find the error(s) in each of the following. Explain how to correct the error(s). a) x.add( new JMenuItem( "Submenu Color" ) ); // create submenu ANS: A JMenu is used to create a submenu, not a JMenuItem. b) container.setLayout( new GridbagLayout() ); ANS: GridbagLayout should be GridBagLayout.
25.9 Explore the effects of varying the weightx and weighty values of the program in Fig 25.21. What happens when a slot has a nonzero weight but is not allowed to fill the whole area (i.e., the fill value is not BOTH)? ANS: When the weight is non-zero but the component is not allowed to fill in both directions, blank space is created around the component. The amount of space allocated for the component in the panel is the same as if it could expand to fill the space, but the component does not stretch in that direction.
26 The most general definition of beauty…Multeity in Unity. —Samuel Taylor Coleridge
Do not block the way of inquiry. —Charles Sanders Peirce
A person with one watch knows what time it is; a person with two watches is never sure. —Proverb
Learn to labor and to wait. —Henry Wadsworth Longfellow
The world is moving so fast these days that the man who says it can’t be done is generally interrupted by someone doing it. —Elbert Hubbard
Objectives In this chapter you’ll learn: What threads are and why they’re useful. ■ How threads enable you to manage concurrent activities. ■ The life cycle of a thread. ■ To create and execute Runnables. ■ Thread synchronization. ■ What producer/consumer relationships are and how they’re implemented with multithreading. ■ To enable multiple threads to update Swing GUI components in a thread-safe manner. ■
Multithreading: Solutions
Self-Review Exercises
2
Self-Review Exercises 26.1
Fill in the blanks in each of the following statements: . a) A thread enters the terminated state when ANS: its run method ends. b) To pause for a designated number of milliseconds and resume execution, a thread of class . should call method ANS: sleep, Thread. of class Condition moves a single thread in an object’s waiting state c) Method to the runnable state. ANS: signal. of class Condition moves every thread in an object’s waiting state to d) Method the runnable state. ANS: signalAll. thread enters the state when it completes its task or othere) A(n) wise terminates. ANS: runnable, terminated. state for a specified interval of time. f) A runnable thread can enter the ANS: timed waiting. g) At the operating-system level, the runnable state actually encompasses two separate and . states, ANS: ready, running. interface. h) Runnables are executed using a class that implements the ANS: Executor. ends each thread in an ExecutorService as soon i) ExecutorService method as it finishes executing its current Runnable, if any. ANS: shutdown. on a Condition object to release the associated Lock j) A thread can call method and place that thread in the state. ANS: await, waiting. relationship, the generates data and stores it in a shared k) In a(n) reads data from the shared object. object, and the ANS: producer/consumer, producer, consumer. implements the BlockingQueue interface using an array. l) Class ANS: ArrayBlockingQueue. indicates that only one thread at a time should execute on an object. m) Keyword ANS: synchronized.
26.2
State whether each of the following is true or false. If false, explain why. a) A thread is not runnable if it has terminated. ANS: True. b) Some operating systems use timeslicing with threads. Therefore, they can enable threads to preempt threads of the same priority. ANS: False. Timeslicing allows a thread to execute until its timeslice (or quantum) expires. Then other threads of equal priority can execute. c) When the thread’s quantum expires, the thread returns to the running state as the operating system assigns it to a processor. ANS: False. When a thread’s quantum expires, the thread returns to the ready state and the operating system assigns to the processor another thread.
3
Chapter 26
Multithreading: Solutions
d) On a single-processor system without timeslicing, each thread in a set of equal-priority threads (with no other threads present) runs to completion before other threads of equal priority get a chance to execute. ANS: True.
Exercises NOTE: Solutions to the programming exercises are located in the ch26solutions folder. Each exercise has its own folder named ex26_## where ## is a two-digit number representing the exercise number. For example, exercise 26.8’s solution is located in the folder ex26_08. 26.3
State whether each of the following is true or false. If false, explain why. a) Method sleep does not consume processor time while a thread sleeps. ANS: True. b) Declaring a method synchronized guarantees that deadlock cannot occur. ANS: False. Deadlocks can occur if the lock on an object is never released. c) Once a ReentrantLock has been obtained by a thread, the ReentrantLock object will not allow another thread to obtain the lock until the first thread releases it. ANS: True. d) Swing components are thread safe. ANS: False. Swing components are not thread safe. All interactions with Swing GUI components should be performed in the event-dispatching thread.
26.4
Define each of the following terms. a) thread ANS: An individual execution context of a program. b) multithreading ANS: The ability of more than one thread to execute concurrently. c) runnable state ANS: A state in which the thread is capable of running (if the processor becomes available). d) timed waiting state ANS: A state in which the thread cannot use the processor because it is waiting for a time interval to expire or a notification from another thread. e) preemptive scheduling ANS: A thread of higher priority enters a running state and is assigned to the processor. The thread preempted from the processor is placed back in the ready state according to its priority. f) Runnable interface ANS: An interface that provides a run method. By implementing the Runnable interface, any class can be executed as a separate thread. g) notifyAll method ANS: Transitions all threads waiting on an object’s monitor to the runnable state. h) producer/consumer relationship ANS: A relationship in which a producer and a consumer share common data. The producer typically wants to "produce" (add information) and the consumer wants to "consume" (remove information). i) quantum ANS: A small amount of processor time, also called a time slice.
26.5
Discuss each of the following terms in the context of Java’s threading mechanisms:
Exercises a)
4
synchronized
ANS: When a method or block is declared synchronized and it is running, the object is
locked. Other threads cannot access the other synchronized methods of the object until the lock is released. b) producer ANS: A thread that writes data to a shared memory resource. c) consumer ANS: A thread that reads data from a shared memory resource. d) wait ANS: Places a thread in the waiting state until another thread calls notify or notifyAll on the same object or until a specified amount of time elapses. e) notify ANS: Wake a thread currently waiting on the given object. f) Lock ANS: An interface implemented by objects that control access to a resource shared among multiple threads. Only one thread can be holding a Lock at one time—a second thread calling the lock method will block until the unlock method is called. Using the Lock interface is more complicated than using the synchronized keyword, but is more flexible. g) Condition ANS: Objects of this interface represent condition variables that can be used with Locks to manage access to a shared resource. 26.6 List the reasons for entering the blocked state. For each of these, describe how the program will normally leave the blocked state and enter the runnable state. ANS: A thread transitions to the blocked state when it attempts to perform a task that cannot be completed immediately and the thread must temporarily wait until that task completes. For example, when a thread issues an input/output request, the operating system blocks the thread from executing until that I/O request completes—at that point, the blocked thread transitions to the runnable state, so it can resume execution. A thread also transitions to the blocked state when it attempts to acquire a monitor lock that is not currently available. When the lock becomes available, the thread returns to the runnable state and attempts to acquire the lock. 26.7 Two problems that can occur in systems that allow threads to wait are deadlock, in which one or more threads will wait forever for an event that cannot occur, and indefinite postponement, in which one or more threads will be delayed for some unpredictably long time. Give an example of how each of these problems can occur in multithreaded Java programs. ANS: Deadlock: If we have two threads named thread1 and thread2, deadlock might occur in the following situation: If thread1 is waiting for thread2 to complete a task, and thread2 is waiting for thread1 to complete a task, then neither thread can continue. Since both threads are in the waiting state, neither thread can be signaled to continue executing. To help prevent deadlocks, ensure locks are always taken in the same order and released in the opposite order they were taken. Indefinite Postponement: This typically occurs because threads of higher priority are scheduled before threads of lower priority.
27
Networking: Solutions
If the presence of electricity can be made visible in any part of a circuit, I see no reason why intelligence may not be transmitted instantaneously by electricity. —Samuel F. B. Morse
Protocol is everything. —Francois Giuliani
What networks of railroads, highways and canals were in another age, the networks of telecommunications, information and computerization … are today. —Bruno Kreisky
The port is near, the bells I hear, the people all exulting. —Walt Whitman
Objectives In this chapter you’ll learn: ■
Java networking with URLs, sockets and datagrams.
■
To implement Java networking applications by using sockets and datagrams.
■
To implement Java clients and servers that communicate with one another.
■
To implement network-based collaborative applications.
■
To construct a simple multithreaded server.
2
Chapter 27
Networking: Solutions
Self-Review Exercises 27.1
Fill in the blanks in each of the following statements: occurs when an input/output error occurs when closing a socket. a) Exception ANS: IOException. occurs when a hostname indicated by a client cannot be resolved b) Exception to an address. ANS: UnknownHostException. c) If a DatagramSocket constructor fails to set up a DatagramSocket properly, an exception occurs. of type ANS: SocketException. . d) Many of Java’s networking classes are contained in package ANS: java.net. e) Class binds the application to a port for datagram transmission. ANS: DatagramSocket. contains an IP address. f) An object of class ANS: InetAddress. and . g) The two types of sockets we discussed in this chapter are ANS: stream sockets, datagram sockets. . h) The acronym URL stands for ANS: Uniform Resource Locator. . i) The acronym URI stands for ANS: Uniform Resource Identifier. . j) The key protocol that forms the basis of the World Wide Web is ANS: HTTP. receives a URL object as an argument and displays in a k) AppletContext method browser the World Wide Web resource associated with that URL. ANS: showDocument. object containing the local IP address of the l) Method getLocalHost returns a(n) computer on which the program is executing. ANS: InetAddress. m) The URL constructor determines whether its String argument is a valid URL. If so, the URL object is initialized with that location. If not, a(n) exception occurs. ANS: MalformedURLException.
27.2
State whether each of the following is true or false. If false, explain why. a) UDP is a connection-oriented protocol. ANS: False; UDP is a connectionless protocol and TCP is a connection-oriented protocol. b) With stream sockets a process establishes a connection to another process. ANS: True. c) A server waits at a port for connections from a client. ANS: True. d) Datagram packet transmission over a network is reliable—packets are guaranteed to arrive in sequence. ANS: False; packets can be lost, arrive out of order or be duplicated.
Exercises NOTE: Solutions to the programming exercises are located in the ch27solutions folder. Each exercise has its own folder named ex27_## where ## is a two-digit number representing the exercise number. For example, exercise 27.13’s solution is located in the folder ex26_13.
Exercises 27.3
27.4
3
Distinguish between connection-oriented and connectionless network services. ANS: Connection-oriented services maintain a connection while data is being transferred. Connectionless services do not maintain a connection. Connection-oriented services are generally slower but more reliable. How does a client determine the hostname of the client computer? ANS: InetAddress.getLocalHost().getHostName().
27.5
27.6
27.7
27.8
27.9 client.
Under what circumstances would a SocketException be thrown? ANS: If a socket operation fails due to a problem in the underlying protocol. For example, if a DatagramSocket cannot bind to the specified port. How can a client get a line of text from a server? ANS: After connecting, the client can get data from the server using the stream object returned by the Socket’s getInputStream method. The code required to get a single line of text can be simplified by wrapping the InputStream in a Scanner or ObjectInputStream. Alternatively, the server can send the text by wrapping it in a DatagramPacket and using send method of class DatagramSocket. Describe how a client connects to a server. ANS: A server listens for a connection on a specific address and port using the ServerSocket class. A client can then connect to the server by giving the address and port to the Socket constructor. Once the connect operation completes, the server and client can send data back and forth between each other. Describe how a server sends data to a client. ANS: For stream-based sockets, the client connects to the server by creating a socket using the Socket class constructor. The name of the server and the port to connect to are passed to the Socket constructor. Information can be exchanged between the client and server using the socket’s InputStream and OutputStream. For datagram-based sockets, the server can send a DatagramPacket to the client using the send method of class DatagramSocket. Describe how to prepare a server to receive a stream-based connection request from a single ANS: First a ServerSocket object must be created and associated with a port on the server
computer. If the ServerSocket is created properly, a call to the accept method can be issued on the ServerSocket object. This call will wait for a client to connect. When a client connects, a Socket object is returned from the accept call. The Socket object is used to get the InputStream and OutputStream objects for communication with the client. 27.10 How does a server listen for streams-based socket connections at a port? ANS: The ServerSocket accept method is used. 27.11 What determines how many connect requests from clients can wait in a queue to connect to a server? ANS: When the ServerSocket object is created on the server, the second argument to the ServerSocket constructor specifies the "queue length" (the number of clients that can wait to be processed by the server). 27.12 As described in the text, what reasons might cause a server to refuse a connection request from a client? ANS: A server usually has a capacity of the number of clients that can wait for a connection and be processed by the server. If the queue of clients is full, client connections are refused.
28 It is a capital mistake to theorize before one has data. —Arthur Conan Doyle
Now go, write it before them in a table, and note it in a book, that it may be for the time to come for ever and ever. —The Holy Bible, Isaiah 30:8
Get your facts first, and then you can distort them as much as you please. —Mark Twain
I like two kinds of men: domestic and foreign. —Mae West
Objectives In this chapter you’ll learn: Relational database concepts. ■ To use Structured Query Language (SQL) to retrieve data from and manipulate data in a database. ■ To use the JDBC™ API to access databases. ■ To use the RowSet interface from package javax.sql to manipulate databases. ■ To use JDBC 4’s automatic JDBC driver discovery. ■ To create precompiled SQL statements with parameters via PreparedStatements. ■ How transaction processing makes database applications more robust. ■
Accessing Databases with JDBC: Solutions
2
Chapter 28
Accessing Databases with JDBC: Solutions
Self-Review Exercise 28.1
Fill in the blanks in each of the following statements: . a) The international standard database language is and . b) A table in a database consists of objects. c) Statement objects return SQL query results as uniquely identifies each row in a table. d) The is followed by the selection criteria that specify the rows to see) SQL keyword lect in a query. specify the order in which rows are sorted in a query. f) SQL keywords the tables. g) Merging rows from multiple database tables is called is an organized collection of data. h) A(n) is a set of columns whose values match the primary-key values of ani) A(n) other table. method is used to obtain a Connection to a database. j) helps manage the connection between a Java program and a datak) Interface base. object is used to submit a query to a database. l) A(n) and objects are scrollable and updatm) Unlike a ResultSet object, able by default. , a disconnected RowSet, caches the data of a ResultSet in memory. n)
Answers to Self-Review Exercise 28.1 a) SQL. b) rows, columns. c) ResultSet. d) primary key. e) WHERE. f) ORDER BY. g) joining. h) database. i) foreign key. j) DriverManager, getConnection. k) Connection. l) Statement. m) JdbcRowSet, CachedRowSet n) CachedRowSet.
Exercises NOTE: Solutions to the programming exercises are located in the ch28solutions folder. Each exercise has its own folder named Ex28_## where ## is a two-digit number representing the exercise number. For example, exercise 28.3’s solution is located in the folder Ex28_03.
29
JavaServer™ Faces Web Apps: Part 1
If any man will draw up his case, and put his name at the foot of the first page, I will give him an immediate reply. Where he compels me to turn over the sheet, he must wait my leisure. —Lord Sandwich
Rule One: Our client is always right. Rule Two: If you think our client is wrong, see Rule One. —Anonymous
A fair question should be followed by a deed in silence. —Dante Alighieri
You will come here and get books that will open your eyes, and your ears, and your curiosity, and turn you inside out or outside in. —Ralph Waldo Emerson
Objectives In this chapter you’ll learn: To create JavaServer Faces web apps. ■ To create web apps consisting of multiple pages. ■ To validate user input on a web page. ■ To maintain user-specific state information throughout a web app with session tracking. ■
Self-Review Exercises
2
Self-Review Exercises 29.1
State whether each of the following is true or false. If false, explain why. a) A URL contains information that directs a browser to the resource that the user wishes to access. ANS: True. b) Host names are translated into IP addresses by web servers. ANS: False. Host names are translated into IP addresses by DNS servers. c) The path in a URL typically specifies a resource’s exact location on the server. ANS: False. The server translates a virtual directory into a real location, thus hiding a resource’s true location. d) GET requests and POST requests can both be used to send form data to a web server. ANS: True. e) Browsers typically cache the server’s response to a POST request. ANS: False. Browsers typically do not cache the server’s response to a POST request, because the next POST might not return the same result. f) A tag library defines a set of elements that can be inserted into the XHTML markup. ANS: True. g) You must create and manage the JavaBean objects that are used in your JSF web applications. ANS: False. The JSF framework creates and manages objects of your JavaBean classes for you. h) When the Faces servlet encounters an EL expression that accesses a bean property, it automatically invokes the property’s set or get method based on the context in which the property is used. ANS: True. i) An h:panelGrid element organizes elements in an XHTML table. ANS: True. j) An h:selectOneMenu element is typically rendered in a web page as a set of radio buttons. ANS: False. An h:selectOneRadio element is rendered as a set of radio buttons. An h:selectOneMenu is rendered as a drop-down list. k) The messages specified by an element’s requiredMessage and validatorMessage attributes are displayed in an associated h:message element when validation fails. ANS: True. l) The HTTP protocol provides information that enables web servers to maintain state information regarding particular clients. ANS: False. HTTP is a stateless protocol that does not provide information that enables web servers to maintain state information regarding particular clients—a separate tracking technology must be used. m) The ui:repeat element inserts its nested element(s) once for each element in a collection. The collection can be any IEnumerable type. ANS: False. A ui:repeat element can iterate over only arrays, Lists and ResultSets. For any other object, the elements in a ui:repeat element will be inserted once.
29.2
Fill in the blanks in each of the following statements: . a) Java multitier applications are typically implemented using the features of ANS: Java Enterprise Edition (Java EE). software make resources available, such as web pages, b) Computers that run images, PDF documents and even objects that perform complex tasks. ANS: web-server.
3
Chapter 29
JavaServer™ Faces Web Apps: Part 1
c) The JSF web-application framework’s processes each requested JSF page. ANS: Faces servlet. exposes its data as read/write, read-only or write-only properties. d) A(n) ANS: JavaBean. annotation indicates that the JSF framework should create and manage e) The instances of the class. ANS: @ManagedBean. element contains the components with which a user interacts to prof) A(n) vide data, such as registration or login information, to a JSF app. ANS: h:form. element triggers an action when clicked. g) A(n) ANS: h:commandButton. h) A(n) validator determines whether a field contains an acceptable number of characters. ANS: f:validateLength. validator determines whether a field contains a string that matches a i) A(n) specified regular expression pattern. ANS: f:validateRegex. , the browser re-requests the page and sends the values of the form’s j) In a(n) fields to the server for processing. ANS: postback. bean is created when a session begins and exists throughout the entire k) A(n) session. ANS: @SessionScoped.
Exercises NOTE: Solutions to the programming exercises are located in the ch29solutions folder. Each exercise has its own folder named Ex29_## where ## is a two-digit number representing the exercise number. For example, exercise 29.3’s solution is located in the folder Ex29_03.
30
JavaServer™ Faces Web Apps: Part 2
Whatever is in any way beautiful hath its source of beauty in itself, and is complete in itself; praise forms no part of it. —Marcus Aurelius Antoninus
There is something in a face, An air, and a peculiar grace, Which boldest painters cannot trace. —William Somerville
Cato said the best way to keep good acts in memory was to refresh them with new. —Francis Bacon
I never forget a face, but in your case I’ll make an exception. —Groucho Marx
Objectives In this chapter you’ll learn: ■
To access databases from JSF applications.
■
The basic principles and advantages of Ajax technology.
■
To use Ajax in a JSF web app.
Self-Review Exercise
2
Self-Review Exercise 30.1
Fill in the blanks in each of the following statements. . a) Ajax is an acronym for ANS: Asynchronous JavaScript and XML. allows the server to manage a limited number of database connections b) A(n) and share them among requests. ANS: connection pool. is a technology for locating application components (such as databases) in a c) distributed application. ANS: JNDI (Java Naming and Directory Interface). enables a web application to obtain a Connection to a database. d) A(n) ANS: DataSource. e) The annotation can be used to inject a DataSource object into a managed bean. ANS: @Resource. element displays a collection of objects in tabular format. f) A(n) ANS: h:dataTable. attribute can specify the name of another page in the g) An h:commandButton’s web app that should be returned to the client. ANS: action. elements h) To specify headers or footers for the columns in h:dataTables, use and , respectively. nested with their name attributes set to ANS: f:facet, "header", "footer". separates the user interaction portion of an application from its server interi) action, enabling both to proceed asynchronously in parallel. ANS: Ajax. help make web applications more responsive, making them feel more like j) desktop applications. ANS: partial page updates. attribute specifies a space-separated list of element k) The f:ajax element’s ids—the values of these elements are submitted as part of the Ajax request. ANS: execute. attribute specifies a space-separated list of element ids l) The f:ajax element’s for the elements that should be updated via partial page updates. ANS: render.
Exercises NOTE: Solutions to the programming exercises are located in the ch30solutions folder. Each exercise has its own folder named Ex30_## where ## is a two-digit number representing the exercise number. For example, exercise 30.3’s solution is located in the folder Ex30_03.
3
Chapter 30
JavaServer™ Faces Web Apps: Part 2
Web Services
31 A client is to me a mere unit, a factor in a problem. —Sir Arthur Conan Doyle
They also serve who only stand and wait. —John Milton
...if the simplest things of nature have a message that you understand, rejoice, for your soul is alive. —Eleonora Duse
Protocol is everything. —Francoise Giuliani
Objectives In this chapter you will learn: ■ What a web service is. ■ How to publish and consume web services in NetBeans. ■ How XML, JSON, XML-Based Simple Object Access Protocol (SOAP) and Representational State Transfer (REST) Architecture enable Java web services. ■ How to create client desktop and web applications that consume web services. ■ How to use session tracking in web services to maintain client state information. ■ How to connect to databases from web services. ■ How to pass objects of userdefined types to and return them from a web service.
2
Chapter 31
Web Services
Self-Review Exercises 31.1
State whether each of the following is true or false. If false, explain why. a) All methods of a web service class can be invoked by clients of that web service. ANS: False. Only methods declared with the @WebMethod annotation can be invoked by a web service’s clients. b) When consuming a web service in a client application created in NetBeans, you must create the proxy class that enables the client to communicate with the web service. ANS: False. The proxy class is created by NetBeans when you add a web service client to the application. c) A proxy class communicating with a web service normally uses SOAP to send and receive messages. ANS: True. d) Session tracking is automatically enabled in a client of a web service. ANS: False. In the JAX-WS framework, the client must indicate whether it wants to allow the web service to maintain session information. First, you must cast the proxy object to interface type BindingProvider, then use the BindingProvider’s getRequestContext method to obtain the RequestContext object. Finally, you must use the RequestContext’s put method to set the property BindingProvider.SESSION_ MAINTAIN_PROPERTY to true. e) Web methods cannot be declared static. ANS: True. f) A user-defined type used in a web service must define both get and set methods for any property that will be serialized. ANS: True. g) Operations in a REST web service are defined by their own unique URLs. ANS: True. h) A SOAP-based web service can return data in JSON format. ANS: False. A SOAP web service implicitly returns data in XML format.
31.2
Fill in the blanks for each of the following statements: a) A key difference between SOAP and REST is that SOAP messages have data wrapped . in a(n) ANS: SOAP message or SOAP envelope. —it does not need to implement any interfaces or b) A web service in Java is a(n) extend any classes. ANS: POJO (plain old Java object) protoc) Web service requests are typically transported over the Internet via the col. ANS: HTTP. element of the @WebMethod d) To set the exposed name of a web method, use the annotation. ANS: operationName. transforms an object into a format that can be sent between a web service and e) a client. ANS: serialization. f) To return data in JSON format from a method of a REST-based web service, the @Pro. duces annotation is set to ANS: "application/json". g) To return data in XML format from a method of a REST-based web service, the @Produces annotation is set to . ANS: "application/xml".
Exercises
3
Exercises 31.3 (Phone Book Web Service) PLEASE USE THE UPDATED VERSION OF THE EXERCISE POSTED AT: http://bit.ly/hSLBon 31.4 (Phone Book Web Service Modification) PLEASE USE THE UPDATED VERSION OF THE EXERCISE POSTED AT: http://bit.ly/hSLBon 31.5 (Phone-Book Web Service with JSON) Modify Exercise 31.4 so that the PhoneBookEntry class is passed to and from the web service as a JSON object. Use serialization to convert the JSON object into an object of type PhoneBookEntry. ANS: NO SOLUTION PROVIDED 31.6 (Blackjack Web Service Modification) Modify the Blackjack web service example in Section 31.9 to include class Card. Modify web method dealCard so that it returns an object of type Card and modify web method getHandValue so that it receives an array of Card objects from the client. Also modify the client application to keep track of what cards have been dealt by using ArrayLists of Card objects. The proxy class created by NetBeans will treat a web method’s array parameter as a List, so you can pass these ArrayLists of Card objects directly to the getHandValue method. Your Card class should include set and get methods for the face and suit of the card. ANS: See solution on disk. 31.7 (Airline Reservation Web-Service Modification) Modify the airline reservation web service in Section 31.10 so that it contains two separate methods—one that allows users to view all available seats, and another that allows users to reserve a particular seat that is currently available. Use an object of type Ticket to pass information to and from the web service. The web service must be able to handle cases in which two users view available seats, one reserves a seat and the second user tries to reserve the same seat, not knowing that it is now taken. The names of the methods that execute should be reserve and getAllAvailableSeats. ANS: NO SOLUTION PROVIDED 31.8 (Morse Code Web Service) In Exercise 16.22, you learned about Morse Code and wrote applications that could translate English phrases into Morse Code and vice versa. Create a SOAPbased web service that provides two methods—one that translates an English phrase into Morse Code and one that translates Morse Code into English. Next, build a Morse Code translator GUI application that invokes the web service to perform these translations. ANS: NO SOLUTION PROVIDED
Making a Difference 31.9 (Project: Spam Scanner Web Service) In Exercise 16.27, you created a spam scanner application that scanned an e-mail and gave it a point rating based on the occurrence of certain words and phrases that commonly appear in spam e-mails and how many times the words and phrases occurred in the e-mail. Create a SOAP-based Spam scanner web service. Next, modify the GUI application you created in Exercise 16.27 to use the web service to scan an e-mail. Then display the point rating returned by the web service. ANS: NO SOLUTION PROVIDED 31.10 (SMS Web Service) In Exercise 16.28, you created an SMS message-translator application. Create a SOAP-based web service with three methods: a) one that receives an SMS abbreviation and returns the corresponding English word or phrase, b) one that receives an entire SMS message and returns the corresponding English text, and c) one that translates English text into an SMS message.
4
Chapter 31
Web Services
Use the web service from a GUI application that displays the web service’s responses. ANS: NO SOLUTION PROVIDED 31.11 (Gender-Neutrality Web Service) In Exercise 1.12, you researched eliminating sexism in all forms of communication. You then described the algorithm you’d use to read through a paragraph of text and replace gender-specific words with gender-neutral equivalents. Create a SOAP-based web service that receives a paragraph of text, then replaces gender-specific words with gender-neutral ones. Use the web service from a GUI application that displays the resulting gender-neutral text. ANS: NO SOLUTION PROVIDED
Making a Difference
5