Big Java.pdf - Google Drive

9 downloads 293 Views 41MB Size Report
Nov 7, 2009 - tracking, and more. • manage time better. • study smarter. • save money. www.wileyplus.com. WP5_FM_8
bj4_fm.fm Page iv Saturday, November 7, 2009 12:01 PM

This online teaching and learning environment integrates the entire digital textbook with the most effective instructor and student resources to fit every learning style.

With WileyPLUS: • Students achieve concept mastery in a rich, structured environment that’s available 24/7

• Instructors personalize and manage their course more effectively with assessment, assignments, grade tracking, and more

• manage time better • study smarter • save money

From multiple study paths, to self-assessment, to a wealth of interactive visual and audio resources, WileyPLUS gives you everything you need to personalize the teaching and learning experience.

» F i n d o u t h ow t o M a k e I t Yo u r s » www.wileyplus.com

WP5_FM_8x10.indd 1

8/7/09 11:36 AM

all the help, resources, and personal support you and your students need!

2-Minute Tutorials and all of the resources you & your students need to get started www.wileyplus.com/firstday

Student support from an experienced student user Ask your local representative for details!

Collaborate with your colleagues, find a mentor, attend virtual and live events, and view resources www.WhereFacultyConnect.com

Pre-loaded, ready-to-use assignments and presentations www.wiley.com/college/quickstart

Technical Support 24/7 FAQs, online chat, and phone support www.wileyplus.com/support

Your WileyPLUS Account Manager Training and implementation support www.wileyplus.com/accountmanager

Make It Yours! WP5_FM_8x10.indd 2

8/7/09 11:36 AM

bj4_fm.fm Page iii Saturday, November 7, 2009 12:01 PM

Big Java 4

th edition

bj4_fm.fm Page iv Saturday, November 7, 2009 12:01 PM

bj4_fm.fm Page v Saturday, November 7, 2009 12:01 PM

4

th edition

Big Java Cay Horstmann

JOHN WILEY & SONS, INC.

SAN JOSE STATE UNIVERSITY

bj4_fm.fm Page vi Saturday, November 7, 2009 12:01 PM

VICE PRESIDENT AND EXECUTIVE PUBLISHER EXECUTIVE EDITOR EDITORIAL ASSISTANT PRODUCTION SERVICES MANAGER PRODUCTION EDITOR EXECUTIVE MARKETING MANAGER CREATIVE DIRECTOR SENIOR DESIGNER PHOTO EDITOR MEDIA EDITOR PRODUCTION SERVICES COVER DESIGNER COVER ILLUSTRATION

Donald Fowley Beth Lang Golub Michael Berlin Dorothy Sinclair Janet Foxman Christopher Ruel Harry Nolan Madelyn Lesure Lisa Gee Lauren Sapira Cindy Johnson Howard Grossman Susan Cyr

This book was set in Stempel Garamond by Publishing Services, and printed and bound by RRD Jefferson City. The cover was printed by RRD Jefferson City. This book is printed on acid-free paper. ∞ Copyright © 2010, 2008, 2006, 2002 John Wiley & Sons, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, Inc., 222 Rosewood Drive, Danvers, MA 01923, website www.copyright.com. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030-5774, (201) 748-6011, fax (201) 748-6008, website www.wiley.com/go/permissions. Evaluation copies are provided to qualified academics and professionals for review purposes only, for use in their courses during the next academic year. These copies are licensed and may not be sold or transferred to a third party. Upon completion of the review period, please return the evaluation copy to Wiley. Return instructions and a free of charge return shipping label are available at www.wiley.com/go/returnlabel. Outside of the United States, please contact your local representative. Library of Congress Cataloging-in-Publication width="300" height="400">

If you know HTML, you can proudly explain your creation, by adding text and more HTML tags: ch02/applet/RectangleAppletExplained.html 1 2 3 4 5 6 7 8 9 10

Two rectangles

Here is my first applet:



An HTML file can have multiple applets. Simply add a separate applet tag for each applet. You can give the HTML file any name you like. It is easiest to give the HTML file the same name as the applet. But some development environments already generate an HTML file with the same name as your project to hold your project notes; then you must give the HTML file containing your applet a different name.

An Applet in the Applet Viewer

An Applet in a Web Browser

bj4_ch02_8.fm Page 65 Thursday, November 5, 2009 10:47 AM

2.13 Ellipses, Lines, Text, and Color 65

Graphics Track

To run the applet, you have two choices. You can use the applet viewer, a program that is included with the Java Software Development Kit from Sun Microsystems. You simply start the applet viewer, giving it the name of the HTML file that contains your applets: appletviewer RectangleApplet.html

You view applets with the applet viewer or a Javaenabled browser.

The applet viewer only shows the applet, not the HTML text (see the left figure). You can also show the applet inside any Java-enabled web browser, such as Firefox or Safari. (If you use Internet Explorer, you probably need to configure it. By default, Microsoft supplies either an outdated version of Java or no Java at all. Go to the java.com web site and install the Java plugin.) The second figure shows the applet running in a browser. As you can see, both the text and the applet are displayed.

2.13 Ellipses, Lines, Text, and Color In Section 2.12 you learned how to write a program that draws rectangles. In this section you will learn how to draw other shapes: ellipses and lines. With these graphical elements, you can draw quite a few interesting pictures.

2.13.1 Ellipses and Circles

Ellipse2D.Double ellipse = new Ellipse2D.Double(x, y, width, height);

The class name Ellipse2D.Double looks different from the class names that you have encountered up to now. It consists of two class names Ellipse2D and Double separated (x, y)

Width

Height

The Ellipse2D.Double and Line2D.Double classes describe graphical shapes.

To draw an ellipse, you specify its bounding box (see Figure 24) in the same way that you would specify a rectangle, namely by the x- and y-coordinates of the topleft corner and the width and height of the box. However, there is no simple Ellipse class that you can use. Instead, you must use one of the two classes Ellipse2D.Float and Ellipse2D.Double, depending on whether you want to store the ellipse coordinates as single- or double-precision floatingpoint values. Because the latter are more convenient to use in Java, we will always use the Ellipse2D.Double class. Here is how you construct an ellipse:

Figure 24

An Ellipse and Its Bounding Box

bj4_ch02_8.fm Page 66 Thursday, November 5, 2009 10:47 AM

66 Chapter 2 Using Objects

Graphics Track

by a period (.). This indicates that Ellipse2D.Double is a so-called inner class inside Ellipse2D. When constructing and using ellipses, you don’t actually need to worry about the fact that Ellipse2D.Double is an inner class—just think of it as a class with a long name. However, in the import statement at the top of your program, you must be careful that you import only the outer class: import java.awt.geom.Ellipse2D;

Drawing an ellipse is easy: Use exactly the same draw method of the Graphics2D class that you used for drawing rectangles. g2.draw(ellipse);

To draw a circle, simply set the width and height to the same values: Ellipse2D.Double circle = new Ellipse2D.Double(x, y, diameter, diameter); g2.draw(circle);

Notice that (x, y) is the top-left corner of the bounding box, not the center of the circle.

2.13.2 Lines To draw a line, use an object of the Line2D.Double class. A line is constructed by specifying its two end points. You can do this in two ways. Simply give the x- and ycoordinates of both end points: Line2D.Double segment = new Line2D.Double(x1, y1, x2, y2);

Or specify each end point as an object of the Point2D.Double class: Point2D.Double from = new Point2D.Double(x1, y1); Point2D.Double to = new Point2D.Double(x2, y2); Line2D.Double segment = new Line2D.Double(from, to);

The second option is more object-oriented and is often more useful, particularly if the point objects can be reused elsewhere in the same drawing.

2.13.3 Drawing Text The drawString method draws a string, starting at its basepoint.

You often want to put text inside a drawing, for example, to label some of the parts. Use the drawString method of the Graphics2D class to draw a string anywhere in a window. You must specify the string and the x- and y-coordinates of the basepoint of the first character in the string (see Figure 25). For example, g2.drawString("Message", 50, 100);

Baseline

Basepoint Figure 25

Basepoint and Baseline

bj4_ch02_8.fm Page 67 Thursday, November 5, 2009 10:47 AM

2.13 Ellipses, Lines, Text, and Color 67

Graphics Track

2.13.4 Colors When you first start drawing, all shapes and strings are drawn with a black pen. To change the color, you need to supply an object of type Color. Java uses the RGB color model. That is, you specify a color by the amounts of the primary colors— red, green, and blue—that make up the color. The amounts are given as integers between 0 (primary color not present) and 255 (maximum amount present). For example, Color magenta = new Color(255, 0, 255);

When you set a new color in the graphics context, it is used for subsequent drawing operations.

constructs a Color object with maximum red, no green, and maximum blue, yielding a bright purple color called magenta. For your convenience, a variety of colors have been declared in the Color class. Table 4 shows those colors and their RGB values. For example, Color.PINK has been declared to be the same color as new Color(255, 175, 175). To draw a shape in a different color, first set the color of the Graphics2D object, then call the draw method: g2.setColor(Color.RED); g2.draw(circle); // Draws the shape in red

If you want to color the inside of the shape, use the fill method instead of the draw method. For example, g2.fill(circle);

fills the inside of the circle with the current color.

Table 4 Predefined Colors Color

RGB Value

Color.BLACK

0, 0, 0

Color.BLUE

0, 0, 255

Color.CYAN

0, 255, 255

Color.GRAY

128, 128, 128

Color.DARKGRAY

64, 64, 64

Color.LIGHTGRAY

192, 192, 192

Color.GREEN

0, 255, 0

Color.MAGENTA

255, 0, 255

Color.ORANGE

255, 200, 0

Color.PINK

255, 175, 175

Color.RED

255, 0, 0

Color.WHITE

255, 255, 255

Color.YELLOW

255, 255, 0

bj4_ch02_8.fm Page 68 Thursday, November 5, 2009 10:47 AM

68 Chapter 2 Using Objects

Graphics Track

Figure 26

An Alien Face

The following program puts all these shapes to work, creating a simple drawing (see Figure 26). ch02/face/FaceComponent.java 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

import import import import import import import

java.awt.Color; java.awt.Graphics; java.awt.Graphics2D; java.awt.Rectangle; java.awt.geom.Ellipse2D; java.awt.geom.Line2D; javax.swing.JComponent;

/*

A component that draws an alien face. */ public class FaceComponent extends JComponent { public void paintComponent(Graphics g) { // Recover Graphics2D Graphics2D g2 = (Graphics2D) g; // Draw the head Ellipse2D.Double head = new Ellipse2D.Double(5, 10, 100, 150); g2.draw(head); // Draw the eyes g2.setColor(Color.GREEN); Rectangle eye = new Rectangle(25, 70, 15, 15); g2.fill(eye); eye.translate(50, 0); g2.fill(eye); // Draw the mouth Line2D.Double mouth = new Line2D.Double(30, 110, 80, 110); g2.setColor(Color.RED); g2.draw(mouth); // Draw the greeting g2.setColor(Color.BLUE); g2.drawString("Hello, World!", 5, 175); } }

bj4_ch02_8.fm Page 69 Thursday, November 5, 2009 10:47 AM

2.13 Ellipses, Lines, Text, and Color 69

Graphics Track

ch02/face/FaceViewer.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

SELF CHECK

32. 33. 34. 35. 36.

import javax.swing.JFrame; public class FaceViewer { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setSize(150, 250); frame.setTitle("An Alien Face"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); FaceComponent component = new FaceComponent(); frame.add(component); frame.setVisible(true); } }

Give instructions to draw a circle with center (100, 100) and radius 25. Give instructions to draw a letter “V” by drawing two line segments. Give instructions to draw a string consisting of the letter “V”. What are the RGB color values of Color.BLUE? How do you draw a yellow square on a red background?

Random Fact 2.2 The Evolution of the Internet In 1962, J.C.R. Licklider was head of the first computer research program at DARPA, the Defense Advanced Research Projects Agency. He wrote a series of papers describing a “galactic network” through which computer users could access Please enter values, Q to quit:"); while (in.hasNextDouble()) { book.addScore(in.nextDouble()); } System.out.println("Final score: " + book.finalScore());

Now the finalScore method must do the heavy lifting. It too should not have to do all the work. Instead, we will supply helper methods public double sum() public double minimum()

These methods simply implement the algorithms in Section 7.6.2 and Section 7.6.4. Then the finalScore method becomes public double finalScore() { if (scores.size() == 0) return 0; else if (scores.size() == 1) return scores.get(0); else return sum() - minimum(); }

Step 5

Assemble and test the program. Implement your classes and test them, as described in How To 3.1. Review your code and check that you handle both normal and exceptional situations. What happens with an empty array or array list? One that contains a single element? When no match is found? When there are multiple matches? Consider these boundary conditions and make sure that your program works correctly. In our example, it is impossible to compute the minimum if the array list is empty. In that case, we should determine the special score of 0 before attempting to call the minimum method.

bj4_ch07_8.fm Page 306 Thursday, November 5, 2009 12:35 PM

306 Chapter 7 Arrays and Array Lists

Testing Track

What if the minimum value occurs more than once? That means that a student had more than one test with the same low score. We subtract only one of the occurrences of that low score, and that is the desired behavior. The following table shows test cases and their expected output: Test Case

Expected Output

Comment

8 7 8.5 9.5 7 5 10

50

See Step 1.

8 7 7 9

24

Only one instance of the low score should be removed.

8

8

Don’t remove the lowest score if there is only one.

(no inputs)

0

An empty grade book has score 0.

The complete program is in the ch07/scores directory of the book’s companion code.

Worked Example 7.1

Rolling the Dice This Worked Example shows how to analyze a set of die tosses to see whether the die is “fair”.

7.7 Regression Testing A test suite is a set of tests for repeated testing.

Regression testing involves repeating previously run tests to ensure that known failures of prior versions do not appear in new versions of the software.

It is a common and useful practice to make a new test whenever you find a program bug. You can use that test to verify that your bug fix really works. Don’t throw the test away; feed it to the next version after that and all subsequent versions. Such a collection of test cases is called a test suite. You will be surprised how often a bug that you fixed will reappear in a future version. This is a phenomenon known as cycling. Sometimes you don’t quite understand the reason for a bug and apply a quick fix that appears to work. Later, you apply a different quick fix that solves a second problem but makes the first problem appear again. Of course, it is always best to think through what really causes a bug and fix the root cause instead of doing a sequence of “Band-Aid” solutions. If you don’t succeed in doing that, however, you at least want to have an honest appraisal of how well the program works. By keeping all old test cases around and testing them against every new version, you get that feedback. The process of checking each version of a program against a test suite is called regression testing. How do you organize a suite of tests? An easy technique is to produce multiple tester classes, such as BankTester1, BankTester2, and so on. Another useful approach is to provide a generic tester, and feed it inputs from multiple files. Consider this tester for the Bank class of Section 7.6:

Available online in WileyPLUS and at www.wiley.com/college/horstmann.

bj4_ch07_8.fm Page 307 Monday, October 26, 2009 11:53 AM

7.7 Regression Testing 307

Testing Track

ch07/regression/BankTester.java 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

import java.util.Scanner; /**

This program tests the Bank class. */ public class BankTester { public static void main(String[] args) { Bank firstBankOfJava = new Bank(); firstBankOfJava.addAccount(new BankAccount(1001, 20000)); firstBankOfJava.addAccount(new BankAccount(1015, 10000)); firstBankOfJava.addAccount(new BankAccount(1729, 15000)); Scanner in = new Scanner(System.in); double threshold = in.nextDouble(); int c = firstBankOfJava.count(threshold); System.out.println("Count: " + c); int expectedCount = in.nextInt(); System.out.println("Expected: " + expectedCount); int accountNumber = in.nextInt(); BankAccount a = firstBankOfJava.find(accountNumber); if (a == null) System.out.println("No matching account"); else { System.out.println("Balance of matching account: " + a.getBalance()); int matchingBalance = in.nextInt(); System.out.println("Expected: " + matchingBalance); } } }

Rather than using fixed values for the threshold and the account number to be found, the program reads these values, and the expected responses. By running the program with different inputs, we can test different scenarios, such as the ones for diagnosing off-by-one errors discussed in Common Error 6.2. Of course, it would be tedious to type in the input values by hand every time the test is executed. It is much better to save the inputs in a file, such as the following: ch07/regression/input1.txt 15000 2 1015 10000

The command line interfaces of most operating systems provide a way to link a file to the input of a program, as if all the characters in the file had actually been typed by a user. Type the following command into a shell window: java BankTester < input1.txt

bj4_ch07_8.fm Page 308 Monday, October 26, 2009 11:53 AM

308 Chapter 7 Arrays and Array Lists

Testing Track

The program is executed, but it no longer reads input from the keyboard. Instead, the System.in object (and the Scanner that reads from System.in) gets the input from the file input1.txt. This process is called input redirection. The output is still displayed in the console window: Program Run Count: 2 Expected: 2 Balance of matching account: 10000 Expected: 10000

You can also redirect output. To capture the output of a program in a file, use the command java BankTester < input1.txt > output1.txt

This is useful for archiving test cases. SELF CHECK

16. 17. 18.

Suppose you modified the code for a method. Why do you want to repeat tests that already passed with the previous version of the code? Suppose a customer of your program finds an error. What action should you take beyond fixing the error? Why doesn’t the BankTester program contain prompts for the inputs?

Productivity Hint 7.2 Batch Files and Shell Scripts If you need to perform the same tasks repeatedly on the command line, then it is worth learning about the automation features offered by your operating system. Under Windows, you use batch files to execute a number of commands automatically. For example, suppose you need to test a program by running three testers: java BankTester1 java BankTester2 java BankTester3 < input1.txt

Then you find a bug, fix it, and run the tests again. Now you need to type the three commands once more. There has to be a better way. Under Windows, put the commands in a text file and call it test.bat: File test.bat 1 2 3

java BankTester1 java BankTester2 java BankTester3 < input1.txt

Then you just type test.bat

and the three commands in the batch file execute automatically. Batch files are a feature of the operating system, not of Java. On Linux, Mac OS, and UNIX, shell scripts are used for the same purpose. In this simple example, you can execute the commands by typing sh test.bat

bj4_ch07_8.fm Page 309 Monday, October 26, 2009 11:53 AM

7.7 Regression Testing 309

Testing Track

There are many uses for batch files and shell scripts, and it is well worth it to learn more about their advanced features, such as parameters and loops.

Random Fact 7.2 The Therac-25 Incidents The Therac-25 is a computerized device to deliver radiation treatment to cancer patients (see the figure). Between June 1985 and January 1987, several of these machines delivered serious overdoses to at least six patients, killing some of them and seriously maiming the others. The machines were controlled by a computer program. Bugs in the program were directly responsible for the overdoses. According to Leveson and Turner (“An Investigation of the Therac-25 Accidents,” IEEE Computer, July 1993, pp. 18–41), the program was written by a single programmer, who had since left the manufacturing company producing the device and could not be located. None of the company employees interviewed could say anything about the educational level or qualifications of the programmer. The investigation by the federal Food and Drug Administration (FDA) found that the program was poorly documented and that there was neither a specification document nor a formal test plan. (This should make you think. Do you have a formal test plan for your programs?) The overdoses were caused by an amateurish design of the software that had to control different devices concurrently, namely the keyboard, the display, the printer, and of course the radiation device itself. Synchronization and box=java.awt.Rectangle[x=5,y=10,width=20,height=30]"

bj4_ch10_7.fm Page 446 Wednesday, October 28, 2009 8:16 AM

446 Chapter 10 Inheritance

The compiler can invoke the toString method, because it knows that every object has a toString method: Every class extends the Object class, and that class provides a toString method. As you know, numbers are also converted to strings when they are concatenated with other strings. For example, int age = 18; String s = "Harry's age is " + age; // Sets s to "Harry's age is 18"

In this case, the toString method is not involved. Numbers are not objects, and there is no toString method for them. There is only a small set of primitive types, however, and the compiler knows how to convert them to strings. Let’s try the toString method for the BankAccount class: BankAccount momsSavings = new BankAccount(5000); String s = momsSavings.toString(); // Sets s to something like "BankAccount@d24606bf"

That’s disappointing—all that’s printed is the name of the class, followed by the hash code, a seemingly random code. The hash code can be used to tell objects apart—different objects are likely to have different hash codes. (See Chapter 16 for the details.) We don’t care about the hash code. We want to know what is inside the object. But, of course, the toString method of the Object class does not know what is inside the BankAccount class. Therefore, we have to override the method and supply our own version in the BankAccount class. We’ll follow the same format that the toString method of the Rectangle class uses: first print the name of the class, and then the values of the instance variables inside brackets. public class BankAccount { . . . public String toString() { return "BankAccount[balance=" + balance + "]"; } }

This works better: BankAccount momsSavings = new BankAccount(5000); String s = momsSavings.toString(); // Sets s to "BankAccount[balance=5000]"

10.7.2 Overriding the equals Method When implementing the equals method, test whether two objects have equal state.

The equals method is called whenever you want to compare whether two objects have the same contents: if (coin1.equals(coin2)) . . . // Contents are the same—see Figure 8

This is different from the test with the == operator, which tests whether the two references are to the same object: if (coin1 == coin2) . . . // Objects are the same—see Figure 9

bj4_ch10_7.fm Page 447 Wednesday, October 28, 2009 8:16 AM

10.7 Object: The Cosmic Superclass 447

coin1 =

Coin value = name =

coin2 =

Coin value = name =

Figure 8

0.25 "quarter"

0.25 "quarter"

Two References to Equal Objects

coin1 =

Coin coin2 = value = name =

Figure 9

0.25 "quarter"

Two References to the Same Object

Let us implement the equals method for the equals method of the Object class:

Coin

class. You need to override the

public class Coin { . . . public boolean equals(Object otherObject) { . . . } . . . }

Now you have a slight problem. The Object class knows nothing about coins, so it declares the otherObject parameter of the equals method to have the type Object. When overriding the method, you are not allowed to change the parameter type. To overcome this problem, cast the parameter to the class Coin: Coin other = (Coin) otherObject;

Then you can compare the two coins. public boolean equals(Object otherObject) { Coin other = (Coin) otherObject; return name.equals(other.name) && value == other.value; }

bj4_ch10_7.fm Page 448 Wednesday, October 28, 2009 8:16 AM

448 Chapter 10 Inheritance

Note that you must use equals to compare object references, but use == to compare numbers. When you override the equals method, you should also override the hashCode method so that equal objects have the same hash code—see Chapter 16 for details.

10.7.3 The clone Method You know that copying an object reference simply gives you two references to the same object: BankAccount account = new BankAccount(1000); BankAccount account2 = account; account2.deposit(500); // Now both account and account2 refer to a bank account with a balance of 1500 The clone method makes a new object with the same state as an existing object.

What can you do if you actually want to make a copy of an object? That is the purpose of the clone method. The clone method must return a new object that has an identical state to the existing object (see Figure 10). Implementing the clone method is quite a bit more difficult than implementing the toString or equals methods—see Special Topic 10.6 on page 452 for details. Let us suppose that someone has implemented the clone method for the BankAccount class. Here is how to call it: BankAccount clonedAccount = (BankAccount) account.clone();

The return type of the clone method is the class Object. When you call the method, you must use a cast to convince the compiler that account.clone() really has the same type as clonedAccount.

account =

BankAccount balance =

clonedAccount =

BankAccount balance =

Figure 10

Cloning Objects

SELF CHECK

15. 16.

10000

Should the call x.equals(x) always return true? Can you implement equals in terms of toString? Should you?

10000

bj4_ch10_7.fm Page 449 Wednesday, October 28, 2009 8:16 AM

10.7 Object: The Cosmic Superclass 449

Quality Tip 10.1 Supply toString in All Classes If you have a class whose toString() method returns a string that describes the object state, then you can simply call System.out.println(x) whenever you need to inspect the current state of an object x. This works because the println method of the PrintStream class invokes x.toString() when it needs to print an object, which is extremely helpful if there is an error in your program and the objects don’t behave the way you think they should. You can simply insert a few print statements and peek inside the object state during the program run. Some debuggers can even invoke the toString method on objects that you inspect. Sure, it is a bit more trouble to write a toString method when you aren’t sure your program ever needs one—after all, it might work correctly on the first try. Then again, many programs don’t work on the first try. As soon as you find out that yours doesn’t, consider adding those toString methods to help you debug the program.

Special Topic 10.4 Inheritance and the toString Method You just saw how to write a toString method: Form a string consisting of the class name and the names and values of the instance variables. However, if you want your toString method to be usable by subclasses of your class, you need to work a bit harder. Instead of hardcoding the class name, you should call the getClass method to obtain a class object, an object of the Class class that describes classes and their properties. Then invoke the getName method to get the name of the class: public String toString() { return getClass().getName() + "[balance=" + balance + "]"; }

Then the toString method prints the correct class name when you apply it to a subclass, say a SavingsAccount . SavingsAccount momsSavings = . . . ; System.out.println(momsSavings); // Prints "SavingsAccount[balance=10000]"

Of course, in the subclass, you should override toString and add the values of the subclass instance variables. Note that you must call super.toString to get the superclass instance variables—the subclass can’t access them directly. public class SavingsAccount extends BankAccount { public String toString() { return super.toString() + "[interestRate=" + interestRate + "]"; } }

Now a savings account is converted to a string such as SavingsAccount[balance= 10000][interThe brackets show which instance variables belong to the superclass.

estRate=5].

bj4_ch10_7.fm Page 450 Wednesday, October 28, 2009 8:16 AM

450 Chapter 10 Inheritance

Common Error 10.6 Declaring the equals Method with the Wrong Parameter Type Consider the following, seemingly simpler, version of the equals method for the Coin class: public boolean equals(Coin other) // Don’t do this! { return name.equals(other.name) && value == other.value; }

Here, the parameter of the equals method has the type Coin, not Object. Unfortunately, this method does not override the equals method in the Instead, the Coin class now has two different equals methods: boolean equals(Coin other) // Declared in the Coin class boolean equals(Object otherObject) // Inherited from the Object

This is error-prone because the wrong these variable declarations:

equals

Object

class.

class

method can be called. For example, consider

Coin aCoin = new Coin(0.25, "quarter"); Object anObject = new Coin(0.25, "quarter");

The call aCoin.equals(anObject) calls the second equals method, which returns false. The remedy is to ensure that you use the Object type for the explicit parameter of the equals method.

Special Topic 10.5 Inheritance and the equals Method You just saw how to write an equals method: Cast the otherObject parameter to the type of your class, and then compare the instance variables of the implicit parameter and the other parameter. But what if someone called coin1.equals(x) where x wasn’t a Coin object? Then the bad cast would generate an exception, and the program would die. Therefore, you first want to test whether otherObject really is an instance of the Coin class. The easiest test would be with the instanceof operator. However, that test is not specific enough. It would be possible for otherObject to belong to some subclass of Coin. To rule out that possibility, you should test whether the two objects belong to the same class. If not, return false. if (getClass() != otherObject.getClass()) return false;

Moreover, the Java language specification demands that the equals method return false when otherObject is null. Here is an improved version of the equals method that takes these two points into account: public boolean equals(Object otherObject) { if (otherObject == null) return false; if (getClass() != otherObject.getClass()) return false; Coin other = (Coin) otherObject; return name.equals(other.name) && value == other.value; }

bj4_ch10_7.fm Page 451 Wednesday, October 28, 2009 8:16 AM

10.7 Object: The Cosmic Superclass 451 When you implement equals in a subclass, you should first call equals in the superclass, like this: public CollectibleCoin extends Coin { private int year; . . . public boolean equals(Object otherObject) { if (!super.equals(otherObject)) return false; CollectibleCoin other = (CollectibleCoin) otherObject; return year == other.year; } }

Quality Tip 10.2 Clone Mutable Instance Variables in Accessor Methods Consider the following class: public class Customer { private String name; private BankAccount account; public Customer(String aName) { name = aName; account = new BankAccount(); } public String getName() { return name; } public BankAccount getAccount() { return account; } }

This class looks very boring and normal, but the getAccount method has a curious property. It breaks encapsulation, because anyone can modify the object state without going through the public interface: Customer harry = new Customer("Harry Handsome"); BankAccount account = harry.getAccount(); // Anyone can withdraw money! account.withdraw(100000);

Maybe that wasn’t what the designers of the class had in mind? Maybe they wanted class users only to inspect the account? In such a situation, you should clone the object reference: public BankAccount getAccount(); {

bj4_ch10_7.fm Page 452 Wednesday, October 28, 2009 8:16 AM

452 Chapter 10 Inheritance return (BankAccount) account.clone(); }

Do you also need to clone the getName method? No—that method returns a string, and strings are immutable. It is safe to give out a reference to an immutable object.

Special Topic 10.6 Implementing the clone Method The Object.clone method is the starting point for the clone methods in your own classes. It creates a new object of the same type as the original object. It also automatically copies the instance variables from the original object to the cloned object. Here is a first attempt to implement the clone method for the BankAccount class: public class BankAccount { . . . public Object clone() { // Not complete Object clonedAccount = super.clone(); return clonedAccount; } }

However, this Object.clone method must be used with care. It only shifts the problem of cloning by one level; it does not completely solve it. Specifically, if an object contains a reference to another object, then the Object.clone method makes a copy of that object reference, not a clone of that object. The figure below shows how the Object.clone method works with a Customer object that has references to a String object and a BankAccount object. As you can see, the Object.clone method copies the references to the cloned Customer object and does not clone the objects to which they refer. Such a copy is called a shallow copy.

Customer

String g

name = account =

Customer name = account =

The Object.clone Method Makes a Shallow Copy

BankAccount balance =

10000

bj4_ch10_7.fm Page 453 Wednesday, October 28, 2009 8:16 AM

10.7 Object: The Cosmic Superclass 453 There is a reason why the Object.clone method does not systematically clone all subobjects. In some situations, it is unnecessary. For example, if an object contains a reference to a string, there is no harm in copying the string reference, because Java string objects can never change their contents. The Object.clone method does the right thing if an object contains only numbers, Boolean values, and strings. But it must be used with caution when an object contains references to other objects. For that reason, there are two safeguards built into the Object.clone method to ensure that it is not used accidentally. First, the method is declared protected (see Special Topic 10.3 on page 439). This prevents you from accidentally calling x.clone() if the class to which x belongs hasn’t declared clone to be public. As a second precaution, Object.clone checks that the object being cloned implements the Cloneable interface. If not, it throws an exception. The Object.clone method looks like this: public class Object { protected Object clone() throws CloneNotSupportedException { if (this instanceof Cloneable) { // Copy the instance variables . . . } else throw new CloneNotSupportedException(); } }

Unfortunately, all that safeguarding means that the legitimate callers of Object.clone() pay a price—they must catch that exception (see Chapter 11) even if their class implements Cloneable. public class BankAccount implements Cloneable { . . . public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { // Can’t happen because we implement Cloneable return null; } } }

but we still must catch it.

If an object contains a reference to another mutable object, then you must call clone for that reference. For example, suppose the Customer class has an instance variable of class BankAccount. You can implement Customer.clone as follows: public class Customer implements Cloneable { private String name; private BankAccount account; . . . public Object clone() { try {

bj4_ch10_7.fm Page 454 Wednesday, October 28, 2009 8:16 AM

454 Chapter 10 Inheritance Customer cloned = (Customer) super.clone(); cloned.account = (BankAccount) account.clone(); return cloned; } catch(CloneNotSupportedException e) { // Can’t happen because we implement Cloneable return null; } } }

Special Topic 10.7 Enumeration Types Revisited In Special Topic 5.3, we introduced the concept of an enumeration type: a type with a finite number of values. An example is public enum FilingStatus { SINGLE, MARRIED }

In Java, enumeration types are classes with special properties. They have a finite number of instances, namely the objects declared inside the braces. For example, there are exactly two objects of the FilingStatus class: FilingStatus.SINGLE and FilingStatus.MARRIED . Since FilingStatus has no public constructor, it is impossible to construct additional objects. Enumeration classes extend the Enum class, from which they inherit toString and clone methods. The toString method returns a string that equals the object’s name. For example, FilingStatus.SINGLE.toString() returns "SINGLE". The clone method returns the given object without making a copy. After all, it should not be possible to generate new objects of an enumeration class. The Enum class inherits the equals method from its superclass, Object. Thus, two enumeration constants are only considered equal when they are identical. You can add your own methods and constructors to an enumeration class, for example public enum CoinType { private double value; PENNY(0.01), NICKEL(0.05), DIME(0.1), QUARTER(0.25); CoinType(double aValue) { value = aValue; } public double getValue() { return value; } }

This CoinType class has exactly four instances: CoinType.PENNY, CoinType.NICKEL, CoinType.DIME, and CoinType.QUARTER . If you have one of these four CoinType objects, you can apply the getValue method to obtain the coin’s value. Note that there is a major philosophical difference between this CoinType class and the Coin class that we have discussed elsewhere in this chapter. A Coin object represents a particular coin. You can construct as many Coin objects as you like. Different Coin objects can be equal to another. We consider two Coin objects equal when their names and values match. However, CoinType describes a type of coins, not an individual coin. The four CoinType objects are distinct from each other.

bj4_ch10_7.fm Page 455 Wednesday, October 28, 2009 8:16 AM

10.7 Object: The Cosmic Superclass 455

Random Fact 10.1 Scripting Languages Suppose you work for an office where you must help with the bookkeeping. Suppose that every sales person sends in a weekly spreadsheet with sales figures. One of your jobs is to copy and paste the individual figures into a master spreadsheet and then copy and paste the totals into a word processor document that gets e-mailed to several managers. This kind of repetitive work can be intensely boring. Can you automate it? It would be a real challenge to write a Java program that can help you—you’d have to know how to read a spreadsheet file, how to format a word processor document, and how to send e-mail. Fortunately, many office software packages include scripting languages. These are programming languages that are integrated with the software for the purpose of automating repetitive tasks. The best-known of these scripting languages is Visual Basic Script, which is a part of the Microsoft Office suite. The Macintosh operating system has a language called AppleScript for the same purpose. In addition, scripting languages are available for many other purposes. JavaScript is used for web pages. (There is no relationship between Java and JavaScript—the name JavaScript was chosen for marketing reasons.) Tcl (short for “tool control language” and pronounced “tickle”) is an open source scripting language that has been ported to many platforms and is often used for scripting software test procedures. Shell scripts are used for automating software configuration, backup procedures, and other system administration tasks. Scripting languages have two features that makes them easier to use than full-fledged programming languages such as Java. First, they are interpreted. The interpreter program reads each line of program code and executes it immediately without compiling it first. That makes experimenting much more fun—you get immediate feedback. Also, scripting languages are usually loosely typed, meaning you don’t have to declare the types of variables. Every variable can hold values of any type. For example, the figure below shows a scripting session with the JavaScript implementation that is included in the Java Development Kit.

Scripting Java Classes with JavaScript

bj4_ch10_7.fm Page 456 Wednesday, October 28, 2009 8:16 AM

456 Chapter 10 Inheritance

Graphics Track

This version of JavaScript allows you to manipulate Java objects. The script stores frame and label objects in variables that are declared without types. It then calls methods that are executed immediately, without compilation. The frame pops up as soon as the line with the setVisible command is entered. In recent years, authors of computer viruses have discovered how scripting languages simplify their lives. The famous “love bug” is a Visual Basic Script program that is sent as an attachment to an e-mail. The e-mail has an enticing subject line “I love you” and asks the recipient to click on an attachment masquerading as a love letter. In fact, the attachment is a script file that is executed when the user clicks on it. The script creates some damage on the recipient’s computer and then, through the power of the scripting language, uses the Outlook e-mail client to mail itself to all addresses found in the address book. Try programming that in Java! By the way, the person suspected of authoring that virus was a student who had submitted a proposal to write a thesis researching how to write such programs. Perhaps not surprisingly, the proposal was rejected by the faculty. Why do we still need Java if scripting is easy and fun? Scripts often have poor error checking and are difficult to adapt to new circumstances. Scripting languages lack many of the structuring and safety mechanisms (such as classes and type checking by the compiler) that are important for building robust and scalable programs.

10.8 Using Inheritance to Customize Frames Provide a JFrame subclass for a complex frame.

As you add more user-interface components to a frame, the frame can get quite complex. Your programs will become easier to understand when you use inheritance for complex frames. To do so, design a subclass of JFrame. Store the components as instance variables. Initialize them in the constructor of your subclass. If the initialization code gets complex, simply add some helper methods. Here, we carry out this process for the investment viewer program in Chapter 9. public class InvestmentFrame extends JFrame { private JButton button; private JLabel label; private JPanel panel; private BankAccount account; public InvestmentFrame() { account = new BankAccount(INITIAL_BALANCE); // Use instance variables for components label = new JLabel("balance: " + account.getBalance()); // Use helper methods createButton(); createPanel(); setSize(FRAME_WIDTH, FRAME_HEIGHT); } private void createButton() {

bj4_ch10_7.fm Page 457 Thursday, November 5, 2009 1:53 PM

10.8 Using Inheritance to Customize Frames 457

Graphics Track

button = new JButton("Add Interest"); ActionListener listener = new AddInterestListener(); button.addActionListener(listener); } private void createPanel() { panel = new JPanel(); panel.add(button); panel.add(label); add(panel); } . . . }

This approach differs from the programs in Chapter 9. In those programs, we simply configured the frame in the main method of a viewer class. It is a bit more work to provide a separate class for the frame. However, the frame class makes it easier to organize the code that constructs the user-interface elements. Of course, we still need a class with a main method: public class InvestmentViewer2 { public static void main(String[] args) { JFrame frame = new InvestmentFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }

SELF CHECK

17. 18.

How many Java source files are required by the investment viewer application when we use inheritance to declare the frame class? Why does the InvestmentFrame constructor call setSize(FRAME_WIDTH, FRAME_HEIGHT), whereas the main method of the investment viewer class in Chapter 9 called frame.setSize(FRAME_WIDTH, FRAME_HEIGHT) ?

Special Topic 10.8 Adding the main Method to the Frame Class Have another look at the InvestmentFrame and InvestmentViewer2 classes. Some programmers prefer to combine these two classes, by adding the main method to the frame class: public class InvestmentFrame extends JFrame { public static void main(String[] args) { JFrame frame = new InvestmentFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } public InvestmentFrame() { account = new BankAccount(INITIAL_BALANCE);

bj4_ch10_7.fm Page 458 Wednesday, October 28, 2009 8:16 AM

458 Chapter 10 Inheritance

Graphics Track

// Use instance variables for components label = new JLabel("balance: " + account.getBalance()); // Use helper methods createButton(); createPanel(); setSize(FRAME_WIDTH, FRAME_HEIGHT); } . . . }

This is a convenient shortcut that you will find in many programs, but it does muddle the responsibilities between the frame class and the program. Therefore, we do not use this approach in this book.

Summary of Learning Objectives Explain the notions of inheritance, superclasses, and subclasses.

• Sets of classes can form complex inheritance hierarchies. Implement subclasses in Java.

• Inheritance is a mechanism for extending existing classes by adding instance • • • • •

variables and methods. A subclass inherits the methods of its superclass. The instance variables declared in the superclass are present in subclass objects. A subclass has no access to private instance variables of its superclass. The more general class is called a superclass. The more specialized class that inherits from the superclass is called the subclass. Inheriting from a class differs from implementing an interface: The subclass inherits behavior from the superclass.

Describe how a subclass can override methods from its superclass.

• A subclass can inherit a superclass method or override it by providing another

implementation. • Use the super reserved word to call a method of the superclass. Describe how a subclass can construct its superclass.

• To call the superclass constructor, you use the super reserved word in the first

statement of the subclass constructor. Describe how to convert between class and superclass types.

• Subclass references can be converted to superclass references. • The instanceof operator tests whether an object belongs to a particular type. Describe dynamic method lookup and polymorphism.

• When the virtual machine calls an instance method, it locates the method of the

implicit parameter’s class. This is called dynamic method lookup. • An abstract method is a method whose implementation is not specified.

bj4_ch10_7.fm Page 459 Wednesday, October 28, 2009 8:16 AM

Review Exercises 459 • An abstract class is a class that cannot be instantiated. • Protected features can be accessed by all subclasses and by all classes in the same

package. Provide appropriate overrides of the methods of the Object superclass.

• • • •

Every class extends the Object class either directly or indirectly. In your classes, provide toString methods that describe each object’s state. When implementing the equals method, test whether two objects have equal state. The clone method makes a new object with the same state as an existing object.

Use inheritance to customize frames.

• Provide a JFrame subclass for a complex frame.

Classes, Objects, and Methods Introduced in this Chapter java.lang.Cloneable java.lang.CloneNotSupportedException

java.lang.Object clone toString

Media Resources • Worked Example Implementing an Employee Hierarchy for Payroll Processing • Lab Exercises www.wiley.com/ college/ horstmann

Animation Inheritance Practice Quiz Code Completion Exercises

Review Exercises R10.1 What is the balance of b after the following operations? SavingsAccount b = new SavingsAccount(10); b.deposit(5000); b.withdraw(b.getBalance() / 2); b.addInterest();

R10.2 Describe all constructors of the SavingsAccount class. List all methods that are inher-

ited from the BankAccount class. List all methods that are added to the SavingsAccount class. R10.3 Can you convert a superclass reference into a subclass reference? A subclass refer-

ence into a superclass reference? If so, give examples. If not, explain why not.

bj4_ch10_7.fm Page 460 Wednesday, October 28, 2009 8:16 AM

460 Chapter 10 Inheritance R10.4 Identify the superclass and the subclass in each of the following pairs of classes. a. Employee, Manager b. Polygon, Triangle c. GraduateStudent, Student d. Person, Student e. Employee, GraduateStudent f. BankAccount, CheckingAccount g. Vehicle, Car h. Vehicle, Minivan i. Car, Minivan j. Truck, Vehicle

R10.5 Suppose the class Sub extends the class Sandwich. Which of the following assignments

are legal? Sandwich x = new Sandwich(); Sub y = new Sub();

a. x b. y c. y d. x

= y; = x; = new Sandwich(); = new Sub();

R10.6 Draw an inheritance diagram that shows the inheritance relationships between the

classes: • Person • Employee • Student

• • •

Instructor Classroom Object

R10.7 In an object-oriented traffic simulation system, we have the following classes:

• • • • •

Vehicle Car Truck Sedan Coupe

• • • • •

PickupTruck SportUtilityVehicle Minivan Bicycle Motorcycle

Draw an inheritance diagram that shows the relationships between these classes. R10.8 What inheritance relationships would you establish among the following classes?

• • • • • • •

Student Professor TeachingAssistant Employee Secretary DepartmentChair Janitor

• • • • • •

SeminarSpeaker Person Course Seminar Lecture ComputerLab

bj4_ch10_7.fm Page 461 Wednesday, October 28, 2009 8:16 AM

Review Exercises 461 R10.9 Which of these conditions returns true? Check the Java documentation for the

inheritance patterns. a. Rectangle r = new Rectangle(5, 10, 20, 30); b. if (r instanceof Rectangle) . . . c. if (r instanceof Point) . . . d. if (r instanceof Rectangle2D.Double) . . . e. if (r instanceof RectangularShape) . . . f. if (r instanceof Object) . . . g. if (r instanceof Shape) . . .

R10.10 Explain the two meanings of the super reserved word. Explain the two meanings of

the this reserved word. How are they related? R10.11 (Tricky.) Consider the two calls public class D extends B { public void f() { this.g(); // 1 } public void g() { super.g(); // 2 } . . . }

Which of them is an example of polymorphism? R10.12 Consider this program: public class AccountPrinter { public static void main(String[] args) { SavingsAccount momsSavings = new SavingsAccount(0.5); CheckingAccount harrysChecking = new CheckingAccount(0); . . . endOfMonth(momsSavings); endOfMonth(harrysChecking); printBalance(momsSavings); printBalance(harrysChecking); } public static void endOfMonth(SavingsAccount savings) { savings.addInterest(); } public static void endOfMonth(CheckingAccount checking) { checking.deductFees(); }

bj4_ch10_7.fm Page 462 Wednesday, October 28, 2009 8:16 AM

462 Chapter 10 Inheritance

public static void printBalance(BankAccount account) { System.out.println("The balance is $" + account.getBalance()); } }

Do the calls to the endOfMonth methods use dynamic method invocation? Inside the printBalance method, does the call to getBalance use dynamic method invocation? R10.13 Explain the terms shallow copy and deep copy. R10.14 What access attribute should instance variables have? What access attribute should

static variables have? How about static final variables? R10.15 What access attribute should instance methods have? Does the same hold for static

methods? R10.16 The static variables System.in and System.out are public. Is it possible to overwrite

them? If so, how? R10.17 Why are public instance variables dangerous? Are public static variables more dan-

gerous than public instance variables?

Programming Exercises P10.1 Enhance the addInterest method of the SavingsAccount class to compute the interest

on the minimum balance since the last call to addInterest. Hint: You need to modify the withdraw method as well, and you need to add an instance variable to remember the minimum balance. P10.2 Add a TimeDepositAccount class to the bank account hierarchy. The time deposit

account is just like a savings account, but you promise to leave the money in the account for a particular number of months, and there is a $20 penalty for early withdrawal. Construct the account with the interest rate and the number of months to maturity. In the addInterest method, decrement the count of months. If the count is positive during a withdrawal, charge the withdrawal penalty. P10.3 Add a class NumericQuestion to the question hierarchy of How To 10.1. If the

response and the expected answer differ by no more than 0.01, then accept it as correct. P10.4 Add a class FillInQuestion to the question hierarchy of How To 10.1. An object of

this class is constructed with a string that contains the answer, surrounded by _ _, for example, "The inventor of Java was _James Gosling_" . The question should be displayed as The inventor of Java was _____

P10.5 Modify the checkAnswer method of the Question class of How To 10.1 so that it does

not take into account different spaces or upper/lowercase characters. For example, the response " JAMES gosling" should match an answer of "James Gosling".

bj4_ch10_7.fm Page 463 Wednesday, October 28, 2009 8:16 AM

Programming Exercises 463 P10.6 Add a class MultiChoiceQuestion to the question hierarchy of How To 10.1 that allows

multiple correct choices. The respondent should provide all correct choices, separated by spaces. Provide instructions in the question text. P10.7 Add a class AnyCorrectChoiceQuestion to the question hierarchy of How To 10.1 that

allows multiple correct choices. The respondent should provide any one of the correct choices. The answer string should contain all of the correct choices, separated by spaces. P10.8 Add a method addText to the Question class of How To 10.1 and provide a different

implementation of ChoiceQuestion that calls addText rather than storing an array list of choices. P10.9 Provide toString and equals methods for the Question and ChoiceQuestion classes of

How To 10.1. P10.10 Implement a subclass Square that extends the Rectangle class. In the constructor,

accept the x- and y-positions of the center and the side length of the square. Call the and setSize methods of the Rectangle class. Look up these methods in the documentation for the Rectangle class. Also supply a method getArea that computes and returns the area of the square. Write a sample program that asks for the center and side length, then prints out the square (using the toString method that you inherit from Rectangle) and the area of the square. setLocation

P10.11 Implement a superclass Person. Make two classes, Student and Instructor, that inherit

from Person. A person has a name and a year of birth. A student has a major, and an instructor has a salary. Write the class declarations, the constructors, and the methods toString for all classes. Supply a test program that tests these classes and methods. P10.12 Make a class Employee with a name and salary. Make a class Manager inherit from Employee. Add an instance variable, named department, of type String. Supply a method toString that prints the manager’s name, department, and salary. Make a class Executive inherit from Manager. Supply appropriate toString methods for all classes. Supply a test program that tests these classes and methods.

P10.13 Reorganize the bank account classes as follows. In the BankAccount class, introduce

an abstract method endOfMonth with no implementation. Rename the addInterest and methods into endOfMonth in the subclasses. Which classes are now abstract and which are concrete? Write a static method void test(BankAccount account) that makes five transactions and then calls endOfMonth. Test it with instances of all concrete account classes.

deductFees

G P10.14 Implement an abstract class Vehicle and concrete subclasses Car and Truck. A vehicle

has a position on the screen. Write methods draw that draw cars and trucks as follows:

Car

Truck

bj4_ch10_7.fm Page 464 Wednesday, October 28, 2009 8:16 AM

464 Chapter 10 Inheritance

Then write a method randomVehicle that randomly generates Vehicle references, with an equal probability for constructing cars and trucks, with random positions. Call it 10 times and draw all of them. G P10.15 Write a program that prompts the user for an integer, using a JOptionPane, and then

draws as many rectangles at random positions in a component as the user requested. Use inheritance for your frame class. G P10.16 Write a program that asks the user to enter an integer n into a JOptionPane, and then

draws an n-by-n grid. Use inheritance for the frame class.

Programming Projects Project 10.1 Your task is to program robots with varying behaviors. The robots try to escape a

maze, such as the following: * ******* * * * * ***** * * * * * * * *** * * * * *** * * * * * * ******* *

A robot has a position and a method void move(Maze m) that modifies the position. Provide a common superclass Robot whose move method does nothing. Provide subclasses RandomRobot, RightHandRuleRobot, and MemoryRobot. Each of these robots has a different strategy for escaping. The RandomRobot simply makes random moves. The RightHandRuleRobot moves around the maze so that it’s right hand always touches a wall. The MemoryRobot remembers all positions that it has previously occupied and never goes back to a position that it knows to be a dead end. Project 10.2 Implement the toString, equals, and clone methods for all subclasses of the BankAc-

class, as well as the Bank class of Chapter 7. Write unit tests that verify that your methods work correctly. Be sure to test a Bank that holds objects from a mixture of account classes.

count

bj4_ch10_7.fm Page 465 Wednesday, October 28, 2009 8:16 AM

Answers to Self-Check Questions 465

Answers to Self-Check Questions 1. To express the common behavior of text fields and text components. 2. Not all bank accounts earn interest. 3. Two instance variables: balance and interestRate. 4. deposit, withdraw, getBalance, and addInterest. 5. Manager is the subclass; Employee is the superclass. 6. The SavingsAccount class inherits the deposit, withdraw, and getBalance methods. The addInterest

method is new. No methods override superclass methods.

7. It needs to reduce the balance, and it cannot access the balance instance variable 8. 9. 10.

11.

12. 13. 14. 15. 16.

17. 18.

directly. So that the count can reflect the number of transactions for the following month. It was content to use the superclass constructor without parameters, which sets the balance to zero. No—this is a requirement only for constructors. For example, the CheckingAccount.deposit method first increments the transaction count, then calls the superclass method. We want to use the method for all kinds of bank accounts. Had we used a parameter of type SavingsAccount, we couldn’t have called the method with a CheckingAccount object. We cannot invoke the deposit method on a variable of type Object. The object is an instance of BankAccount or one of its subclasses. The balance of a is unchanged (you withdraw from and deposit to the same account), and the transaction count is incremented twice. It certainly should—unless, of course, x is null. If toString returns a string that describes all instance variables, you can simply call toString on the implicit and explicit parameters, and compare the results. However, comparing the instance variables is more efficient than converting them into strings. Three: InvestmentFrameViewer, InvestmentFrame, and BankAccount. The InvestmentFrame constructor adds the panel to itself.

bj4_ch10_7.fm Page 466 Wednesday, October 28, 2009 8:16 AM

bj4_ch11_7.fm Page 467 Thursday, October 29, 2009 1:50 PM

11

Chapter

Input/Output and Exception Handling

CHAPTER GOALS • To be able to read and write text files • To learn how to throw and catch exceptions • To be able to design your own exception classes • To understand the difference between checked and unchecked exceptions

• To know when and where to catch an exception

This chapter starts with a discussion of file input and output. Whenever you read or write >link text

Throw an exception if you find a malformed hyperlink. Extra credit if your program can follow the links that it finds and find links in those web pages as well. (This is the method that search engines such as Google use to find web sites.)

Answers to Self-Check Questions 1. When the PrintWriter object is created, the output file is emptied. Sadly, that is the

2. 3. 4. 5.

same file as the input file. The input file is now empty and the while loop exits immediately. The Scanner constructor throws a FileNotFoundException, and the program terminates. number is 6, input is ",995.0" price is set to 6 because the comma is not considered a part of a floating-point number in Java. Then the call to nextInt causes an exception, and quantity is not set. Read them as strings, and convert those strings to numbers that are not equal to N/A: String input = in.next(); if (!input.equals("N/A")) { double value = Double.parseDouble(input); Process value }

6. Throw an exception if the amount being deposited is less than zero. 7. The balance is still zero because the last statement of the withdraw method was never 8.

9. 10.

11.

executed. You must include the FileNotFoundException and you may include the NoSuchElementException if you consider it important for documentation purposes. InputMismatchException is a subclass of NoSuchElementException. It is your choice whether to include it. Because programmers should simply check for null pointers instead of trying to handle a NullPointerException. The Scanner constructor succeeds, and in is constructed. Then the call in.next() throws a NoSuchElementException, and the try block is aborted. None of the catch clauses match, so none are executed. If none of the enclosing method calls catch the exception, the program terminates. No—you catch both exception types in the same way, as you can see from the code example on page 485. Recall that IOException is a checked exception and NumberFormatException is an unchecked exception.

bj4_ch11_7.fm Page 503 Thursday, October 29, 2009 1:50 PM

Answers to Self-Check Questions 503 12. If it had been declared inside the try block, its scope would only have extended to

the end of the try block, and the finally clause could not have closed it. 13. The PrintWriter constructor throws an exception. The assignment to out and the try

14. 15.

16.

17.

block are skipped. The finally clause is not executed. This is the correct behavior because out has not been initialized. To pass the exception message string to the RuntimeException superclass. Because file corruption is beyond the control of the programmer, this should be a checked exception, so it would be wrong to extend RuntimeException or IllegalArgumentException. Because the error is related to input, IOException would be a good choice. It would not be able to do much with them. The A=Deposit, B=Withdrawal, C=Cancel: "); String command = in.next(); if (command.equalsIgnoreCase("A")) { System.out.print("Amount: "); double amount = in.nextDouble(); theATM.deposit(amount); theATM.back(); } else if (command.equalsIgnoreCase("B")) { System.out.print("Amount: "); double amount = in.nextDouble();

bj4_ch12_7.fm Page 543 Thursday, October 29, 2009 2:36 PM

12.5 Case Study: An Automatic Teller Machine 543

70 71 72 73 74 75 76 77 78 79 80

theATM.withdraw(amount); theATM.back(); } else if (command.equalsIgnoreCase("C")) theATM.back(); else System.out.println("Illegal input!"); } } } }

Program Run Enter account number: 1 Enter PIN: 1234 A=Checking, B=Savings, C=Quit: A Balance=0.0 A=Deposit, B=Withdrawal, C=Cancel: A Amount: 1000 A=Checking, B=Savings, C=Quit: C . . .

Here are the user interface classes for the GUI version of the user interface. ch12/atm/ATMViewer.java 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

import java.io.IOException; import javax.swing.JFrame; import javax.swing.JOptionPane; /**

A graphical simulation of an automatic teller machine. */ public class ATM Viewer { public static void main(String[] args) { ATM theATM; try { Bank theBank = new Bank(); theBank.readCustomers("customers.txt"); theATM = new ATM(theBank); } catch(IOException e) { JOptionPane.showMessageDialog(null, "Error opening accounts file."); return; } JFrame frame = new ATMFrame(theATM); frame.setTitle("First National Bank of Java"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }

bj4_ch12_7.fm Page 544 Thursday, October 29, 2009 2:36 PM

544 Chapter 12 Object-Oriented Design ch12/atm/ATMFrame.java 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 51 52 53 54 55 56 57

import import import import import import import import

java.awt.FlowLayout; java.awt.GridLayout; java.awt.event.ActionEvent; java.awt.event.ActionListener; javax.swing.JButton; javax.swing.JFrame; javax.swing.JPanel; javax.swing.JTextArea;

/**

A frame displaying the components of an ATM. */ public class ATMFrame extends JFrame { private static final int FRAME_WIDTH = 300; private static final int FRAME_HEIGHT = 300; private JButton aButton; private JButton bButton; private JButton cButton; private KeyPad pad; private JTextArea display; private ATM theATM; /**

Constructs the user interface of the ATM frame. */ public ATMFrame(ATM anATM) { theATM = anATM; // Construct components pad = new KeyPad(); display = new JTextArea(4, 20); aButton = new JButton(" A "); aButton.addActionListener(new AButtonListener()); bButton = new JButton(" B "); bButton.addActionListener(new BButtonListener()); cButton = new JButton(" C "); cButton.addActionListener(new CButtonListener()); // Add components JPanel buttonPanel = new JPanel(); buttonPanel.add(aButton); buttonPanel.add(bButton); buttonPanel.add(cButton); setLayout(new FlowLayout()); add(pad); add(display);

bj4_ch12_7.fm Page 545 Thursday, October 29, 2009 2:36 PM

12.5 Case Study: An Automatic Teller Machine 545

58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115

add(buttonPanel); showState(); setSize(FRAME_WIDTH, FRAME_HEIGHT); } /**

Updates display message. */ public void showState() { int state = theATM.getState(); pad.clear(); if (state == ATM.START) display.setText("Enter customer number\nA = OK"); else if (state == ATM.PIN) display.setText("Enter PIN\nA = OK"); else if (state == ATM.ACCOUNT) display.setText("Select Account\n" + "A = Checking\nB = Savings\nC = Exit"); else if (state == ATM.TRANSACT) display.setText("Balance = " + theATM.getBalance() + "\nEnter amount and select transaction\n" + "A = Withdraw\nB = Deposit\nC = Cancel"); } class AButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { int state = theATM.getState(); if (state == ATM.START) theATM.setCustomerNumber((int) pad.getValue()); else if (state == ATM.PIN) theATM.selectCustomer((int) pad.getValue()); else if (state == ATM.ACCOUNT) theATM.selectAccount(ATM.CHECKING); else if (state == ATM.TRANSACT) { theATM.withdraw(pad.getValue()); theATM.back(); } showState(); } } class BButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { int state = theATM.getState(); if (state == ATM.ACCOUNT) theATM.selectAccount(ATM.SAVINGS); else if (state == ATM.TRANSACT) { theATM.deposit(pad.getValue()); theATM.back();

bj4_ch12.fm Page 546 Sunday, November 15, 2009 4:21 PM

546 Chapter 12 Object-Oriented Design

116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133

} showState(); } } class CButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { int state = theATM.getState(); if (state == ATM.ACCOUNT) theATM.reset(); else if (state == ATM.TRANSACT) theATM.back(); showState(); } } }

This class uses layout managers to arrange the text field and the keypad buttons. See Chapter 18 for more information about layout managers. ch12/atm/KeyPad.java 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

import import import import import import import

java.awt.BorderLayout; java.awt.GridLayout; java.awt.event.ActionEvent; java.awt.event.ActionListener; javax.swing.JButton; javax.swing.JPanel; javax.swing.JTextField;

/**

A component that lets the user enter a number, using a keypad labeled with digits. */ public class KeyPad extends JPanel { private JPanel buttonPanel; private JButton clearButton; private JTextField display; /**

Constructs the keypad panel. */ public KeyPad() { setLayout(new BorderLayout()); // Add display field display = new JTextField(); add(display, "North"); // Make button panel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(4, 3));

bj4_ch12_7.fm Page 547 Thursday, October 29, 2009 2:36 PM

12.5 Case Study: An Automatic Teller Machine 547

35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92

// Add digit buttons addButton("7"); addButton("8"); addButton("9"); addButton("4"); addButton("5"); addButton("6"); addButton("1"); addButton("2"); addButton("3"); addButton("0"); addButton("."); // Add clear entry button clearButton = new JButton("CE"); buttonPanel.add(clearButton); class ClearButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { display.setText(""); } } ActionListener listener = new ClearButtonListener(); clearButton.addActionListener(new ClearButtonListener()); add(buttonPanel, "Center"); } /**

Adds a button to the button panel. @param label the button label */ private void addButton(final String label) { class DigitButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { // Don’t add two decimal points if (label.equals(".") && display.getText().indexOf(".") != -1) return; // Append label text to button display.setText(display.getText() + label); } } JButton button = new JButton(label); buttonPanel.add(button);

bj4_ch12_7.fm Page 548 Thursday, October 29, 2009 2:36 PM

548 Chapter 12 Object-Oriented Design

93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113

ActionListener listener = new DigitButtonListener(); button.addActionListener(listener); } /**

Gets the value that the user entered. @return the value in the text field of the keypad */ public double getValue() { return Double.parseDouble(display.getText()); } /**

Clears the display. */ public void clear() { display.setText(""); } }

In this chapter, you learned a systematic approach for building a relatively complex program. However, object-oriented design is definitely not a spectator sport. To really learn how to design and implement programs, you have to gain experience by repeating this process with your own projects. It is quite possible that you don’t immediately home in on a good solution and that you need to go back and reorganize your classes and responsibilities. That is normal and only to be expected. The purpose of the object-oriented design process is to spot these problems in the design phase, when they are still easy to rectify, instead of in the implementation phase, when massive reorganization is more difficult and time consuming. SELF CHECK

12. 13.

Why does the Bank class in this example not store an array list of bank accounts? Suppose the requirements change—you need to save the current account balances to a file after every transaction and reload them when the program starts. What is the impact of this change on the design?

Random Fact 12.2 Software Development—Art or Science? There has been a long discussion whether the discipline of computing is a science or not. We call the field “computer science”, but that doesn’t mean much. Calling a discipline a science doesn’t automatically make it so. A scientific discipline operates on the scientific method: by posing hypotheses and testing them with experiments that are repeatable by other workers in the field. For example, a physicist may have a theory on the makeup of nuclear particles and attempt to confirm or refute that theory by running experiments in a particle collider. If an experiment cannot be confirmed, such as the “cold fusion” research in the early 1990s, then the theory dies a quick death.

bj4_ch12_7.fm Page 549 Thursday, October 29, 2009 2:36 PM

Summary of Learning Objectives 549 Some software developers indeed run experiments. They try out various methods of computing certain results or of configuring computer systems, and measure the differences in performance. Some computer scientists discover fundamental principles. One class of fundamental results, for instance, states that it is impossible to write certain kinds of computer programs, no matter how powerful the computing equipment is. For example, it is impossible to write a program that takes as its input any two Java program files and as its output prints whether or not these two programs always compute the same results. Such a program would be very handy for grading student homework, but nobody, no matter how clever, will ever be able to write one that works for all input files. However, the majority of computer scientists are not researching the limits of computation. Some people view software development as an art or craft. A programmer who writes elegant code that is easy to understand and runs with optimum efficiency can indeed be considered a good craftsman. Calling it an art is perhaps far-fetched, because an art object requires an audience to appreciate it, whereas the program code is generally hidden from the program user. Others call software development an engineering discipline. Just as mechanical engineering is based on the fundamental mathematical principles of statics, computing has certain mathematical foundations. There is more to mechanical engineering than mathematics, such as knowledge of materials and of project planning. The same is true for computing. A software engineer needs to know about planning, budgeting, design, test automation, documentation, and source code control, in addition to computer science subjects, such as programming, algorithm design, and Hello!"); greeting.reverse(); System.out.println(greeting.getText());

prints the string "!olleH". Implement a recursive solution by removing the first character, reversing a sentence consisting of the remaining text, and combining the two. P13.2 Redo Exercise P13.1 with a recursive helper method that reverses a substring of the

message text.

bj4_ch13_7.fm Page 587 Friday, October 30, 2009 9:39 AM

Programming Exercises 587 P13.3 Implement the reverse method of Exercise P13.1 as an iteration. P13.4 Use recursion to implement a method boolean find(String t) that tests whether a

string is contained in a sentence: Sentence s = new Sentence("Mississippi!"); boolean b = s.find("sip"); // Returns true

Hint: If the text starts with the string you want to match, then you are done. If not, consider the sentence that you obtain by removing the first character. P13.5 Use recursion to implement a method int indexOf(String t) that returns the starting

position of the first substring of the text that matches t. Return –1 if t is not a substring of s. For example, Sentence s = new Sentence("Mississippi!"); int n = s.indexOf("sip"); // Returns 6

Hint: This is a bit trickier than the preceding problem, because you must keep track of how far the match is from the beginning of the sentence. Make that value a parameter of a helper method. P13.6 Using recursion, find the largest element in an array. public class ,name=" + name + "]"; } }

ch16/hashcode/CoinHashCodePrinter.java 1 2 3 4 5 6 7 8 9 10

import java.util.HashSet; import java.util.Set; /**

A program that prints hash codes of coins. */ public class CoinHashCodePrinter { public static void main(String[] args) {

bj4_ch16_7.fm Page 685 Friday, October 30, 2009 3:44 PM

16.4 Computing Hash Codes 685

11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

Coin coin1 = new Coin(0.25, "quarter"); Coin coin2 = new Coin(0.25, "quarter"); Coin coin3 = new Coin(0.05, "nickel"); System.out.println("hash code of coin1=" + coin1.hashCode()); System.out.println("hash code of coin2=" + coin2.hashCode()); System.out.println("hash code of coin3=" + coin3.hashCode()); Set coins = new HashSet(); coins.add(coin1); coins.add(coin2); coins.add(coin3); for (Coin c : coins) System.out.println(c); } }

Program Run hash code of coin1=-1513525892 hash code of coin2=-1513525892 hash code of coin3=-1768365211 Coin[value=0.25,name=quarter] Coin[value=0.05,name=nickel]

SELF CHECK

9. 10.

What is the hash code of the string "to"? What is the hash code of new Integer(13)?

Common Error 16.1 Forgetting to Provide hashCode When putting elements into a hash table, make sure that the hashCode method is provided. (The only exception is that you don’t need to provide hashCode if equals isn’t provided either. In that case, distinct objects of your class are considered different, even if they have matching contents.) If you forget to implement the hashCode method, then you inherit the hashCode method of the Object class. That method computes a hash code of the memory location of the object. For example, suppose that you do not provide the hashCode method of the Coin class. Then the following code is likely to fail: Set coins = new HashSet(); coins.add(new Coin(0.25, "quarter")); // The following comparison will probably fail if hashCode if (coins.contains(new Coin(0.25, "quarter")) System.out.println("The set contains a quarter.");

not provided

The two Coin objects are constructed at different memory locations, so the hashCode method of the Object class will probably compute different hash codes for them. (As always with hash codes, there is a small chance that the hash codes happen to collide.) Then the contains method will inspect the wrong bucket and never find the matching coin. The remedy is to provide a hashCode method in the Coin class.

bj4_ch16_7.fm Page 686 Friday, October 30, 2009 3:44 PM

686 Chapter 16 Advanced , description=" + description; } public int compareTo(Object otherObject) { WorkOrder other = (WorkOrder) otherObject; if (priority < other.priority) return -1; if (priority > other.priority) return 1; return 0; } }

bj4_ch16_7.fm Page 709 Friday, October 30, 2009 3:44 PM

16.9 The Heapsort Algorithm 709 ch16/pqueue/HeapDemo.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

/**

This program demonstrates the use of a heap as a priority queue. */ public class HeapDemo { public static void main(String[] args) { MinHeap q = new MinHeap(); q.add(new WorkOrder(3, "Shampoo carpets")); q.add(new WorkOrder(7, "Empty trash")); q.add(new WorkOrder(8, "Water plants")); q.add(new WorkOrder(10, "Remove pencil sharpener shavings")); q.add(new WorkOrder(6, "Replace light bulb")); q.add(new WorkOrder(1, "Fix broken sink")); q.add(new WorkOrder(9, "Clean coffee maker")); q.add(new WorkOrder(2, "Order cleaning supplies")); while (q.size() > 0) System.out.println(q.remove()); } }

Program Run priority=1, description=Fix broken sink priority=2, description=Order cleaning supplies priority=3, description=Shampoo carpets priority=6, description=Replace light bulb priority=7, description=Empty trash priority=8, description=Water plants priority=9, description=Clean coffee maker priority=10, description=Remove pencil sharpener shavings

SELF CHECK

15.

16.

The software that controls the events in a user interface keeps the events in a />

When the parser sees the />, it knows not to look for a matching end-tag. • Finally, attribute values must be enclosed in quotes. For example,

is not acceptable. You must use

XML describes the meaning of ?>

Next, the XML document contains the actual ?>

more > . . .

Elements can have attributes. Use attributes to describe how to interpret the element content.

An attribute has a name (such as href) and a value. In XML, the value must be enclosed in single or double quotes. An element can have multiple attributes, for example

And, as you have already seen, an element can have both attributes and content. Sun's Java web site

Programmers often wonder whether it is better to use attributes or child elements. For example, should a product be described as

or

bj4_ch23_7.fm Page 909 Tuesday, November 3, 2009 4:09 PM

23.1 XML Tags and Documents 909 Toaster 29.95

The former is shorter. However, it violates the spirit of attributes. Attributes are intended to provide information about the element content. For example, the price element might have an attribute currency that helps interpret the element content. The content 29.95 has a different interpretation in the element 29.95

than it does in the element 29.95

You have now seen the components of an XML document that are needed to use XML for encoding price="29.95"/>

seems simpler than Toaster 29.95

There is the temptation to use attributes because they are “easier to type”. But of course, you don’t type XML documents, except for testing purposes. In real-world situations, XML documents are generated by programs. Attributes are less flexible than elements. Suppose we want to add a currency indication to the value. With elements, that’s easy to do: 29.95

or even USD 29.95

With attributes, you are stuck—you can’t refine the structure. Of course, you could use

But then your program has to parse the string USD 29.95 and manually take it apart. That’s just the kind of tedious and error-prone coding that XML is designed to avoid.

bj4_ch23_7.fm Page 912 Tuesday, November 3, 2009 4:09 PM

912 Chapter 23 XML In HTML, there is a simple rule when using attributes. All strings that are not part of the displayed text are attributes. For example, consider a link. The Java web page

The text inside the a element, The Java web page , is part of what the user sees on the web page, but the href attribute value http://java.sun.com is not displayed on the page. Of course, HTML is a little different from the XML documents that you construct to describe ?> Ink Jet Refill Kit 29.95 8 4-port Mini Hub 19.95 4 Figure 3

An XML Document

bj4_ch23_7.fm Page 916 Tuesday, November 3, 2009 4:09 PM

916 Chapter 23 XML









Ink Jet Refill Kit

29.95

Figure 4

8





4-port Mini Hub

19.95

4

The Tree View of the Document

This XPath selects the quantity of the first item, that is, the value 8. (In XPath, array positions start with 1. Accessing /items/item[0] would be an error.) Similarly, you can get the price of the second product as /items/item[2]/product/price

To get the number of items, use the XPath expression count(/items/item)

In our example, the result is 2. The total number of children can be obtained as count(/items/*)

In our example, the result is again 2 because the items element has exactly two children. To select attributes, use an @ followed by the name of the attribute. For example, /items/item[2]/product/price/@currency

would select the currency price attribute if it had one. Finally, if you have a document with variable or unknown structure, you can find out the name of a child with an expression such as the following: name(/items/item[1]/*[1])

The result is the name of the first child of the first item, or product. That is all you need to know about the XPath syntax to analyze simple documents. (See Table 1 for a summary.) There are many more options in the XPath syntax that we do not cover here. If you are interested, look up the specification (http:/ /www.w3.org/TR/xpath) or work through the online tutorial (http://www.zvon.org/xxl/ XPathTutorial/General/examples.html ). To evaluate an XPath expression in Java, first create an XPath object: XPathFactory xpfactory = XPathFactory.newInstance(); XPath path = xpfactory.newXPath();

Then call the evaluate method, like this: String result = path.evaluate( expression, doc)

bj4_ch23_7.fm Page 917 Tuesday, November 3, 2009 4:09 PM

23.2 Parsing XML Documents 917

Table 1 XPath Syntax Summary Syntax Element

Purpose

Example

name

Matches an element

item

/

Separates elements

/items/item

[n]

Selects a value from a set

/items/item[1]

@name

Matches an attribute

price/@currency

*

Matches anything

/items/*[1]

count

Counts matches

count(/items/item)

name

The name of a match

name(/items/*[1])

Here, expression is an XPath expression and doc is the Document object that represents the XML document. For example, the statement String result = path.evaluate("/items/item[2]/product/price", doc)

sets result to the string "19.95". Now you have all the tools that you need to read and analyze an XML document. The example program at the end of this section puts these techniques to work. (The program uses the LineItem and Product classes from Chapter 12.) The class ItemListParser can parse an XML document that contains a list of product descriptions. Its parse method takes the file name and returns an array list of LineItem objects: ItemListParser parser = new ItemListParser(); ArrayList items = parser.parse("items.xml");

The ItemListParser class translates each XML element into an object of the corresponding Java class. We first get the number of items: int itemCount = Integer.parseInt(path.evaluate("count(/items/item)", doc));

For each item element, we gather the product encoding="UTF-8"?> Toaster29.95 3Hair dryer 24.951

SELF CHECK

6.

7.

Suppose you need to construct a Document object that represents an XML document other than an item list. Which methods from the ItemListBuilder class can you reuse? How would you write a document to the file output.xml?

bj4_ch23_7.fm Page 928 Tuesday, November 3, 2009 4:09 PM

928 Chapter 23 XML

HOW TO 23.2

Writing an XML Document What is the best way to write an XML document? This How To shows you how to produce a Document object and generate an XML document from it.

Step 1

Provide the outline of a document builder class. To construct the Document object from an object of some class, you should implement a class such as this one: public class MyBuilder { private DocumentBuilder builder; private Document doc; public Document build( SomeClass x) { . . . } . . . private Element createTextElement(String name, String text) { Text t = doc.createTextNode(text); Element e = doc.createElement(name); e.appendChild(t); return e; } }

Step 2

Look at the format of the XML document that you want to create. Consider all elements, except for those that only have text content. Find the matching Java classes. In the ItemListBuilder example, we ignore quantity, description, and price because they have text content. The remaining elements and their Java classes are • product - Product • item - LineItem • items - ArrayList

Step 3

For each element in Step 2, add a helper method to your builder class. Each helper method has the form private Element create ElementName(ClassForElement x)

For example, public class MyBuilder { . . . public Document build(ArrayList x) { . . . } private Element createProduct(Product x) { . . . } private Element createItem(LineItem x) { . . . } private Element createItems(ArrayList x) { . . . } }

Step 4

Implement the helper methods. For each element, call the helper methods of its children. However, if a child has text content, call createTextElement instead. For example, the item element has two children: product and quantity. The former has a helper method, and the latter has text content. Therefore, the createItem method calls createProduct and createTextElement : private Element createItem(LineItem anItem) {

bj4_ch23_7.fm Page 929 Tuesday, November 3, 2009 4:09 PM

23.4 Validating XML Documents 929 Element e = doc.createElement("item"); e.appendChild(createProduct(anItem.getProduct())); e.appendChild(createTextElement("quantity", "" + anItem.getQuantity())); return e; }

You may find it helpful to implement the helper methods “bottom up”, starting with the simplest method (such as createProduct) and finishing with the method for the root element (createItems). Step 5

Finish off your builder by writing a constructor and the build method. public class MyBuilder { public MyBuilder() throws ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); builder = factory.newDocumentBuilder(); } public Document build( ClassForRootElement x) { doc = builder.newDocument(); doc.appendChild( createRootElementName(x)); return doc; } . . . }

Step 6

Use a class, such as the LSSerializer, to convert the Document to a string. For example, Invoice x = . . .; InvoiceBuilder builder = new InvoiceBuilder(); Document doc = builder.build(x); LSSerializer ser = . . .; String str = ser.writeToString(doc);

23.4 Validating XML Documents In this section you will learn how to specify rules for XML documents of a particular type. There are several mechanisms for this purpose. The oldest and simplest mechanism is a Document Type Definition (DTD), the topic of this section. We discuss other mechanisms in Special Topic 23.1 on page 938.

23.4.1 Document Type Definitions Consider a document of type items. Intuitively, items denotes a sequence of item elements. Each item element contains a product and a quantity. A product contains a description and a price. Each of these elements contains text describing the product’s description, price, and quantity. The purpose of a DTD is to formalize this description.

bj4_ch23_7.fm Page 930 Tuesday, November 3, 2009 4:09 PM

930 Chapter 23 XML

Table 2 Replacements for Special Characters

A DTD is a sequence of rules that describes the valid child elements and attributes for each element type.

Character

Encoding

Name




Greater than (right angle bracket)

&

&

Ampersand

'

'

Apostrophe

"

"

Quotation mark

A DTD is a sequence of rules that describes • The valid attributes for each element type • The valid child elements for each element type Let us first turn to child elements. The valid child elements of an element are described by an ELEMENT rule:

This means that an item list must contain a sequence of 0 or more item elements. As you can see, the rule is delimited by , and it contains the name of the element whose children are to be constrained (items), followed by a description of what children are allowed. Next, let us turn to the definition of an item node:

This means that the children of an item node must be a product node, followed by a quantity node. The definition for a product is similar:

Finally, here are the definitions of the three remaining node types: . A price without a currency would not be valid. For an optional attribute, you use the #IMPLIED reserved word instead. product (description, price)> quantity (#PC type="xsd:integer"/>

Note that an XML schema is itself written in XML—unlike a DTD, which uses a completely different syntax. (The xsd: prefix is a name space prefix to denote that xsd:element and xsd:integer are part of the XML Schema Definition name space. See Special Topic 23.2 on page 939 for more information about name spaces. ) In XML Schema, you can define complex types, much as you define classes in Java. Here is the definition of an Address type:

Then you can specify that an invoice should have shipto and billto instance variables that are both of type Address:

These examples show that an XML schema can be more precise than a DTD.

bj4_ch23_7.fm Page 939 Tuesday, November 3, 2009 4:09 PM

23.4 Validating XML Documents 939 The XML Schema specification has many advanced features—see the W3C web site, for details. However, some programmers find that specification overly complex and instead use a competing standard called Relax NG—see www.relaxng.org. Relax NG is simpler than XML Schema, and it shares a feature with DTDs: a compact notation that is not XML. For example, in Relax NG, you simply write www.w3c.org/xml ,

element quantity { xsd:integer }

to denote that quantity is an element containing an integer. The designers of Relax NG realized that XML, despite its many advantages, is not always the best notation for humans.

Special Topic 23.2 Other XML Technologies This chapter covers the subset of the XML 1.0 specification that is most useful for common programming situations. Since version 1.0 of the XML specification was released, there has been a huge amount of interest in advanced XML technologies. A number of useful technologies have recently been standardized. Among them are: • Schema Definitions • Name Spaces • XHTML • XSL and Transformations Special Topic 23.1 contains more information about schema definitions. Name spaces were invented to ensure that many different people and organizations can develop XML documents without running into conflicts with element names. For example, if you look inside Special Topic 23.1, you will see that XML Schema definitions have element names that are prefixed with a tag xsd:, such as

That way, the tag and attribute names, such as element and string, don’t conflict with other names. In that regard, name spaces are similar to Java packages. However, a name space prefix such as xsd: is just a shortcut for the actual name space identifier, which is a much longer, unique string. For example, the full name space for XML Schema definitions is http:// www.w3.org/2000/08/XMLSchema . Each schema definition starts out with the statement

which binds the xsd prefix to the full name space. XHTML is the most recent recommendation of the W3C for formatting web pages. Unlike HTML, XHTML is fully XML-compliant. Once web-editing tools switch to XHTML, it will become much easier to write programs that parse web pages. The XHTML standard has been carefully designed to be backwards compatible with existing browsers. While XHTML documents are intended to be viewed by browsers, general XML documents are not designed to be viewed at all. Nevertheless, it is often desirable to transform an XML document into a viewable form. XSL (Extensible Stylesheet Language) was created for this purpose. A style sheet indicates how to change an XML document into an HTML document, or even a completely different format, such as PDF. For more information on these and other emerging technologies, see the W3C web site, http://www.w3c.org/xml.

bj4_ch23_7.fm Page 940 Tuesday, November 3, 2009 4:09 PM

940 Chapter 23 XML

Summary of Learning Objectives Describe the purpose of XML and the structure of an XML document.

• XML allows you to encode complex >half dollar

bj4_ch23_7.fm Page 942 Tuesday, November 3, 2009 4:09 PM

942 Chapter 23 XML 0.25 quarter

What are the values of the following XPath expressions? a. /purse/coin[1]/value b. /purse/coin[2]/name c. /purse/coin[2]/name/@lang d. name(/purse/coin[2]/*[1]) e. count(/purse/coin) f. count(/purse/coin[2]/name)

R23.12 With the XML file of Exercise R23.11, give XPath expressions that yield: a. the value of the first coin. b. the number of coins. c. the name of the first child element of the first coin element. d. the name of the first attribute of the first coin’s name element. (The expression

selects the attributes of an element.) e. the value of the lang attribute of the second coin’s name element. @*

R23.13 Design a DTD that describes a bank with bank accounts. R23.14 Design a DTD that describes a library patron who has checked out a set of books.

Each book has an ID number, an author, and a title. The patron has a name and telephone number. R23.15 Write the DTD file for the following XML document Comtrade Tornado 2495 60 AMAX Powerstation 75 2999 62

R23.16 Design a DTD for invoices, as described in How To 23.3 on page 936. R23.17 Design a DTD for simple English sentences, as described in Random Fact 23.2 on

page 920. R23.18 Design a DTD for arithmetic expressions, as described in Random Fact 23.2 on

page 920.

bj4_ch23_7.fm Page 943 Tuesday, November 3, 2009 4:09 PM

Programming Exercises 943

Programming Exercises P23.1 Write a program that can read XML files, such as 0.5 half dollar . . .

Your program should construct a Purse object and print the total value of the coins in the purse. P23.2 Building on Exercise P23.1, make the program read an XML file as described in that

exercise. Then print an XML file of the form 0.5 half dollar 3 0.25 quarter 2

P23.3 Repeat Exercise P23.1, using a DTD for validation. P23.4 Write a program that can read XML files, such as 3 1295.32 . . .

Your program should construct a Bank object and print the total value of the balances in the accounts. P23.5 Repeat Exercise P23.4, using a DTD for validation. P23.6 Enhance Exercise P23.4 as follows: First read the XML file in, then add 10 percent

interest to all accounts, and write an XML file that contains the increased account balances. P23.7 Write a DTD file that describes documents that contain information about coun-

tries: name of the country, its population, and its area. Create an XML file that has

bj4_ch23_7.fm Page 944 Tuesday, November 3, 2009 4:09 PM

944 Chapter 23 XML

five different countries. The DTD and XML should be in different files. Write a program that uses the XML file you wrote and prints: • The country with the largest area. • The country with the largest population. • The country with the largest population density (people per square kilometer). P23.8 Write a parser to parse invoices using the invoice structure described in How To

23.1 on page 909. The parser should parse the XML file into an Invoice object and print out the invoice in the format used in Chapter 12. P23.9 Modify Exercise P23.8 to support separate shipping and billing addresses. Supply a

modified DTD with your solution. P23.10 Write a document builder that turns an invoice object, as defined in Chapter 12,

into an XML file of the format described in How To 23.1 on page 909. P23.11 Modify Exercise P23.10 to support separate shipping and billing addresses. G P23.12 Write a program that can read an XML document of the form 5 10 20 30

and draw the shape in a window. G P23.13 Write a program that can read an XML document of the form 5 10 20 30

and draw the shape in a window. G P23.14 Write a program that can read an XML document of the form 5 10 20 30

Support shape attributes "rectangle", "roundrectangle", and "ellipse". Draw the shape in a window. G P23.15 Write a program that can read an XML document of the form 5 10 . . .

bj4_ch23_7.fm Page 945 Tuesday, November 3, 2009 4:09 PM

Programming Projects 945

and draw the shape in a window. G P23.16 Write a program that can read an XML document of the form 5 10 20 30 5 10 25 40 Hello, World! 20 30

and show the drawing in a window. G P23.17 Repeat Exercise P23.16, using a DTD for validation.

Programming Projects Project 23.1 Following Exercise P12.7, design an XML format for the appointments in an

appointment calendar. Write a program that first reads in a file with appointments, then another file of the format . . . . . . . . .

Your program should process the commands and then produce an XML file that consists of the updated appointments. Project 23.2 Write a program to simulate an airline seat reservation system, using XML docu-

ments. Reference Exercise P12.8 for the airplane seat information. The program reads a seating chart, in an XML format of your choice, and a command file, in an XML format of your choice, similar to the command file of the preceding exercise. Then the program processes the commands and produces an updated seating chart.

bj4_ch23_7.fm Page 946 Tuesday, November 3, 2009 4:09 PM

946 Chapter 23 XML

Answers to Self-Check Questions 1. Your answer should look similar to this: James Bond 007

2. Most browsers display a tree structure that indicates the nesting of the tags. Some

browsers display nothing at all because they can’t find any HTML tags. 3. The text hamster.jpg is never displayed, so it should not be a part of the document.

4. 5. 6. 7.

Instead, the src attribute tells the browser where to find the image that should be displayed. 29.95. name(/*[1]). The createTextElement method is useful for creating other documents. First construct a string, as described, and then use a PrintWriter to save the string to a file.

8. 9. 10.

User name: Password:



HTTP Internet HTML Browser Client Figure 1

948

The Architecture of a Web Application

Web Server

bj4_ch24_7.fm Page 949 Tuesday, November 3, 2009 5:21 PM

24.1 The Architecture of a Web Application 949

Figure 2

When a form is submitted, the names and values of the form elements are sent to the web server.

A Simple Form

Figure 2 shows the form. Note that there are three input elements: a text field, a password field, and a submit button. (The HTML tags are summarized in Appendix F.) When a submit button is pressed, the form encoding="UTF-8"?> Page title

Page contents A JavaServer Faces (JSF) page contains HTML and JSF tags.

You can think of this as the required “plumbing”, similar to the public static void incantation that is required for every Java program. If you compare this page with the HTML page from the preceding section, you will notice that the main elements are very similar to a regular HTML page, but several elements (head, body, and form) are JSF tags with an h: prefix. Following is a complete example of a JSF page. Figure 3 shows the result of executing the program.

main

Figure 3

Executing the time Web Application

bj4_ch24_7.fm Page 951 Tuesday, November 3, 2009 5:21 PM

24.2 The Architecture of a JSF Application 951 ch24/time/index.xhtml 1 2 3 4 5 6 7 8 9 10 11 12 13 14

The JSF container converts a JSF page to an HTML page, replacing all JSF tags with text and HTML tags.

JSF Page

The time application

The current time is #{timeBean.time}



The purpose of a JSF page is to generate an HTML page. The basic process is as follows: • The HTML tags that are present in the JSF page (such as title and p) are retained. These are the static part of the page: the formatting instructions that do not change. • The JSF tags are translated into HTML. This translation is dynamic: it depends on the state of Java objects that are associated with the tags. In our example, the expression #{timeBean.time} has been replaced by dynamically generated text, namely the current time. Figure 4 shows the basic process. The browser requests a JSF page. The page is processed by the JSF container, the server-side software that implements the JSF framework. The JSF container translates all JSF tags into text and HTML tags, yielding a pure HTML page. That page is transmitted to the client browser. The browser displays the page.

JSF Container

Figure 4

HTML File

Web Server

Internet

Web Browser

The JSF Container Rewrites the Requested Page

24.2.2 Managed Beans

A managed bean is an object that is controlled by the JSF container.

The expression #{timeBean.time} is called a value expression. Value expressions invoke method calls on Java objects, which are called managed beans. These objects are called “managed” because they are controlled by the JSF container. The container creates a managed bean when it is first used in a value expression. The scope of the managed bean determines which clients can access the object and how long the object stays alive.

bj4_ch24_7.fm Page 952 Tuesday, November 3, 2009 5:21 PM

952 Chapter 24 Web Applications

A bean with session scope is available for multiple requests by the same browser.

In this chapter, we only consider managed beans with session scope. A sessionscoped object can be accessed by all requests from the same browser. If multiple users are simultaneously accessing a JSF application, each of them is given a separate object. This is a good default for simple web applications. Here is the code for the TimeBean class. Note the following: • You declare a session-scoped managed bean with the annotations @ManagedBean and @SessionScoped. • The name of the bean in a value expression is the class name with the first letter changed to lowercase, e.g., timeBean. • The value expression timeBean.time calls the getTime method. You will see the reason in the next section. • The getTime method uses the DateFormat class to format the current time, producing a string such as 9:00:00 AM. • When deploying the application, all class files must be placed inside the WEB-INF/ classes directory. Because many application servers also require that classes be contained in a package, we place our classes inside the bigjava package. For that reason, the class is contained in the WEB-INF/classes/bigjava directory. ch24/time/WEB-INF/classes/bigjava/TimeBean.java 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

package bigjava; import import import import import

java.text.DateFormat; java.util.Date; java.util.TimeZone; javax.faces.bean.ManagedBean; javax.faces.bean.SessionScoped;

@ManagedBean @SessionScoped public class TimeBean { private DateFormat timeFormatter; /**

Initializes the formatter. */ public TimeBean() { timeFormatter = DateFormat.getTimeInstance(); } /**

Read-only time property. @return the formatted time */ public String getTime() { Date time = new Date(); String timeString = timeFormatter.format(time); return timeString; } }

bj4_ch24_7.fm Page 953 Friday, November 6, 2009 6:55 PM

24.2 The Architecture of a JSF Application 953

24.2.3 Separation of Presentation and Business Logic The JSF technology enables the separation of presentation and business logic.

We will look at value expressions and managed beans in more detail in the next section. The key observation is that every JSF application has two parts: presentation and business logic. The term “presentation” refers to the user interface of the web application: the arrangement of the text, images, buttons, and so on. The business logic is the part of the application that is independent of the visual presentation. In commercial applications, it contains the rules that are used for business decisions: what products to offer, how much to charge, to whom to extend credit, and so on. In our example, we simulated the business logic with a TimeBean object. JSF pages define the presentation logic. Managed beans define the business logic. Value expressions tie the two together. The separation of presentation logic and business logic is very important when designing web applications. Some web technologies place the code for the business logic right into the web page. However, this quickly turns into a serious problem. Programmers are rarely skilled in web design (as you can see from the boring web pages in this chapter). Graphic designers don’t usually know much about programming and find it very challenging to improve web pages that contain a lot of code. JSF solves this problem. In JSF, the graphic designer only sees the elements that make up the presentation logic. It is easy to take a boring JSF page and make it pretty by adding banners, icons, and so on.

24.2.5 Deploying a JSF Application To run a JSF application, you need a server with a JSF container. We suggest that you use the GlassFish application server, http://glassfish.dev.java.net, which has, together with many other features that you can ignore, a JSF container and a convenient administration interface. To deploy a JSF application, follow these steps: 1. Make a separate directory tree for each web application. 2. Place JSF pages (such as index.xhtml) into the root directory of the application’s 3. 4. 5.

6.

directory tree. Create a WEB-INF subdirectory in your application directory. Place all Java classes inside a classes subdirectory of the WEB-INF directory. Note that you should place your classes into a package. Place the file web.xml (which is shown below) inside the WEB-INF subdirectory. Some servers need the web.xml file to configure the JSF container. We also turn on development mode, which gives better error messages. Zip up all application files into a file with extension .war (Web Archive). This is easily achieved by running the jar command from the command line, after changing to the application directory. For example, cd time jar cvf time.war .

The period (.) denotes the current directory. The jar command creates an archive time.war consisting of all files in all subdirectories of the current directory.

bj4_ch24.fm Page 954 Sunday, November 15, 2009 3:55 PM

954 Chapter 24 Web Applications 7. Make sure the application server is started. The application server listens to

web requests, typically on port 8080. 8. Deploy the application to the application server. With GlassFish, this can be

achieved either through the administrative interface or simply by copying the WAR file into a special deployment directory. By default, this is the subdirectory domains/domain1/autodeploy inside the GlassFish installation directory. 9. Point your browser to an URL such as http://localhost:8080/time/faces/ index.xhtml. Note the faces part in the URL. If you forget this part, the file will not be processed by the JSF container. Figure 5 shows the directory structure for the application.

Figure 5

The Directory Structure of the time Application

ch24/time/WEB-INF/web.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

SELF CHECK

3. 4. 5.

Faces Servlet javax.faces.webapp.FacesServlet Faces Servlet /faces/* faces/index.xhtml javax.faces.PROJECT_STAGE Development

What steps are required to add the image of a clock to the time application? (The clock doesn’t have to show the correct time.) Does a Swing program automatically separate presentation and business logic? Why does the WAR file need to be deployed to the application server?

bj4_ch24_7.fm Page 955 Tuesday, November 3, 2009 5:21 PM

24.2 The Architecture of a JSF Application 955

Special Topic 24.1 Session State and Cookies You may recall from Chapter 21 that HTTP is a stateless protocol. A browser sends a request to a web server. The web server sends the reply and then disconnects. This is different from other protocols, such as POP, where the mail client logs into the mail server and stays connected until it has retrieved all e-mail messages. In contrast, a browser makes a new connection to the web server for each web page, and the web server has no way of knowing that those connections originate from the same browser. This makes it difficult to implement web applications. For example, in a shopping application, it is essential to track which requests came from a particular shopper. Cookies were invented to overcome this restriction. A cookie consists of a small string that the web server sends to a browser, and that the browser sends back to the same server with all further requests. That way, the server can tie the stream of requests together. The JSF container matches up the cookies with the beans that have session scope. When a browser request contains a cookie, the value expressions in the JSF page refer to the matching beans. You may have heard some privacy advocates complaining about cookies. Cookies are not inherently evil. When used to establish a session or to remember login information, they can make web applications more user-friendly. But when cookies are used to track your identity while you surf the Web, there can be privacy concerns. For example, Figure 6 shows some of the cookies that my browser held on a particular day. I have no recollection of visiting the advertising sites, so it is a bit disconcerting to see that my browser communicated with them. Some people turn off cookies, and then web applications need to use another scheme to establish a session, typically by embedding a session identifier in the request URL or a hidden field of a form. The JSF session mechanism automatically switches to URLs with session identifiers if the client browser doesn’t support cookies.

Figure 6

Viewing the Cookies in a Browser

bj4_ch24_7.fm Page 956 Tuesday, November 3, 2009 5:21 PM

956 Chapter 24 Web Applications

24.3 JavaBeans Components Properties of a software component can be accessed without having to write Java code. A JavaBean is a class that exposes properties through its get and set methods.

A software component is an entity that encapsulates functionality and can be plugged into a software system without programming. A managed bean is an example of a software component. When we added the timeBean object to the web application, we did not write Java code to construct the object or to call its methods. Some programming languages have explicit support for components, but Java does not. Instead, in Java, you use a programming convention to implement components. A JavaBean is a Java class that follows this convention. A JavaBean exposes properties—values of the component that can be accessed without programming. Just about any Java class can be a JavaBean—there are only two requirements. • A JavaBean must have a constructor with no parameters. • A JavaBean must have methods for accessing the component properties that follow the get/set naming convention. For example, to get or set a property named city, the methods must be called getCity and setCity. In general, if the name of the property is propertyName, and its type is Type, then the associated methods must be of the form public Type getPropertyName() public void setPropertyName(Type newValue)

Note that the name of a property starts with a lowercase letter (such as city), but the corresponding methods have an uppercase letter (getCity). The only exception is that property names can be all capitals, such as ID or URL, with corresponding methods getID or setURL. If a property has only a get method, then it is a read-only property. If it has only a set method, then it is a write-only property. A JavaBean can have additional methods, but they are not connected with properties. Here is a simple example of a bean class that formats the time for a given city, which we will further develop in the next section. public class TimeZoneBean { // Instance variables . . . // Required constructor with no parameters public TimeZoneBean() { . . . } // city property public String getCity() { . . . } public void setCity(String newValue) { . . . } // read-only time property public String getTime() { . . . } // Other methods . . . }

This bean has two properties: city and time.

bj4_ch24_7.fm Page 957 Tuesday, November 3, 2009 5:21 PM

24.4 Navigation Between Pages 957

In the value expression of an output tag, only the property getter is called.

In the value expression of an input tag, the property setter is called when the page is submitted.

SELF CHECK

You should not make any assumptions about the internal representation of properties in the bean class. The getter and setter methods may simply read or write an instance variable. But they may also do other work. An example is the getTime method from the TimeBean in the preceding section; it formats the current time. When a property name is used in a value expression that is included in the JSF page, then the get method is involved. For example, when the string The current time is #{timeBean.time}

is rendered, the JSF container calls the getTime method of the session’s TimeBean instance. When a property name is used in an h:inputText tag (that, is the equivalent of an HTML input field or a JTextField), the situation is more complex. Consider this example:

When the JSF page is first displayed, the getCity method is called, and the current value of the city property is displayed. But after the user submits the page, the setCity method is called. It sets the city property to the value that the user typed into the input field. 6. 7.

Is the Random class a JavaBean? What work does the setCity method of the TimeZoneBean do?

24.4 Navigation Between Pages

The outcome string of an action determines the next page that the JSF container sends to the browser.

In most web applications, users will want to move between different pages. For example, a shopping application might have a login page, a page to show products for sale, and a checkout page that shows the shopping cart. In this section, you will learn how to enable users to navigate from one page to another. Consider our sample timezone program. If the time computation uses the time zone at the server location, it will not be very useful when the user is in another time zone. Therefore, we will prompt for the city in which the user is located. When the user clicks the submit button, we move to the page next.xhtml and display the time in the user’s time zone (see Figure 7). However, if no time zone is available for the city, we display the page error.xhtml. A button yields an outcome, a string that determines the next page. Unless specified otherwise, the next page is the outcome string with the .xhtml extension added. For example, if the outcome string is error, the next page is error.xhtml. (It is possible to specify a different mapping from outcomes to pages, but there is no need to do so for a simple application.) In many situations, the next page depends on the result of some computation. In our example, we need different outcomes depending on the city that the user entered. To achieve this flexibility, you specify a method expression as the action attribute:

bj4_ch24_7.fm Page 958 Tuesday, November 3, 2009 5:21 PM

958 Chapter 24 Web Applications

Figure 7

A method expression specifies a bean and a method that should be invoked on the bean.

The timezone Application

A method expression consists of the name of a bean and the name of a method. When the form is submitted, the JSF container calls timeZoneBean.checkCity(). The checkCity method returns the outcome string: public class TimeZoneBean { . . . public String checkCity() { zone = getTimeZone(city); if (zone == null) return "error"; return "next"; } }

If the next page does not depend on a computation, then you set the action attribute of the button to a fixed outcome string, like this:

If a button has no action attribute, or if the action outcome is null, then the current page is redisplayed. We can now complete our time zone application. The Java library contains a convenient TimeZone class that knows about time zones across the world. A time zone is

bj4_ch24_7.fm Page 959 Tuesday, November 3, 2009 5:21 PM

24.4 Navigation Between Pages 959

identified by a string such as "America/Los_Angeles" or "Asia/Tokyo". The static method getAvailableIDs returns a string array containing all IDs: String[] ids = TimeZone.getAvailableIDs();

There are several hundred time zone IDs. (We are using time zones in this example because the TimeZone class gives us an interesting encoding="UTF-8"?> The timezone application

Set time zone:



The next JSF page shows the result, using two value expressions that display the city and time properties. These expressions invoke the getCity and getTime methods of the bean class. ch24/timezone/next.xhtml 1 2 3 4 5 6

The timezone application

bj4_ch24.fm Page 962 Sunday, November 15, 2009 3:54 PM

962 Chapter 24 Web Applications

7 8 9 10 11 12 13 14 15 16 17

The current time in #{timeZoneBean.city} is #{timeZoneBean.time}



Figure 8 shows the directory structure of the timezone application.

Figure 8

SELF CHECK

8. 9.

HOW TO 24.1

The Directory Structure of the timezone Application

What tag would you need to add to error.xhtml so that the user can click on a button labeled “Help” and see help.xhtml? Which page would be displayed if the checkCity method returned null?

Designing a Managed Bean A managed bean is just a regular Java class, with three special characteristics. • The bean must have a constructor with no parameters • Methods of the form Type getPropertyName() void setPropertyName(Type x)

define properties that can be accessed from JSF pages. • Methods of the form String

methodName()

can be used to specify command actions. Here are step-by-step instructions for designing a managed bean class. Step 1

Decide on the responsibility of the bean. When designing a JSF application, it is tempting to stuff all code into a single bean class. Some development environments even encourage this approach. However, from a software engineering perspective, it is best to come up with different beans for different

bj4_ch24_7.fm Page 963 Tuesday, November 3, 2009 5:21 PM

24.5 JSF Components 963 responsibilities. For example, a shopping application might have a UserBean to describe the current user, a SiteBean to describe how the user visits the shopping site, and a ShoppingCartBean that holds the items that the user is purchasing. Step 2

Discover the properties that the bean should expose. A property is an entity that you want to access or modify from your JSF pages. For example, a UserBean might have properties firstName, lastName, and password. Sometimes, you have to resort to a bit of trickery. For example, consider adding an item to the shopping cart. You could use a property items, but it would be cumbersome to access all items in a JSF page and then set items to a new collection that contains one additional element. Instead, you can design a property addedItem. When that property is set, the setAddedItem method of your bean adds its value to the collection of items.

Step 3

Settle on the type and access permissions for each property. Properties that are only used to generate output can be read-only. Properties that are used in h:inputText and other input tags must have read-write access.

Step 4

Define action methods for navigation. Your action methods can carry out arbitrary tasks in order to react to the user inputs. The only limitation is that they don’t have access to the form />

The h:inputTextArea component has attributes to specify the rows and columns, such as

bj4_ch24_7.fm Page 964 Tuesday, November 3, 2009 5:21 PM

964 Chapter 24 Web Applications

Table 1 Common JSF Components Component

JSF Tag

Common Attributes

Text Field

h:inputText

value

Password Field

h:inputSecret

value

Text Area

h:inputTextArea

value rows cols

Radio Button Group

h:selectOneRadio

value layout

Checkbox

h:selectOneCheckbox

value

Checkbox Group

h:selectManyCheckbox

value layout

Menu

h:selectOneMenu h:selectManyMenu

value

Image

h:graphicImage

value

Submit Button

h:commandButton

value action

Example

The radio button and checkbox groups allow you to specify horizontal or vertical layout:

In European languages, lineDirection means horizontal and pageDirection means vertical. However, in some languages, lines are written top-to-bottom, and the meanings are reversed. Button groups and menus are more complex than the other user interface components. They require you to specify two properties: • the collection of possible choices • the actual choice Use an f:selectItems tag to specify all choices for a component that allows selection from a list of choices.

The value attribute of the component specifies the actual choice to be displayed. The collection of possible choices is defined by a nested f:selectItems tag, like this:

bj4_ch24_7.fm Page 965 Tuesday, November 3, 2009 5:21 PM

24.6 A Three-Tier Application 965

When you use the f:selectItems tag, you need to add the namespace declaration xmlns:f="http://java.sun.com/jsf/core"

to the html tag at the top of your JSF page. The value of the f:selectItems tag must have a type that can describe a list of choices. There are several types that you can use, but the easiest—and the only one that we will discuss—is a Map. The keys of the map are the labels—the strings that are displayed next to each choice. The corresponding map values are the label values—the values that correspond to the selection. For example, a choice map for months would map January to 1, February to 2, and so on: public class CreditCardBean { . . . public Map getMonthChoices() { Map choices = new LinkedHashMap(); choices.put("January", 1); choices.put("February", 2); . . . return choices; } }

Here, we use a LinkedHashMap because we want to visit entries in the order in which they are inserted. This is more useful than a HashMap, which would visit the labels in random order or a TreeMap, which would visit them in alphabetical order (starting with April!). The type of the value property of the component enclosing the f:selectItems tag must match the type of the map value. For example, creditCardBean.expirationMonth must be an integer, not a string. If multiple selections are allowed, the type of the value property must be a list or array of matching types. For example, if one could choose multiple months, a selectManyRadio component would have a value property with a type such as int[] or ArrayList. SELF CHECK

10. 11.

Which JSF components can be used to give a user a choice between “AM/PM” and “military” time? How would you supply a set of choices for a credit card expiration year to a h:selectOneMenu component?

24.6 A Three-Tier Application A three-tier application has separate tiers for presentation, business logic, and ) private encoding="UTF-8"?> The multizone application

Enter city:



ch24/multizone/next.xhtml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

The multizone application



bj4_ch24_7.fm Page 969 Tuesday, November 3, 2009 5:21 PM

24.6 A Three-Tier Application 969

16 17 18 19 20 21 22 23



ch24/multizone/error.xhtml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

The multizone application

Sorry, no information is available for #{timeZoneBean.cityToAdd}.



ch24/multizone/WEB-INF/classes/bigjava/TimeZoneBean.java 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

package bigjava; import import import import import import import import import import import import import import import

java.sql.Connection; java.sql.PreparedStatement; java.sql.ResultSet; java.sql.SQLException; java.text.DateFormat; java.util.ArrayList; java.util.Date; java.util.Map; java.util.TimeZone; java.util.TreeMap; java.util.logging.Logger; javax.annotation.Resource javax.faces.bean.ManagedBean; javax.faces.bean.SessionScoped; javax.sql.) private /> to the index.xhtml file. No—it is possible (and sadly common) for programmers to place the business logic into the frame and component classes of the user interface. The application server knows nothing about the files on your computer. You need to hand it the WAR file with all the application’s pages, code, and configuration files so that it can execute the application when it receives a web request. Technically, yes. It has a constructor with no parameters. However, it has no methods with names that start with get or set, so it exposes no properties. There is no way of knowing without looking at the source code. Perhaps it simply executes a statement city = newValue, setting an instance variable of the bean class. But the method may also do other work, for example checking whether the city name is valid or storing the name in a action="help"/> to error.xhtml. The current page would be redisplayed. h:selectOneRadio, h:selectOneMenu, or h:selectOneCheckbox You would need a bean with a property such as the following: public Map getYearChoices() { Map choices = new TreeMap(); choices.put("2003", 2003); choices.put("2004", 2004); . . . return choices; }

Then supply a tag .

12. Then the />

This code tells the browser to load and display the image that is stored in the file hamster.jpeg. This is a slightly different type of tag. Rather than text inside a tag pair , the img tag uses an attribute to specify a file name. Attributes have names and values. For example, the src attribute has the value "hamster.jpeg". Table 2 contains commonly used attributes. It is considered polite to use several additional attributes with the img tag, namely the image size and an alternate description:

These additional attributes help the browser lay out the page and display a temporary description while gathering the >Java is an object-oriented programming language.

When the viewer of the web page clicks on the word Java, the browser loads the web page located at java.sun.com. (The value of the href attribute is a Universal Resource Locator (URL), which tells the browser where to go. The prefix http:, for Hypertext Transfer Protocol, tells the browser to fetch the file as a web page. Other protocols allow different actions, such as ftp: to download a file, mailto: to send e-mail to a user, and file: to view a local HTML file.) Finally, the applet tag includes an applet in a web page. To display an applet, you need first to write and compile a Java file to generate the applet code—see Special Topic 2.2. Then you tell the browser how to find the code for the applet and how much screen space to reserve for the applet. Here is an example: An animation of Harry, the Horrible Hamster

The text between the and tags is only displayed in lieu of the actual applet by browsers that can’t run Java applets.

bj4_appF.fm Page 1044 Wednesday, November 4, 2009 6:43 PM

1044 Appendix F

HTML Summary

Table 3 Selected HTML Entities Entity

Description

Appearance




&

Ampersand

&

"

Quotation mark

"

 

Nonbreaking space

©

Copyright symbol

©

You have noticed that tags are enclosed in angle brackets (less-than and greaterthan signs). What if you want to show an angle bracket on a web page? HTML provides the notations < and > to produce the < and > symbols, respectively. Other codes of this kind produce symbols such as accented letters. The & (ampersand) symbol introduces these codes; to get that symbol itself, use &. See Table 3 for a summary. You may already have created web pages with a web editor that works like a word processor, giving you a WYSIWYG (what you see is what you get) view of your web page. But the tags are still there, and you can see them when you load the HTML file into a text editor. If you are comfortable using a WYSIWYG web editor, and if your editor can insert applet tags, you don’t need to memorize HTML tags at all. But many programmers and professional web designers prefer to work directly with the tags at least some of the time, because it gives them more control over their pages.

bj4_appG.fm Page 1045 Wednesday, November 4, 2009 6:50 PM

Appendix

G

Tool Summary In this summary, we use a monospaced font for actual commands such as javac. An italic font denotes descriptions of tool command components such as options. Items enclosed in brackets [. . .] are optional. Items separated by vertical bars | are alternatives. Do not include the brackets or vertical bars when typing the commands.

The Java Compiler javac [options] sourceFile1| @fileList1 sourceFile2| @fileList2 . . .

A file list is a text file that contains one file name per line. For example, File Greeting.list 1 2

Greeting.java GreetingTest.java

Then you can compile all files with the command javac @Greeting.list

The Java compiler options are summarized in Table 1.

Table 1 Common Compiler Options Option -classpath locations or -cp locations

-sourcepath

-d

locations

directory

Description

The compiler is to look for classes on this path, overriding the CLASSPATH environment variable. If neither is specified, the current directory is used. Each location is a directory, JAR file, or ZIP file. Locations are separated by a platformdependent separator (: on Unix, ; on Windows). The compiler is to look for source files on this path. If not specified, source files are searched in the class path. The compiler places files into the specified directory.

-g

Generate debugging information.

-verbose

Include information about all classes that are being compiled (useful for troubleshooting).

-deprecation

Give detailed information about the usage of deprecated messages.

-Xlint:errorType

Carry out additional error checking. If you get warnings about unchecked conversions, compile with the -Xlint:unchecked option.

1045

bj4_appG.fm Page 1046 Wednesday, November 4, 2009 6:50 PM

1046 Appendix G

Tool Summary

The Java Virtual Machine Launcher The following command loads the given class and starts its main method, passing it an array containing the provided command line arguments. java [options] ClassName [argument1 argument2 . . . ]

The following command loads the main class of the given JAR file and starts its main method, passing it an array containing the provided command line arguments. java [options] -jar jarFileName [argument1 argument2 . . . ]

The Java virtual machine options are summarized in Table 2.

Table 2 Common Virtual Machine Launcher Options Option

Description

-classpath locations or -cp locations

Look for classes on this path, overriding the CLASSPATH environment variable. If neither is specified, the current directory is used. Each location is a directory, JAR file, or ZIP file. Locations are separated by a platform-dependent separator (: on Unix, ; on Windows).

-verbose

Trace class loading

-Dproperty=value

Set a system property that you can retrieve with the method.

System.getProperties

The Applet Viewer appletviewer url1 url2 . . .

The urls are searched for applets, and each applet is displayed in a separate window. An applet should be specified as an HTML tag of the form . . .

The codebase parameter is an URL that is relative to the URL of the HTML file containing the applet or object tag.

bj4_appG.fm Page 1047 Wednesday, November 4, 2009 6:50 PM

Appendix G

Tool Summary 1047

The JAR Tool To combine one or more files into a JAR (Java Archive) file, use the command jar cvf jarFile file1 file2 . . .

The resulting JAR file can be included in a class path. To build a program that can be launched with java manifest file, such as

-jar,

you must create a

File myprog.mf 1

Main-Class: com/horstmann/MyProg

The manifest must specify the path name of the class file that launches the application, but with the .class extension removed. Then build the JAR file as jar cvfm jarFile manifestFile file1 file2 . . .

You can also use JAR as a replacement for a ZIP utility, simply to compress and bundle a set of files for any purpose. Then you may want to suppress the generation of the JAR manifest, with the command jar cvfM jarFile file1 file2 . . .

To extract the contents of a JAR file into the current directory, use jar xvf jarFile

To see the files contained in a JAR file without extracting the files, use jar tvf jarFile

bj4_appH.fm Page 1048 Wednesday, November 4, 2009 6:57 PM

Appendix

H

javadoc Summary Setting Documentation Comments in Source A documentation comment is delimited by /** and */. You can comment • Classes • Methods • Instance variables Each comment is placed immediately above the feature it documents. Each /** . . . */ documentation comment contains introductory text followed by tagged documentation. A tag starts with an @ character, such as @author or @param. Tags are summarized in Table 1. The first sentence of the introductory text should be a summary statement. The javadoc utility automatically generates summary pages that extract these sentences.

Table 1 Common javadoc Tags Tag @param

parameter explanation

A parameter of a method. Use a separate tag for each parameter.

@return

explanation

The return value of a method.

@throws

exceptionType explanation

An exception that a method may throw. Use a separate tag for each exception.

@deprecated

@see @see @see

1048

Description

packageName.ClassName packageName.ClassName #methodName(Type1, Type2, . . .) packageName.ClassName#variableName

A feature that remains for compatibility but that should not be used for new code. A reference to a related documentation entry.

@author

The author of a class or interface. Use a separate tag for each author.

@version

The version of a class or interface.

bj4_appH.fm Page 1049 Wednesday, November 4, 2009 6:57 PM

Appendix H javadoc Summary 1049

You can use HTML tags such as em for emphasis, code for a monospaced font, img for images, ul for bulleted lists, and so on. Here is a typical example. The summary sentence (in color) will be included with the method summary. /**

Withdraws money from the bank account. Increments the transaction count. @param amount the amount to withdraw @return the balance after the withdrawal @throws IllegalArgumentException if the balance is not sufficient */ public double withdraw(double amount) { if (balance - amount < minimumBalance) throw new IllegalArgumentException(); balance = balance - amount; transactions++; return balance; }

Generating Documentation from Commented Source To extract the comments, run the javadoc program: javadoc [options] sourceFile1| packageName1 | @fileList1 sourceFile2 | packageName2 | @fileList2 . . .

See the documentation of the javac command in Appendix F for an explanation of file lists. Commonly used options are summarized in Table 2. To document all files in the current directory, use (all on one line) javadoc -link http://java.sun.com/javase/7/docs/api -d docdir *.java

Table 2 Common javadoc Command Line Options Option -link

-d

Description

Link to another set of Javadoc files. You should include a link to the standard library documentation, either locally or at http://java.sun.com/javase/7/docs/api .

URL

directory

Store the output in directory. This is a useful option, because it keeps your current directory from being cluttered up with javadoc files.

-classpath

locations

Look for classes on the specified paths, overriding the CLASSPATH environment variable. If neither is specified, the current directory is used. Each location is a directory, JAR file, or ZIP file. Locations are separated by a platform-dependent separator (: Unix, ; Windows).

-sourcepath

locations

Look for source files on the specified paths. If not specified, source files are searched in the class path.

-author, -version

Include author, version information in the documentation. This information is omitted by default.

bj4_appI.fm Page 1050 Wednesday, November 4, 2009 7:02 PM

Appendix

I

Number Systems Binary Numbers Decimal notation represents numbers as powers of 10, for example 1729decimal = 1 × 103 + 7 × 10 2 + 2 × 101 + 9 × 100

There is no particular reason for the choice of 10, except that several historical number systems were derived from people’s counting with their fingers. Other number systems, using a base of 12, 20, or 60, have been used by various cultures throughout human history. However, computers use a number system with base 2 because it is far easier to build electronic components that work with two values, which can be represented by a current being either off or on, than it would be to represent 10 different values of electrical signals. A number written in base 2 is also called a binary number. For example, 1101binary = 1 × 23 + 1 × 22 + 0 × 21 + 1 × 20 = 8 + 4 + 1 = 13

For digits after the “decimal” point, use negative powers of 2. 1.101binary = 1 × 20 + 1 × 2−1 + 0 × 2−2 + 1 × 2−3 1 1 + 2 8 = 1 + 0.5 + 0.125 = 1.625 = 1+

In general, to convert a binary number into its decimal equivalent, simply evaluate the powers of 2 corresponding to digits with value 1, and add them up. Table 1 shows the first powers of 2. To convert a decimal integer into its binary equivalent, keep dividing the integer by 2, keeping track of the remainders. Stop when the number is 0. Then write the remainders as a binary number, starting with the last one.

1050

bj4_appI.fm Page 1051 Wednesday, November 4, 2009 7:02 PM

Appendix I

Number Systems 1051

For example, 100 ÷ 2 50 ÷ 2 25 ÷ 2 12 ÷ 2 6÷2 3÷2 1÷ 2

= 50 remainder 0 = 25 remainder 0 = 12 remainder 1 = 6 remainder 0 = 3 remaainder 0 = 1 remainder 1 = 0 remainder 1

Table 1 Powers of Two Power

Decimal Value

20

1

21

2

22

4

23

8

24

16

25

32

26

64

27

128

28

256

29

512

210

1,024

211

2,048

212

4,096

213

8,192

214

16,384

215

32,768

216

65,536

Therefore, 100decimal = 1100100 binary . Conversely, to convert a fractional number less than 1 to its binary format, keep multiplying by 2. If the result is greater than 1, subtract 1. Stop when the number is 0. Then use the digits before the decimal points as the binary digits of the fractional part, starting with the first one. For example, 0.35 ⋅ 2 0.7 ⋅ 2 0.4 ⋅ 2 0.8 ⋅ 2 0.6 ⋅ 2 0.2 ⋅ 2

= = = = = =

0.7 1.4 0.8 1.6 1.2 0.4

Here the pattern repeats. That is, the binary representation of 0.35 is 0.01 0110 0110 0110 ... To convert any floating-point number into binary, convert the whole part and the fractional part separately.

Two’s Complement Integers To represent negative integers, there are two common representations, called “signed magnitude” and “two’s complement”. Signed magnitude notation is simple: use the leftmost bit for the sign (0 = positive, 1 = negative). For example, when using 8-bit numbers, −13 = 10001101signed magnitude

However, building circuitry for adding numbers gets a bit more complicated when one has to take a sign bit into account. The two’s complement representation solves this problem.

bj4_appI.fm Page 1052 Wednesday, November 4, 2009 7:02 PM

1052 Appendix I

Number Systems

To form the two’s complement of a number, • Flip all bits. • Then add 1. For example, to compute −13 as an 8-bit value, first flip all bits of 00001101 to get 11110010. Then add 1: −13 = 11110011two’s complement

Now no special circuitry is required for adding two numbers. Simply follow the normal rule for addition, with a carry to the next position if the sum of the digits and the prior carry is 2 or 3. For example, 1

+13 -13

1111

111

0000 1101 1111 0011 1 0000 0000

But only the last 8 bits count, so +13 and −13 add up to 0, as they should. In particular, −1 has two’s complement representation 1111 . . . 1111, with all bits set. The leftmost bit of a two’s complement number is 0 if the number is positive or zero, 1 if it is negative. Two’s complement notation with a given number of bits can represent one more negative number than positive numbers. For example, the 8-bit two’s complement numbers range from −128 to +127. This phenomenon is an occasional cause for a programming error. For example, consider the following code: byte b = . . .; if (b < 0) b = (byte) -b;

This code does not guarantee that b is nonnegative afterwards. If b happens to be −128, then computing its negative again yields −128. (Try it out—take 10000000, flip all bits, and add 1.)

IEEE Floating-Point Numbers The Institute for Electrical and Electronics Engineering (IEEE) defines standards for floating-point representations in the IEEE-754 standard. Figure 1 shows how single-precision (float) and double-precision (double) values are decomposed into • A sign bit • An exponent • A mantissa Floating-point numbers use scientific notation, in which a number is represented as b0 .b1b2b3 … × 2e

bj4_appI.fm Page 1053 Wednesday, November 4, 2009 7:02 PM

Appendix I 1 bit

8 bit

23 bit

sign

biased exponent e + 127

mantissa (without leading 1)

Number Systems 1053

Single Precision 1 bit

11 bit

52 bit

sign

biased exponent e + 1023

mantissa (without leading 1)

Double Precision Figure 1

IEEE Floating-Point Representation

In this representation, e is the exponent, and the digits b0 .b1b2b3 … form the mantissa. The normalized representation is the one where b0 ≠ 0. For example, 100decimal = 1100100binary = 1.100100binary × 26 Because in the binary number system the first bit of a normalized representation must be 1, it is not actually stored in the mantissa. Therefore, you always need to add it on to represent the actual value. For example, the mantissa 1.100100 is stored as 100100. The exponent part of the IEEE representation uses neither signed magnitude nor two’s complement representation. Instead, a bias is added to the actual exponent. The bias is 127 for single-precision numbers, 1023 for double-precision numbers. For example, the exponent e = 6 would be stored as 133 in a single-precision number. Thus, 100decimal = 0 10000101 10010000000000000000000 single-precision IEEE In addition, there are several special values. Among them are: • Zero: biased exponent = 0, mantissa = 0. • Infinity: biased exponent = 11. . .1, mantissa = ±0. • NaN (not a number): biased exponent = 11. . .1, mantissa ≠ ±0.

Hexadecimal Numbers Because binary numbers can be hard to read for humans, programmers often use the hexadecimal number system, with base 16. The digits are denoted as 0, 1, . . . , 9, A, B, C, D, E, F (see Table 2). Four binary digits correspond to one hexadecimal digit. That makes it easy to convert between binary and hexadecimal values. For example, 11|1011|0001binary = 3B1hexadecimal

bj4_appI.fm Page 1054 Wednesday, November 4, 2009 7:02 PM

1054 Appendix I

Number Systems

In Java, hexadecimal numbers are used for Unicode character values, such as \u03B1 (the Greek lowercase letter alpha). Hexadecimal integers are denoted with a 0x prefix, such as 0x3B1.

Table 2 Hexadecimal Digits Hexadecimal

Decimal

Binary

0

0

0000

1

1

0001

2

2

0010

3

3

0011

4

4

0100

5

5

0101

6

6

0110

7

7

0111

8

8

1000

9

9

1001

A

10

1010

B

11

1011

C

12

1100

D

13

1101

E

14

1110

F

15

1111

bj4_appJ.fm Page 1055 Wednesday, November 4, 2009 7:08 PM

Appendix

J

Bit and Shift Operations There are four bit operations in Java: the unary negation (~) and the binary and (&), or (|), and exclusive or (^), often called xor. Tables 1 and 2 show the truth tables for the bit operations in Java. When a bit operation is applied to integer values, the operation is carried out on corresponding bits.

Table 1 The Unary Negation Operation a

~a

0

1

1

0

Table 2 The Binary And, Or, and Xor Operations a

b

a & b

a | b

a ^ b

0

0

0

0

0

0

1

0

1

1

1

0

0

1

1

1

1

1

1

0

For example, suppose we want to compute 46 & 13. First convert both values to binary. 46decimal = 101110 binary (actually 00000000000000000000000000101110 as a 32-bit integer), and 13decimal = 1101binary . Now combine corresponding bits: 0.....0101110 & 0.....0001101 0.....0001100

The answer is 1100binary = 12decimal.

1055

bj4_appJ.fm Page 1056 Friday, November 6, 2009 1:32 PM

1056 Appendix J

Bit and Shift Operations

You sometimes see the | operator being used to combine two bit patterns. For example, Font.BOLD is the value 1, Font.ITALIC is 2. The binary or combination Font.BOLD | Font.ITALIC has both the bold and the italic bit set: 0.....0000001 | 0.....0000010 0.....0000011

Don’t confuse the & and | bit operators with the && and || operators. The latter work only on boolean values, not on bits of numbers. Besides the operations that work on individual bits, there are three shift operations that take the bit pattern of a number and shift it to the left or right by a given number of positions. There are three shift operations: shift left (), and right shift with zero extension (>>>). The left shift moves all bits to the left, filling in zeroes in the least significant bits. Shifting to the left by n bits yields the same result as multiplication by 2n. The right shift with sign extension moves all bits to the right, propagating the sign bit. Therefore, the result is the same as integer division by 2n, both for positive and negative values. Finally, the right shift with zero extension moves all bits to the right, filling in zeroes in the most significant bits. (See Figure 1.) Note that the right-hand-side value of the shift operators is reduced modulo 32 (for int values) or 64 (for long values) to determine the actual number of bits to shift.

0

Left shift ()

0

0

Right shift with zero extension (>>>) Figure 1

The Shift Operations

0

bj4_appJ.fm Page 1057 Wednesday, November 4, 2009 7:08 PM

Appendix J

Bit and Shift Operations 1057

For example, 1 >> (right angle brackets), right shift with zero extension operator, 1056–1057 ’ (single quotes), XML attribute delimiters, 908 / (slash), division operator, 138 /**...*/ (slash asterisks...), comment delimiter, 89, 1039 | (vertical bar), binary or, 1055–1056 || (vertical bars), or logical operator confusing with &&, 199 definition, 196 negating, 200 SQL database queries, 876 in SQL queries, 876 40-hour week, Extreme Programming, 509 404 Not Found message, 857 ) SQL inequality operator, 876 type variable delimiters, 726 anonymous classes, 387–388 anonymous objects, 387–388 ANSI (American National Standards Institute), 650–651 antitrust suit, 58 Apache Derby, downloading, 881 API documentation, 49–51 apostrophe (‘), encoding in DTDs, 930 append method, javax.swing.JTextArea class, 743, 1024 Apple II, 357 Apple Macintosh, 359 applets displaying, 1043, 1046 graphical applications, 63–65 applets package, 352t application-level network protocols, 842–845 Applied Cryptography, 783 arc cosines, 141t arc sines, 141t arc tangent, 141t archiving files, 1047 arguments, passing to programs, 472–473 Ariane rocket incident, 495–496 arithmetic operations. See also numbers; static methods * (asterisk), multiplication operator, 138 - (minus sign), subtraction operator, 138 -- (minus signs), decrement operator, 13 (percent sign), remainder of division operator, 139 + (plus sign), addition operator, 138 ++ (plus signs), increment operator, 138 / (slash), division operator, 138 abs method, 141t absolute values, 141t acos method, 141t addition, 138. See also incrementing arc cosines, 141t arc sines, 141t arc tangent, 141t

asin method, 141t atan method, 141t atan2 method, 141t

big numbers, 130 binary numbers, 130–132 calculations in SQL database queries, 876–877 casting, 140–141 ceil method, 141t combining with assignment, 145 computation overflow, 128 constants, 133–137 cos method, 141t cosines, 141t decrementing, 138. See also subtraction division, 138, 139 exp method, 141t exponential notation, 35 exponentiation, 141t expressions, 35 floor method, 141t fractional numbers. See floating-point numbers How To example, 146–149 incrementing, 138. See also addition integer division errors, 142–143 largest integer, determining, 141t log method, 141t max method, 141t methods for. See static methods min method, 141t multiplication, 138 natural logs, 141t number literals, 35 pow method, 139–140, 141t powers, 139–140 primitive types, 128–129t remainder of division, 139 roots, 139–140 round method, 141t rounding, 140–141, 141t rounding errors, 129 sin method, 141t sine, in radians, 141t smallest integer, determining, 141t sqrt method, 139–140, 141t square roots, 139–140, 141t subtraction, 138. See also decrementing tan method, 141t tangents, 141t toDegrees method, 141t toRadians method, 141t whole numbers. See integers Worked Example: volume and surface of a pyramid, 149 arithmetic operations, conversions. See also casting

bj4_index.fm Page 1086 Friday, November 6, 2009 5:09 PM

1086 Index arithmetic operations, conversions (continued) binary to decimal, 130 decimal to binary, 131 degrees to radians, 141t double to int, 140–141 fractions to binary, 131 integers to binary, 131 radians to degrees, 141t rounding errors, 129 ARPANET, 69 array lists auto-boxing, 289–290 heaps, 704 How To example, 304–306 inserting elements, 285–286, 289–290 java.util.ArrayList class, 283–288 printing, 303 removing elements, 285–286 size, determining, 288 syntax, 284 variable-size objects, 283–288 wrapper classes, 289–290 arraycopy method, java.lang.System class, 1006 ArrayList constructor, java.util.ArrayList class, 1012 ArrayListTester.java class, 286 arrays bounds errors, 278, 279 declaring, examples, 278t definition, 276 fixed length, 278 generic, 733–734 heaps, 704 How To example, 304–306 initialization, 276–277 iterating through, 291–292 length, determining, 288 length of, 276 matrices, 310–314 multidimensional, 314 of objects, 280–281 parallel, 280–281 partially filled, 292–294 printing, 303 printing element separators, 300–303 sequences of related values, 280 specifying elements of, 277 syntax, 279 two-dimensional, 310–314 underestimating data size, 294 variable row lengths, 313–314 Worked Example: world population table, 313 arrays, common algorithms

animated lessons, 297, 298 averaging elements, 295 copying arrays, 299–300 counting matches, 295 element position, finding, 297 filling, 295 growing arrays, 299–300 inserting elements, 298 maximum value, finding, 296 minimum value, finding, 296 printing element separators, 300–303 removing elements, 297–298 searching for values, 296 summing elements, 295 ArrayUtil.java class, 599 artificial intelligence, 201–202 asin method, java.lang.Math class, 141t, 1002 assignment, combining with arithmetic operations, 145 assignment statements vs. variable declarations, 40–41 associating keys and values. See maps association relationships, UML, 517–518 asterisk (*), multiplication operator, 138 asymmetric bounds, 235 Asynchronous JavaScript and XML (AJAX), 973–974 atan method, java.lang.Math class, 141t, 1002 atan2 method, java.lang.Math class, 141t, 1002 ATM (Automatic Teller Machine). See case studies, ATM ATMFrame.java class, 544–546 ATM.java class, 537–539 ATMSimulator.java class, 541–543 ATMViewer.java class, 543 attributes HTML, 1043 UML, 516–517 attributes, XML defaults, 933–934 setting, 923 types, 932 attributes, XML documents definition, 908 naming conventions, 908 parsing, 917 Augusta, Ada, 614 -author option, 1049 @author tag, 1048 auto-boxing, 289–290 autoindent feature, 176 averaging array elements, 295 AVG function, 877

bj4_index.fm Page 1087 Friday, November 6, 2009 5:09 PM

Index 1087 await

method, java.util.concurrent.locks.Condition

interface, 819, 822, 1019 B

Babbage, Charles, 613–614 Babbage’s Analytical Engine, 614 Babbage’s Difference Engine, 613–614 backslash (\) displaying, 152–153 escape character, 152–153, 470 in file names, 470 in TEX typesetting program, 914 backup strategies, tips for, 18 BadDataException.java class, 495 balanced binary search trees, 691–692 BankAccount.java class array lists, 287–288 bank database, 896–897 class implementation, 94–95 deadlocks, 821–822 race conditions, 814–815 BankAccountTester.java class, 99–100 BankAccountThreadRunner.java class, 812–813, 820 BankClient.java class, 854 BankData.java class, 788–790 Bank.java class, 301–302, 539–540, 853–854, 895–896 BankServer.java class, 851 BankService.java class, 851–853 BankSimulator.java class, 787–788 BankTester.java class, 302–303, 307 base directory, packages, 354–355 batch files, 308–309 Beck, Kent, 508 Berners-Lee, Tim, 69 big numbers, 130 BigDecimal constructor, java.math.BigDecimal class, 1007 BigInteger constructor, java.math.BigInteger class, 1007 big-Oh notation, 603, 605–606 big-Omega notation, 605–606 big-Theta notation, 605–606 binary data bits, 778 I/O. See reading binary data; writing binary data binary data, bytes definition, 778 negative values, 782–783 binary expression operators, 1030 binary number system, 1050–1051

binary numbers converting to decimal, 130 overview, 130–132 binary search trees. See also data structures; hashing data structures; heaps balanced, 691–692 BinarySearchTree.java class, 693–696 characteristic property of, 686–688 child nodes, 686 finding nodes, 690 height of, 692 inorder traversal, 697 insert positions, 690 inserting nodes, 688–690 leaf nodes, 686 left children nodes, 686 postorder traversal, 697–698 preorder traversal, 697 printing, 696–698 red-black trees, 692 removing nodes, 690–691 reverse Polish notation, 697–698 right children nodes, 686 root nodes, 686 self-organizing structure, 690 traversing, 696–698 unbalanced, 692 binary searches definition, 617 overview, 616–619 binary trees, 686–687. See also heaps binarySearch method java.util.Arrays class, 619, 1013 java.util.Collections class, 1014 BinarySearcher.java class, 617–618 BinarySearchTree.java class, 693–696 bit operations & (ampersand), binary and, 1055–1056 ^ (caret), binary exclusive or, 1055–1056 - (hyphen), unary negation, 1055–1056 > (right angle brackets), right shift with sign extension operator, 1056–1057 >>> (right angle brackets), right shift with zero extension operator, 1056–1057 | (vertical line), binary or, 1055–1056 shift operations, 1056–1057 bits, 778 black box, 84 black-box testing, 202 block statements, 173 Boehm, Barry, 508 Booch, Grady, 1058

bj4_index.fm Page 1088 Friday, November 6, 2009 5:09 PM

1088 Index books and publications Applied Cryptography, 783 Core Java 2 Volume 1: Fundamentals, 747 Core JavaServer Faces, 963 A Guide to the SQL Standard: A User’s Guide...., 872 The Java Language Specification, 922 The Mythical Man-Month, 510 The Unified Modeling Language User Guide, 508, 1058 Boole, George, 195 boolean data type, 129t, 195, 289 Boolean expressions. See also comparing values && (ampersands), and logical operator, 196, 199, 200 ! (exclamation point), not logical operator, 196–197 || (vertical bars), or logical operator, 196, 199, 200 De Morgan’s Law, 200 flowchart of, 197 lazy evaluation, 200 multiple relational, 199 negating && and || operators, 200 predicate methods, 195–196 short circuit evaluation, 200 Boolean constructor, java.lang.Boolean class, 1000 Boolean variables, 198 booleanValue method, java.lang.Boolean class, 1000 BorderLayout constructor, java.awt.BorderLayout class, 991 borders, GUIs layout, 746 for panels, 748–749 boundary test cases, 203, 204 bounds errors, arrays, 278, 279 Brandeis, Louis, 880 break statements, 188, 246–247 breakpoints, 258, 562 Brooks, Fred, 510–511 buffer overrun attacks, 282–283 buffers, Internet, 846 Buffon needle experiment, 250–255 bugs definition, 19 first recorded, 262 Burroughs, 57–58 bus (computer), 5 business logic, separating from presentation logic, 953 business logic tier, JSF example, 965–972 buttons

groups, JSF example, 964 javax.swing.JButton class, 396–399 javax.swing.JLabel class, 396–399

labels, 396–399 overview, 396–399 panels, 397 ButtonViewer.java class, 392 byte data type, 129t, 289 bytes definition, 778 negative values, 782–783 C

C programming language, 407 C++ programming language, 407 cache directories, 856–857 Caesar cipher, 780–782 CaesarCipher.java class, 781 CaesarEncryptor.java class, 782 calculations in SQL database queries, 876–877 calendar, Worked Example, 54 call by reference, 337–338 call by value, 337–338 call stack, recursion, 562 callbacks, 381–385 camel-case method names, 37 candidate classes, listing, 512 car shape, drawing, 106–110 CarComponent.java class, 108–109 caret (^), binary exclusive or, 1055–1056 CarViewer.java class, 110 case, converting to upper case, 42 case sensitivity coding guidelines, 1066 Java programs, 15 SQL, 867 variables, 1030 XML, 907 case studies exception handling, 491–495 relational databases, 893–898 case studies, ATM ATMFrame.java class, 544–546 ATM.java class, 537–539 ATMSimulator.java class, 541–543 ATMViewer.java class, 543 Bank.java class, 539–540 CRC cards, 531–534 Customer.java class, 540–541 implementation, 536–548 KeyPad.java class, 546–548 machine state, 532–533 method documentation, 535–536

bj4_index.fm Page 1089 Friday, November 6, 2009 5:09 PM

Index 1089 requirements, 529–531 state diagrams, 533–534 UML diagrams, 534–535 case studies, printing invoices Address.java class, 528–529 CRC cards, 519–521 implementation, 524–529 Invoice.java class, 526–527 InvoicePrinter.java class, 525 LineItem.java class, 527 method documentation, 522–524 overview, 518 Product.java class, 528 requirements, 519 UML diagrams, 521–522 CashRegister.java class, 135–136 CashRegisterSimulator.java class, 156–157 CashRegisterTester.java class, 136 casting, 140–141, 379 catch clauses, 485–487, 489 catching exceptions, 485–487 CDATA type, 933 ceil method, java.lang.Math class, 141t, 1003 CENTER region, java.awt.BorderLayout class, 746 central processing unit (CPU), 3–4 Cerf, Vinton, 69 char data type, 129t, 153–154, 289. See also strings character data. See strings character literals vs. string literals, 153 characters, reading, 476–477 charAt method, java.lang.String class, 154 checkboxes creating, 749 grouping, JSF example, 964 testing, 749 checked exceptions, 483–485 CheckingAccount.java class, 432 child elements, 908, 912 child names, determining, 916 child nodes, binary search trees, 686 chips (computer), 3–4 circles, drawing, 65–66 class diagrams, UML, 514–516 .class file extension, 16 class files, Java programs, 16 class invariants, 341–342 class methods. See static methods classes. See also methods; objects abstract, 437 actors, 328 anonymous, 387–388 coding guidelines, 1062–1063

collections of. See libraries; packages concrete, 437 converting from XML documents, 920–921 converting to/from interface types, 378–379 documentation. See API documentation generic, 283 immutable, 332 importing from packages, 51, 353 instances, 83 instantiation, 437 interdependencies. See coupling vs. interface types, 374 naming conventions, 37 overview, 328–329 private, 42 public. See public interfaces syntax summary, 1030–1032 testing, interactively, 53–54 utility, 329 classes, implementing constructors, implementing, 97–98 How To example, 96–98 instance variables, specifying, 97 method declaration, syntax, 94 methods, implementing, 97–98 overview, 92–94 testing the class, 98–100 Worked Example: menus, 98 classes, inner as listeners, 394–396 overview, 385–387 classes, object-oriented design aggregation, 514 candidates, listing, 512 collaborators, 512 CRC (classes, responsibilities, collaborators) card method, 512–513, 516 dependency relationship, 514 discovering, 511–513 has-a relationship, 514 is-a relationship, 514 nouns in the task description, 511–512 relationships, documenting, 513–515 responsibilities, 512 verbs, in the task description, 512 -classpath option, 1049 ClickListener.java class, 392 client programs description, 845–848 designing, How To example, 855–856 clone method java.lang.Object class, 1004 overriding, 448

bj4_index.fm Page 1090 Friday, November 6, 2009 5:09 PM

1090 Index cloning mutable instance variables, 451–452 PCs, 358 close method java.io.InputStream class, 997 java.io.OutputStream class, 780, 998 java.io.PrintStream class, 998 java.net.ServerSocket class, 1008 java.net.Socket class, 1008 java.sql.Connection interface, 886, 1009 java.sql.ResultSet interface, 888, 1010 java.sql.Statement class, 888, 1012 close method, java.io.PrintWriter class automatic close, 490 automatic object closing, 490 closing output files, 469 method summary, 469, 998 close method, java.util.Scanner class automatic close, 490 method summary, 1018 closing objects automatically, 490 code, Java programs creating, 15 modifying, 15 code coverage, 202–205 code units, 153–154 coding guidelines, Java. See also standards for coding { } (curly brackets), aligning, 1067 case sensitivity, 1066 classes, 1062–1063 constants, 1063–1064 control flow, 1064–1066 exceptions, 1065–1066 if statements, 1064–1065 indentation, 1066–1067 lexical issues, 1066–1067 methods, 1063 naming conventions, 1066 nonlinear flow control, 1065 overview, 1061–1062 source files, 1062 for statements, 1065 unstable layout, 1067 variables, 1063–1064 white space, 1066–1067 coding standards, Extreme Programming, 509 cohesiveness, public interfaces, 329–331 CoinHashCodePrinter.java class, 684–685 Coin.java class, 683–684 collaborator classes, 512 collection classes, Java 7 enhancements, 672–673 collection literals, 672–673

collections of classes. See libraries; packages code. See libraries collective ownership, Extreme Programming, 509 collisions, hash codes, 675–676 Color constructor, java.awt.Color class, 991 color viewer creating, 768–770 illustration, 765 colors fills, 67 overview, 67–69 pen, changing, 67 predefined, 67t ColorViewerFrame.java class, 768–770 ColorViewer.java class, 768 columns, database. See also rows, database; tables, database definition, 866 indexes, 889 names, getting, 889 number of, getting, 889 replicating, 873 selecting, 875–876 columns, GUI sizing, 747 spanning, 747 specifying, 743 columns, Web applications, 963 combining files, 1047 combo boxes adding items to, 750 creating, 750–751 default selections, 751 editing, 750 getting selected items from, 750 comma (,), in number literals, 35 command line arguments, 472–473 comments. See also documentation /*...*/ (slash asterisk...), comment delimiters, 14, 1039 /**...*/ (slash asterisks...), comment delimiter, 89, 1039 // (slashes), comment delimiter, 12 -author option, 1049 @author tag, 1048 -classpath option, 1049 -d option, 1049 @deprecated tag, 1048 extracting, 1049 javadoc summary, 1048–1049 -link option, 1049 methods, 89–91 @param tag, 1048

bj4_index.fm Page 1091 Friday, November 6, 2009 5:09 PM

Index 1091 public interfaces, 89–92 @return tag, 1048 @see tag, 1048 -sourcepath option, 1049 syntax summary, 1039 @throws tag, 1048 @version tag, 1048 COMMIT command, 898–899 commit method, java.sql.Connection interface, 898, 1009 committing database changes, 898–899 Comparable interface, 667 compare method, java.util.Comparator interface, 622, 1015 compareTo method java.lang.Comparable interface, 620, 621, 1001 java.lang.String class, 179, 1005 comparing values. See also Boolean expressions; decisions; if statements adjacent, 238 break statements, 188 compareTo method, 179 else statements, dangling, 191–192 enumeration types, 194–195, 454 equals method, 179–181, 181–182 floating-point numbers, 177–178 multiple alternatives, 185–188 nested branches, 188–191 objects, 181–182 relational operators, 177 roundoff errors, 177–178 side effects, 182 strings, 179–181 switch statements, 187–188 syntax, 178 testing for null, 182 compilers definition, 8 Java compiler, options, 1045 parsing program source, 923 compile-time errors, definition, 18–19 compiling, Java programs, 15–17 component objects constructing, 60 drawing on, 60–65 component size, default, 400 compound statements, 173 compressing files, 1047 computation overflow, 128 computers, anatomy of bus, 5 chips, 3–4 CPU (central processing unit), 3–4 directories, 17. See also files

file system, 17. See also files folders. See directories hard disks, 4, 5 memory chips (illustration), 4 memory module (illustration), 4 motherboard, 5 networks, 4 peripheral devices, 4 RAM (random access memory), 4 removable storage, 4 schematic diagram, 6 storage (primary), 4. See also RAM (random access memory) storage (secondary), 4. See also hard disks; removable storage transistors, 4 computers, history of Ada programming language, 614 antitrust suit, 58 Apple II, 357 Apple Macintosh, 359 ARPANET, 69 Babbage’s Analytical Engine, 614 Babbage’s Difference Engine, 613–614 Burroughs, 57–58 cloning PCs, 358 Control Data, 57–58 DARPA, 69 e-mail, 69 ENIAC, 6–7 first usable electronic computer, 6–7 GE, 57–58 GNU (GNU’s Not Unix), 69 Honeywell, 57–58 IBM, 57–58 IBM Personal Computer, 358–359 the Internet, 69–70 Internet Explorer, 70 mainframes, 57–58 microprocessors, 357 Microsoft, 359 Mosaic, 70 NCR, 57–58 personal computers, 357–359 Project Gutenberg, 69 RCA, 57–58 Seven Dwarfs, 57–58 spreadsheet programs, 357–358 TCP/IP (Transmission Control Protocol/ Internet Protocol), 69 Univac Corporation, 57–58 user interface, 359 vacuum tubes, 6–7 VisiCalc, 357–358 Web browsers, 70 World Wide Web, 70 computing, limitations of, 576–578

bj4_index.fm Page 1092 Friday, November 6, 2009 5:09 PM

1092 Index computing hash codes. See hash codes, computing computing totals, 236 concatenating strings, 149–150 concrete classes, 437 condition objects, 818 conditional operator, 176 connecting to databases, 886, 892 consistency, public interfaces, 331–332 console window, reading input from, 156 constants coding guidelines, 1063–1064 declaration syntax, 134 definition, 133 distinguishing from variables, 133 final reserved word, 133 identifying, 133 interface types, 377–378 magic numbers, 137 naming conventions, 133 using, 134–137 constraining type parameters, 730–731 constructing component objects, 60 objects, 46–47 rectangles, 46–47 constructors calling other constructors, 104 constructing objects, 46–47 declaring as void, 89 definition, 87 duplicate names, 87 implementing, 97–98 vs. methods, 47, 87 reinitializing existing objects, 47 subclasses, 430–432 superclass, calling, 431 syntax summary, 1035 type parameters, inferring from variable types, 672–673 uninitialized object references, 101–102 containers choosing, 673–674 as event listeners, 399–400 contains method, java.util.Collection interface, 668, 685, 1014 continue statements, 246–247 continuous integration, Extreme Programming, 509 Control Data, 57–58 control flow, coding guidelines, 1064–1066 converting strings to numbers, 150 cookies, 955 © (copyright) HTML entity, 1044 copy protection, 714–715

copying arrays, 299–300 objects. See clone method copyOf method, java.util.Arrays class, 299, 1013 Core Java 2 Volume 1: Fundamentals, 747 Cornell, Gary, 747 cos method, java.lang.Math class, 141t, 1003 cosines, 141t COUNT function, 876–877 counters, 236–237 counting matches in arrays, 295 keeping a counter, 236–237 CountryValue.java class, 479–480 coupling, public interfaces, 329–331 CPU (central processing unit), 3–4 CRC cards. See also UML (Unified Modeling Language) description, 512–513 example, 513 summary of, 1058 UML diagrams, 516 CRC cards, case studies ATM, 531–534 printing an invoice, 519–521 CREATE TABLE command, 866 createElement method, org.w3c.dom.Document interface, 923, 1027 createLSSerializer method, org.w3c.dom.ls.DOMImplementationLS

interface, 925, 1028 createStatement method, java.sql.Connection interface, 887, 1009 createTextNode method, org.w3c.dom.Document interface, 923, 1027 creating. See implementing credit card processing, 244 curly brackets ({ }) around method statements, 12 array initialization, 277 in block statements, 173 coding guidelines, 1067 lining up, 174–175 in TEX typesetting program, 914 currentTimeMillis method, java.lang.System class, 599, 1006 Customer.java class, 540–541 customizing, frames, 456–458 CYC project, 201–202 D

option, 1049 DARPA

-d

bj4_index.fm Page 1093 Friday, November 6, 2009 5:09 PM

Index 1093 computer-controlled vehicles, 202 history of computers, 69 Darwen, Hugh, 872 data structures. See also linked lists abstract arrays, 649 abstract data types, 647–650 abstract lists, 649 containers, choosing, 673–674 FIFO (first in, first out), 652 finding elements. See binary search trees; hashing data structures hashing. See hash; hashing How To example: choosing containers, 673–674 LIFO (last in, first out), 651 priority queues, 698–699 queues, 651–653 random access, 631, 648 run-time stacks, 652 sequential access, 631, 648 stacks, 651–653 Worked Example: reverse Polish notation, 654 Worked Example: word frequency, 674 data structures, heaps array lists, 704 arrays, 704 definition, 699 fixing the heap, 702–704, 710 HeapDemo.java class, 709 heapsort algorithm, 709–714 HeapSorter.java class, 712–714 inserting elements, 700–701 MinHeap.java class, 705–708 as priority queues, 705–708 removing root elements. See fixing the heap sorting, 709–714 structure of, 699–700 WorkOrder.java class, 708 data structures, maps adding associations, 671 associating keys and values, 670–672 changing associations, 671 definition, 670 get method, java.util.Map interface, 671 hash maps, 671–672 java.util.HashMap class, 671 java.util.TreeMap class, 671 key values, null, 671 key values, returning, 671 keySet method, java.util.Map interface, 671 MapDemo.java class, 672 order of elements, 671–672

printing key/value pairs, 671 put method, java.util.Map interface, 671 reference to, storing, 671 remove method, java.util.Map interface, 671 removing keys and values, 671 tree maps, 671–672 data structures, sets adding elements, 668 Comparable interface, 667 contains method, java.util.Collection interface, 668, 685 definition, 666 duplicate elements, 666 “for each” loops, 668 hash tables, 667 hashCode method, 667 HashSet structures, 667–668, 670 hasNext method, 668 interface references, 670 iterating through elements, 668 Iterator vs. ListIterator, 668 java.util.HashSet class, 667–668 java.util.TreeSet class, 667–668 LinkedList references, 670 List references, 670 listing elements, 668 next method, 668 random access, 668 removing elements, 668 sorted access, 667–668 SpellCheck.java class, 668–669 stepping through the set, 668 testing for elements, 668 trees, 667 TreeSet structures, 667–668, 670 data types. See also arithmetic operations boolean, 129t byte, 129t char, 129t, 153–154. See also strings character data. See strings combining. See expressions definition, 34 double, 34–35, 129t exponential notation, 35 expressions, 35 float, 129t floating-point numbers. See floatingpoint numbers fractional numbers. See double data type; floating-point numbers generic, syntax summary, 1039 int, 129t integers. See integers long, 129t number literals, 35

bj4_index.fm Page 1094 Friday, November 6, 2009 5:09 PM

1094 Index data types (continued) parameters, specifying, 45 primitive types, 128–129t, 1029 reference types, 1029 short, 129t syntax summary, 1029 testing for, 434 variable, specifying, 36–37 whole numbers. See integers DataAnalyzer.java class, 239–240, 492 database access package, 352t databases. See relational databases DataSet.java class, 240–241, 384 DataSetReader.java class, 494–495 DataSetTester2.java class, 384–385 DataSetTester3.java class, 386–387 DataSetTester.java class, 376–377 Date, Chris, 872 Date constructor, java.util.Date class, 1015 de Buffon, Georges-Louis Leclerc, 250 De Morgan’s Law, 200 deadlocks, 818–824 deadly embrace. See deadlocks debuggers. See also testing programs breakpoints, 258 definition, 19, 257 description, 257–260 inspect-variable command, 259 set breakpoint command, 258 single-step command, 259–260 step-into command, 259–260 step-over command, 259–260 debugging. See also testing programs How To example, 260–261 recursion, 562 Worked Example: sample session, 261 decimal numbers, converting to binary, 131 decisions. See also comparing values conditional operators, 176 if statements, 172–176, 1064–1065 declaring. See also implementing generic classes, syntax, 727 generic methods, syntax, 729 interface types, 373–374 variables, 37 decrementing, 138. See also subtraction decryption, 780. See also encryption default package, 352 defensive programming, 19 degrees, converting to radians, 141t DELETE command, 843 deleting. See removing dependency diagrams, 1060 dependency relationship symbol, UML, 515t

dependency relationships, 514 deploying JSF applications, 953–954 deployment phase, software life cycle, 507 DepositRunnable.java class, 813 @deprecated tag, 1048 Derby database, JSF example, 967 design phase, software life cycle, 506 destroy method, java.applet.Applet class, 991 diagrams, drawing, 114 dialog box, javax.swing.JFileChooser class, 471 dialog boxes, reading input from, 159–160 dice casting analyzing, 306 simulation, 251–252 Die.java class, 251–252 DieSimulator.java class, 252 Difference Engine, 613–614 Dijkstra, Edsger, 202 Dimension constructor, java.awt.Dimension class, 992 directories, 17. See also files discovering classes, 511–513 divide method, java.math.BigInteger class, 1007 division integers, 139, 142–143 operator for, 138 DNS (Domain Naming Service), 840 do loops, 227 DOCTYPE declaration, 934–935 Document Object Model package, 352t document type definition (DTD). See DTD (document type definition) documentation. See also comments HTML-based, 92 hyperlinks, 92 javadoc utility, 92 public interface, 89–92, 96–97 dollar sign ($), in names, 37 domain names, 841 dongles, 715 dot (.), in package names, 355 double data type converting to int, 140–141 description, 129t fractional numbers, 34–35 wrapper class, 289 Double constructor, java.lang.Double class, 1001 double quotes (“) encoding in DTDs, 930 HTML entity for, 1044 XML attribute delimiters, 907–908

bj4_index.fm Page 1095 Friday, November 6, 2009 5:09 PM

Index 1095 method, java.lang.Double class, 290, 1001 doubly linked lists, 633 draw method, java.awt.Graphics2D class, 993 drawing, computer graphics diagrams, 114 manipulated images, 115 scenes, 114–115 drawing, shapes. See also graphical applications on components, 60–65 How To example, 110–113 shape classes, 106–110 a simple car, 106–110 drawString method, java.awt.Graphics2D class, 993 DROP TABLE command, 867 DTD (document type definition). See also XML documents & (ampersand), encoding, 930 ’ (apostrophe), encoding, 930 “ (double quotes), encoding, 930 - (hyphen), in attribute values, 933 < (left angle bracket), encoding, 930 > (right angle bracket), encoding, 930 _ (underscore), in attribute values, 933 & (ampersand) encoding, 930 attribute defaults, 933–934 attribute types, 932 CDATA type, 933 creating, How To example, 936–938 definition, 930 DOCTYPE declaration, 934–935 within a document, 934 element content, regular expressions for, 931 elements, EMPTY, 931 #FIXED attribute, 933 > (greater than) encoding, 930 #IMPLIED attribute, 933 < (less than) encoding, 930 mixed content, 932 parsed character data, 930 #PCDATA type, 930 purpose of, 929 " (quotation marks) encoding, 930 #REQUIRED attribute, 933 schema languages, 938–939 special characters, encoding, 930 specifying, 934–935 stored elsewhere, 934 SYSTEM reserved word, 934–935 XML Schema specification, 938–939 duplicate constructor names, 87 elements in sets, 666 doubleValue

hash codes, 675–676 hash codes, avoiding, 682–683 method names, 43 dynamic method lookup, 380, 1034 E E constant, java.lang.Math class, 135 E (element) type parameter, 726 Earthquake.java class, 185–186 EarthquakeRunner.java class, 186 EAST region, java.awt.BorderLayout class, 746 Eckert, J. Presper, 6 editors Java programs, 15 XML documents, 913 efficiency, recursion, 568–573 electronic voting machines, 104–106 elements, XML vs. attributes, 911–912 content, 908 content, regular expressions for, 931 creating, 923 definition, 908 EMPTY, 931 elements, XML documents parsing, 917 separating, 917 Ellipse2D.Double class, 65–66 Ellipse2D.Double constructor, java.awt.geom.Ellipse2D.Double

class, 995 ellipses, drawing, 65–66 else statements, dangling, 191–192 e-mail, history of computers, 69 embedded systems, 832–833 empty strings, 149 EmptyFrameViewer.java class, 59 encapsulation, 84–85, 424 encryption algorithms, 783–785 Applied Cryptography, 783 Caesar cipher, 780–782 decryption, 780 keys, 780 national security concerns, 783 patenting, 783–785 PGP (Pretty Good Privacy), 784 public key, 784 RSA (Rivest Shamir Adelman), 783–785 sample program, 780–782 Skipjack, 783 engineering discipline, 549 ENIAC computer, 6–7 entities, HTML, 1044

bj4_index.fm Page 1096 Friday, November 6, 2009 5:09 PM

1096 Index enumeration types declaring, syntax, 194 description, 194–195, 454 null, 195 syntax summary, 1032–1033 EOFException constructor, java.io.EOFException class, 997 equal sign (=), SQL equality operator, 876 equal signs (==), equality operator vs. = (equal sign), assignment operator, 177t comparing objects, 181 comparing strings, 179 description, 177t testing for null, 182 equals method declaring with wrong parameter type, 450 description, 450–451 java.lang.Object class, 179–182, 1004 java.lang.String class, 1005 overriding, 446–448 equalsIgnoreCase method, java.lang.String class, 1005 erasure, type parameters, 732–734 error handling . (dot), in package names, 355 array bounds errors, 279 array length, determining, 288 array list size, determining, 288 arrays, underestimating data size, 294 bugs, 19 calling undeclared methods, 42 comparing strings with == (equality operator), 180–181 compile-time errors, 18–19 confusing && and || operators, 199 dangling else statements, 191–192 debuggers, 19 declaring constructors as void, 89 declaring implementing methods as public, 377 defensive programming, 19 exception reports, 152 extracting substrings, 151 forgetting event listeners, 399 infinite loops, 225–226 integer division, 142–143 invoking constructors like methods, 47 logic errors. See run-time errors misspelled words, 20 modifying primitive type parameters, 334–336 off-by-one errors, 226 overlapping scope, 350–351 parameter types, modifying, 393–394 repainting graphic components, 402–403

run-time errors, 19 semicolon errors, for loops, 233–234 semicolons in if statements, 176 shadowing, 350–351 string length, determining, 288 string-to-number conversions, 150 syntax errors. See compile-time errors unbalanced parentheses, 143 unfilled arrays, 280 uninitialized arrays, 280 uninitialized object references in constructors, 101–102 variable declarations vs. assignment statements, 40–41 error handling, rounding errors binary/decimal conversions, 129 floating-point numbers, 144–145 escape sequences Java, 152–153 SQL, 867, 871–872 EtchedBorder constructor, javax.swing.border.EtchedBorder class, 749, 1025 evaluate method, javax.xml.xpath.XPath interface, 916, 1026 Evaluator.java class, 582–583 event adapters, 406–407 event listeners containers as, 399–400 inner classes as, 394–396 on menu items, 758 overview, 391–394 event sources, 391–394 events mouse, 403–406 overview, 391–394 timer, 400–403 exception classes constructors for, 490 hierarchy of, 482 exception handlers, 482 exception handling animated lesson, 493 Ariane rocket incident, 495–496 case study, 491–495 catch clauses, 485–487, 489 catching exceptions, 485–487 checked exceptions, 483–485 closing objects automatically, 490 finally clause, 488–489 recovery, 481 reporting, 481 squelching exceptions, 487 throw early, catch late, 487 throw statement, syntax, 483 throwing exceptions, 481–483, 491

bj4_index.fm Page 1097 Friday, November 6, 2009 5:09 PM

Index 1097 throws clause, 484–485 try blocks, 485–487, 490 try/catch statements, 485–487,

489 unchecked exceptions, 483–485 exception reports, 152 exception types, designing your own, 490– 491 exceptions coding guidelines, 1065–1066 syntax summary, 1038 exclamation point, equal (!=), not-equal operator, 177t, 234 exclamation point (!), not logical operator definition, 196–197 in SQL queries, 876 ExecSQL.java class, 890–891 executable algorithms, 23 execute method java.sql.PreparedStatement interface, 887, 1010 java.sql.Statement class, 887, 1012 executeQuery method java.sql.PreparedStatement interface, 887, 1010 java.sql.Statement class, 887, 1012 executeUpdate method java.sql.PreparedStatement interface, 887, 1010 java.sql.Statement class, 887, 1012 executing programs. See starting programs exit method, java.lang.System class, 1006 exp method, java.lang.Math class, 141t, 1003 expert systems, 201–202 explicit parameters, definition, 43 exponential notation, 35 exponentiation, 141t ExpressionCalculator.java class, 584–585 expressions binary operators, 1030 definition, 35 left-associative operators, 1030 order of operations, 35, 1030 postfix operators, 1030 prefix operators, 1030 syntax summary, 1030 ternary operators, 1030 unary operators, 1030 ExpressionTokenizer.java class, 583–584 extends reserved word, type parameters, 731 Extensible Hypertext Markup Language (XHTML), 939 Extensible Markup Language (XML). See XML (Extensible Markup Language) extracting comments, 1049

Extreme Programming, 508–509 F FaceComponent.java ,

68 69 factoring out common code, 144 FIFO (first in, first out), 652 Fifth-Generation Project, 201 file management, operating system services, 388 File constructor, java.io.File class, 997 file names, backslash in, 470 file pointers, 785–786 file system directories, 17 folders. See directories file transfer, Internet, 856 File Transfer Protocol (FTP), 856 FileInputStream constructor, java.io.FileInputStream class, 997 FileOutputStream constructor, java.io.FileOutputStream class, 997 files archiving, 1047 combining, 1047 compressing, 1047 manifest, 1047 organizing. See directories reading. See reading files reading text from. See reading text, from files selecting from a dialog box, 471 storing. See directories fill method, java.awt.Graphics2D class, 993 filling arrays, 295 fills, colors, 67 final reserved word, 133 finally clause, 488–489 finding. See also searching elements in a set, 676 first match, 237 maximum value in arrays, 296 minimum value in arrays, 296 nodes, binary search trees, 690 first in, first out (FIFO), 652 #FIXED attribute, 933 fixing the heap, 702–704, 710 flags Boolean, 198. See also Boolean variables format, 159t float data type, 129t, 289 floating-point numbers. See also arithmetic operations comparing, 177–178 FaceViewer.java ,

bj4_index.fm Page 1098 Friday, November 6, 2009 5:09 PM

1098 Index floating-point numbers (continued) computing hash codes, 682 definition, 34 vs. integers, 34 Pentium bug, 132–133 floor method, java.lang.Math class, 141t, 1003 flow layout, GUI components, 746 FlowLayout constructor, java.awt.FlowLayout class, 992 flushing buffers, Internet, 846 Font constructor, java.awt.Font class, 993 FontViewer2.java class, 759–763 FontViewerFrame.java class, 752–755 FontViewer.java class, 751 “for each” loops, 291–292, 635–636, 668 for loops. See also loops != (not equal), testing end of range, 234 animated lesson, 229 asymmetric bounds, 235 code sample, 230–232 counting iterations, 235–236 description, 228–229 enhanced, 291–292 examples, 232 iterating through arrays, 291–292 semicolon errors, 233–234 symmetric bounds, 235 syntax, 230 uses for, 232–233 variables, declaring, 234–235 for statements, coding guidelines, 1065 foreign keys, database tables, 869 format flags, 159t format method java.lang.String class, 159, 1005 java.text.DateFormat class, 1012 format specifiers, numbers, 158 format types, numbers, 158t formatting, numbers, 158–159 forName method, java.lang.Class class, 886, 1000 40-hour week, Extreme Programming, 509 404 Not Found message, 857 fractional numbers. See double data type; floating-point numbers fractions, converting to binary, 131 Frame class, main method, 457–458 frame windows, 58–59, 62 frames, customizing, 456–458 frameworks, unit testing, 359–360 FTP (File Transfer Protocol), 856 functional programming languages, 408

functions, describing growth behavior. See big-Oh notation G

garbage collector, 101 GE, 57–58 Geary, David, 963 generic arrays, 733–734 objects, 733 types, syntax summary, 1039 generic classes. See also generic methods; type parameters declaring, syntax, 727 definition, 724 implementing, 725–728 PairDemo.java class, 728 Pair.java class, 727 generic methods. See also generic classes declaring, syntax, 729 definition, 728 parameter type, specifying, 729–730 primitive types, 730 syntax summary, 1039 GET command, 843–844 get method java.util.ArrayList class, 284, 1013 java.util.Calendar class, 1014 java.util.Map interface, 671, 1017 getAttribute method, org.w3c.dom.Element interface, 935, 1027 getAvailableIDs method, java.util.TimeZone class, 1019 getCenterX method, java.awt.geom.RectangularShape

class, 996 getCenterY method, java.awt.geom.RectangularShape

class, 996 getColumnCount method, java.sql.ResultSetMetaData

interface,

889, 1011 getColumnDisplaySize method, java.sql.ResultSetMetaData

interface,

889, 1011 getColumnLabel method, java.sql.ResultSetMetaData

interface,

889, 1011 getConnection method java.sql.DriverManager class, 886, javax.sql.DataSource class, 967

1010

getContentLength method, java.net.URLConnection

class, 857, 1009

getContentType method, java.net.URLConnection

class, 857, 1009

bj4_index.fm Page 1099 Friday, November 6, 2009 5:09 PM

Index 1099 getDomConfig method, org.w3c.dom.ls.LSSerializer

java.net.HttpURLConnection

interface,

925, 1028 method, java.sql.ResultSet interface, 889, 1010–1011 getFeature method, getDouble

org.w3c.dom.DOMImplementation

interface, 1027 getFilePointer method, java.io.RandomAccessFile class, 786, 999 getFirst method, java.util.LinkedList class, 631t, 1016 getGlobal method, java.util.logging.Logger class, 205, 1020 getHeight method java.awt.Component class, 992 java.awt.geom.RectangularShape class, 996 java.awt.Rectangle class, 48, 993 getImplementation method, org.w3c.dom.Document interface, 925, 1027 getInputStream method java.net.Socket class, 845, 856–857, 1008 java.net.URLConnection class, 1009 getInt method, java.sql.ResultSet interface, 889, 1011 getLast method, java.util.LinkedList class, 631t getMaxX method, java.awt.geom.RectangularShape

class, 996 getMaxY method, java.awt.geom.RectangularShape

class, 996 method, java.lang.Throwable class method summary, 1007 retrieving error messages, 491 getMetaData method, java.sql.ResultSet interface, 889, 1011 getMinX method, getMessage

java.awt.geom.RectangularShape

class, 996 getMinY method, java.awt.geom.RectangularShape

class, 996 method, java.net.Socket class, 845, 1008 getProperty method, java.util.Properties class, 887, 1017 getResponseCode method, java.net.HttpURLConnection class, 857, 1008 getResponseMessage method getOutputStream

class, 857,

1008 class, 1008 method, java.sql.Statement class, 888, 1012 getSelectedFile method, javax.swing.JFileChooser class, 471, 1022 getSelectedItem method, javax.swing.JComboBox class getting selected items, 750–751 method summary, 1021 getSource method, java.util.EventObject class, 1015 getString method, java.sql.ResultSet interface, 889, 1011 getText method javax.swing.JTextField class, 740 javax.swing.text.JTextComponent class, 1025 getTimeInstance method, java.text.DateFormat class, 959, 1012 getTimeZone method, java.util.TimeZone class, 959, 1019 getUpdateCount method, java.sql.Statement class, 888, 1012 getValue method, javax.swing.JSlider class, 767, 1024 getWidth method java.awt.Component class, 992 java.awt.geom.RectangularShape class, 996 java.awt.Rectangle class, 48, 993 getX method java.awt.event.MouseEvent class, 995 java.awt.geom.Point2D class, 996 java.awt.Rectangle class, 48, 993 getX1 method, java.awt.geom.Line2D class, 995 getX2 method, java.awt.geom.Line2D class, 995 getY method java.awt.event.MouseEvent class, 995 java.awt.geom.Point2D class, 996 java.awt.Rectangle class, 48, 993 getY1 method, java.awt.geom.Line2D class, 995 getY2 method, java.awt.geom.Line2D class, 995 GlassFish application server, 953 GNU (GNU’s Not Unix), 69 Gosling, James, 9, 407 grammars, definition, 920 graphical applications. See also drawing; specific components; specific shapes applets, 63–65 colors, 67–69 component objects, 60 component size, default, 400 drawing on components, 60–65 java.net.Socket

getResultSet

bj4_index.fm Page 1100 Friday, November 6, 2009 5:09 PM

1100 Index graphical applications (continued) frame windows, 58–59, 62 manipulating image pixels, 250 repainting, 401–403 shape classes, 106–110 Worked Example: editing photos, 54 graphical user interfaces (GUIs). See GUIs (graphical user interfaces) Graphics class description, 61 setColor method, 67–68 Graphics2D class casting, 61 description, 61 draw method, 67 drawString method, 66 fill method, 67 “Green,” Java code name, 9 GreetingRunnable.java class, 804 GreetingThreadRunner.java class, 805 GregorianCalendar constructor, java.util.GregorianCalendar class, 1015 grep command, 477 grid bag layout, GUI components, 747 grid layout, GUI components, 746 GridLayout constructor, java.awt.GridLayout class, 993 grow method, java.awt.Rectangle class, 993 growing arrays, 299–300 > (greater than) encoding, DTDs, 930 HTML entity, 1044 GUI builders, 757–758 GUIs (graphical user interfaces). See also user interface; specific components starting programs, 473 GUIs (graphical user interfaces), implementing color viewer (illustration), 765 color viewer, creating, 768–770 ColorViewerFrame.java class, 768–770 ColorViewer.java class, 768 How To example, 763–764 sliders, 765–767 Swing documentation, 764–770 SwingSet demonstration screen, 765 GUIs (graphical user interfaces), layout management arranging components, 746 border layout, 746 borders for panels, 748–749 columns, sizing, 747 columns, spanning, 747 flow layout, 746 grid bag layout, 747

grid layout, 746 GUI builders, 757–758 How To example, 755–757 layout manager, 746 nesting panels, 747 tabular arrangement, 747 GUIs (graphical user interfaces), making choices. See also GUIs (graphical user interfaces), menus adding items to combo boxes, 750 checkboxes, 749 combo boxes, 750–751 default selections, combo boxes, 751 editing combo boxes, 750 FontViewerFrame.java class, 752–755 FontViewer.java class, 751 getting selected items from combo boxes, 750 multiple. See checkboxes; combo boxes mutually exclusive. See radio buttons radio buttons, 748–749 testing checkboxes, 749 testing radio buttons, 748 GUIs (graphical user interfaces), menus. See also GUIs (graphical user interfaces), making choices definition, 758 FontViewer2.java class, 759–763 illustration, 759 listeners, on menu items, 758 menu bars, 758 menu items, 758 submenus, 758 GUIs (graphical user interfaces), reading text input columns, specifying, 743 dialog boxes, 159–160 InvestmentFrame.java class, 741–742, 744–745 InvestmentViewer3.java class, 741 labeling text fields, 740 multiline input, 743–746 rows, specifying, 743 scroll bars, 744 separating lines, 743 setting default text, 743 single-line input, 740–742 text areas, 743–746 text editing, disabling, 743 text fields, 740–742 H

halting problem, 576–578 Hamblin, Charles, 654 hand-tracing loops, 223–225

bj4_index.fm Page 1101 Friday, November 6, 2009 5:09 PM

Index 1101 programs, 192–193 hard disks, 4, 5 hardwired database connections, 892 has-a relationship, 514 hash codes collisions, 675–676 definition, 674 duplicate, 675–676 examples, 675 hash codes, computing CoinHashCodePrinter.java class, 684–685 Coin.java class, 683–684 duplicates, avoiding, 682–683 for floating-point numbers, 682 hashCode method, avoiding duplicates, 682 hashCode method, omitting, 685 by identity, 683 for keys only, 683 from memory location, 683 for strings, 681 hash functions, 674 hash maps, 671–672 hash sets accessing set elements, 667–668 HashSetDemo.java class, 680–681 HashSet.java class, 677–680 vs. tree sets, 667–668 hash tables definition, 674 minimum size, 676–677 sets, 667 hashCode method avoiding duplicates, 682 choosing a container, 674 omitting, 685 sets, 667 hashing data structures. See also binary search trees; data structures adding elements to a set, 676 definition, 674 finding elements in a set, 676 hashCode method, 674 removing elements from a set, 676 HashMap constructor, java.util.HashMap class, 1015 HashSet constructor, java.util.HashSet class, 1015 HashSet structures, 667–668, 670 HashSetDemo.java class, 680–681 HashSet.java class, 677–680 hasNext method java.util.Iterator interface, 632, 1015 java.util.ListIterator interface, 634t, 639 java.util.Scanner class, 1018

stepping through sets, 668 method, java.util.Scanner class method summary, 1018 reading text numbers, 476 testing calls to nextDouble, 196 hasNextInt method, java.util.Scanner class, 196, 1018 hasNextLine method, java.util.Scanner class, 1018 hasPrevious method, java.util.ListIterator interface, 633, 634t, 1016 HEAD command, 843 HeapDemo.java class, 709 heaps. See also binary search trees; binary trees; data structures array lists, 704 arrays, 704 definition, 699 fixing the heap, 702–704, 710 HeapDemo.java class, 709 heapsort algorithm, 709–714 HeapSorter.java class, 712–714 inserting elements, 700–701 MinHeap.java class, 705–708 as priority queues, 705–708 sorting, 709–714 structure of, 699–700 WorkOrder.java class, 708 heapsort algorithm, 709–714 HeapSorter.java class, 712–714 “Hello World” example, Java programs, 11–14 HelloPrinter.java class, 11 hexadecimal number system, 1053–1054 hiding information, encapsulation, 84–85 hierarchies, 420. See also inheritance hierarchies high-level languages, definition, 8 Hoff, Marcian E., 357 Honeywell, 57–58 Horstmann, Cay S., 747, 963 Houston, Frank, 309–310 HP 35 calculator, 654–655 HTML (hypertext markup language) attributes, examples of, 1043 displaying applets, 1043 entities, list of, 1044 vs. HTTP (Hypertext Transfer Protocol), 843 images, including, 1042 introduction to, 1040–1044 linking to other files, 1043 special characters, symbols for, 1044 hasNextDouble

bj4_index.fm Page 1102 Friday, November 6, 2009 5:09 PM

1102 Index HTML (hypertext markup language) (continued) tags, examples of, 1041–1042 white space, 1042 vs. XML, 907 HTML-based documentation, 92 HTTP (Hypertext Transfer Protocol), 842–845 cache directories, 856–857 DELETE command, 843 GET command, 843–844 HEAD command, 843 vs. HTML (hypertext markup language), 843 OPTIONS command, 843 POST command, 843 PUT command, 843 request properties, 856 request/response information, getting, 856–858 TRACE command, 843 hyperlinks, in documentation, 92 hyphen (-) in command line arguments, 472 unary negation, 1055–1056 in XML attribute values, 933 I

IBM, 57–58 IBM Personal Computer, 358–359 IEEE floating-point number system, 1052–1053 IETF (Internet Engineering Task Force), 650 if statements ; (semicolon), statement terminator, 176 { } (curly brackets), in block statements, 173 { } (curly brackets), lining up, 174–175 autoindent, 176 block statements, 173 coding guidelines, 1064–1065 compound statements, 173 description, 172–173 flowchart of, 173 How To example, 183–185 indentation, 175 nesting levels, 175–176 simple statements, 173 syntax, 174 tab characters, 176 Tab key, 175 tabs, 175–176 IllegalArgumentException constructor, java.lang.IllegalArgumentException

class, 1001 image pixels, manipulating, 250

constructor, javax.swing.ImageIcon class, 1021 images drawing. See drawing; graphical applications including in HTML, 1042 immutable classes, 332 implementation phase, software life cycle case study, ATM, 536–548 case study, printing an invoice, 524–529 definition, 506 implementing. See also declaring classes. See classes, implementing constructors, 97–98 generic classes, 725–728 interface types, 374–376, 377 methods, 97–98 implements reserved word, 374 implicit parameters, definition, 43 #IMPLIED attribute, 933 import directive, 353 importing, classes from packages, 51, 353 in method, java.lang.System class, 156 incrementing, 138. See also addition indentation, coding guidelines, 175, 1066–1067 indexes database columns, 889 database tables, 872–873 infinite loops, 225–226 infinite recursion, 561 INFO constructor, java.util.logging.Level class, 205 info method, java.util.logging.Logger class, 205, 1020 inheritance. See also polymorphism clone method, overriding, 448 vs. creating an interface, 425 customizing frames, 456–458 encapsulation, 424 relationship symbol, UML, 515t syntax, 424 type parameters, 731 inheritance, equals method declaring with wrong parameter type, 450 description, 450–451 overriding, 446–448 inheritance, toString method for all classes, 449 description, 449 overriding, 445–446 inheritance hierarchies. See also subclasses; superclasses definition, 420 description, 420–422 ImageIcon

bj4_index.fm Page 1103 Friday, November 6, 2009 5:09 PM

Index 1103 How To example, 440–444 Worked Example: employee hierarchy, 444 init method, java.applet.Applet class, 991 initialization arrays, 276–277 instance variables, 101 variables, 39–40, 101 initialization blocks, 347–348 inner classes as event listeners, 394–396 as listeners, 394–396 overview, 385–387 static, 646 inorder traversal, binary search trees, 697 input, reading. See reading input/output package, 352t InputStreamReader constructor, java.io.InputStreamReader class, 998 INSERT INTO command, 867 insert positions, binary search trees, 690 inserting. See also adding elements into heaps, 700–701 nodes, binary search trees, 688–690 trace messages, 569 insertion sorts, 604–605 inspect-variable command, 259 instance methods, 146, 1034 instance variables. See also variables access specifiers, 83 definition, 83 initialization, 101 initialization blocks, 347–348 interface types, 377 vs. local, 101 mutable, cloning, 451–452 name, 83 parts of, 83 protecting, 439 shadowing, 426 specifying, 82–84, 97 subclasses, 423–424 syntax, 83 type, 83 instanceof operator, 434 instances, of classes, 83 instantiation classes, 437 interface types, 379 int data type, 129t, 289 Integer constructor, java.lang.Integer class, 1001 integers. See also arithmetic operations computation overflow, 128

converting from strings. See parseInt method converting to binary, 131 definition, 34 vs. floating-point numbers, 35 integrated circuits. See chips Intel Corporation, Pentium floating-point bug, 132–133 interdependencies, classes. See coupling interface implementation relationship symbol, UML, 515t interface references, sets, 670 interface types callbacks, 381–385 vs. classes, 374 constants, 377–378 converting to/from classes, 378–379 declaring, 373–374 implemented by multiple classes. See polymorphism implementing, 374–376, 377 implements reserved word, 374 instance variables, 377 instantiating, 379 overview, 372–373 UML diagram, 376 Worked Example: number sequences, 381 interfaces vs. inheritance, 425 syntax summary, 1032 interleaving threads, 805 international characters, 153–155 International Organization for Standardization (ISO), 650–651 Internet buffers, 846 client programs, 845–848 definition, 840 DNS (Domain Naming Service), 840 domain names, 841 file transfer, 856 flushing buffers, 846 history of computers, 69–70 How To example: designing client/server programs, 855–856 IP addresses, 840–842 ISPs (Internet service providers), 840 packets of data, 841 sockets, 845–846 Telnet program, 843–844 WebGet.java class, 847–848 worms, 282–283 Internet, network protocols application level, 842–845 definition, 840. See also specific protocols DELETE command, 843

bj4_index.fm Page 1104 Friday, November 6, 2009 5:09 PM

1104 Index Internet, network protocols (continued) FTP (File Transfer Protocol), 856 GET command, 843–844 HEAD command, 843 HTTP (Hypertext Transfer Protocol), 842–845 IP (Internet Protocol), 840 OPTIONS command, 843 port numbers, 842 POST command, 843 PUT command, 843 TCP (Transmission Control Protocol), 841–842 TCP/IP (Transmission Control Protocol/ Internet Protocol), 841 TRACE command, 843 URL (Uniform Resource Locator), 842–845 URL connections, 856–859 URLGet.java class, 858–859 Internet, server programs BankClient.java class, 854 Bank.java class, 853–854 BankServer.java class, 851 BankService.java class, 851–853 description, 848 How To example: designing client/server programs, 855–856 killing, 850 server sockets, 849 Internet Engineering Task Force (IETF), 650 Internet Explorer, 70 interpreted scripting languages, 455 inter-program communication, operating system services, 389 interrupted method, java.lang.Thread class, 807, 1006 interrupting threads, 807–809 intersection method, java.awt.Rectangle class, 993 intValue method, java.lang.Integer class, 1001 InvestmentFrame.java class, 741–742, 744–745 Investment.java class, 220–221, 230–231 InvestmentRunner.java class, 221, 231 InvestmentViewer1.java class, 395–396 InvestmentViewer2.java class, 398–399 InvestmentViewer3.java class, 741 Invoice.java class, 526–527 InvoicePrinter.java class, 525 invoices, printing. See case studies, printing invoices invoking programs. See starting programs I/O hierarchy of classes for, 778

input. See reading output. See writing IP (Internet Protocol), 840 IP addresses, 840–842 is-a relationships, 376, 514 isDigit method, java.lang.Character class method summary, 1000 reading text, line by line, 474 testing characters, 196 isEditable method javax.swing.JComboBox class, 1021 javax.swing.text.JTextComponent class, 1025 isLetter method, java.lang.Character class, 196, 1000 isLowerCase method, java.lang.Character class, 196, 1000 ISO (International Organization for Standardization), 650–651 ISPs (Internet service providers), 840 isSelected method, javax.swing.AbstractButton class, 749, 1020 isUpperCase method, java.lang.Character class, 196, 1000 isWhiteSpace method, detecting whitespace, 474–475 ItemListBuilder.java class, 925–927 ItemListParser.java class, 917–919 iterating through arrays, 291–292 set elements, 668 iteration. See enumeration types; for loops; loops; while loops iterator method, java.util.Collection interface, 1014 Iterator vs. ListIterator, 668 iterators, linked lists, 631–633 J

Jacobson, Ivar, 1058 JAR (Java Archive) tool, 1047 Java Community Process, 651 Java Database Connectivity (JDBC), 881 Java language. See also Java programs code name “Green,” 9 collection classes, Java 7 enhancements, 672–673 collection literals, 672–673 collections of code. See libraries history of, 407 portability, 10 safety, 10 security, 10 versions, summary of, 10t

bj4_index.fm Page 1105 Friday, November 6, 2009 5:09 PM

Index 1105 The Java Language Specification, 922 Java operators, summary of, 983t–984t. See also specific operators Java programs. See also Java language; programs; specific elements basic structure, 11–14 case sensitivity, 15 class files, 16 collections of code. See libraries compiling, 15–17 creating and modifying code, 15 free-form layout, 15 “Hello World” example, 11–14 JVM (Java Virtual Machine), 7–8 running, 15–17 source code, 16 Java Virtual Machine (JVM), 7–8, 1046 java.applet package, 352t, 991 java.applet.Applet class, method summary, 991. See also specific methods java.awt package, 352t, 991–994 java.awt.BorderLayout class, method summary, 991. See also specific methods java.awt.Color class, 67–68, 991. See also specific methods java.awt.Component class, method summary, 992. See also specific methods java.awt.Container class, method summary, 992. See also specific methods java.awt.Dimension class, method summary, 992. See also specific methods java.awt.event package, 994–995 java.awt.event.ActionListener interface, 397, 994. See also specific methods java.awt.event.MouseEvent class, method summary, 995. See also specific methods java.awt.event.MouseListener interface, method summary, 995. See also specific methods java.awt.FlowLayout class, method summary, 992. See also specific methods java.awt.Font class, method summary, 993. See also specific methods java.awt.Frame class, method summary, 993. See also specific methods java.awt.geom package, 995–996 java.awt.geom.Ellipse2D.Double class, method summary, 995. See also specific methods java.awt.geom.Line2D class, method summary, 995. See also specific methods java.awt.geom.Line2D.Double class, 66, 996. See also specific methods

class, method summary, 996. See also specific methods java.awt.geom.Point2D.Double class, method summary, 996. See also specific methods java.awt.geom.RectangularShape class, method summary, 996. See also specific methods java.awt.Graphics class, method summary, 993. See also specific methods java.awt.Graphics2D class, method summary, 993. See also specific methods java.awt.GridLayout class, method summary, 993. See also specific methods java.awt.Rectangle class, method summary, 993. See also specific methods java.awt.Shape interface, 994 JavaBeans components, 956–957 javadoc utility, 92, 1048–1049 java.io package, 352t, 997–999 java.io.EOFException class, 482, 997. See also specific methods java.io.File class, 468–470, 997. See also java.util.Scanner class; specific methods java.io.FileInputStream class, 779, 997. See also specific methods java.io.FileNotFoundException class description, 469 input/output files missing, 469 summary, 997 java.io.FileOutputStream class, 779, 997. See also specific methods java.io.FileReader , 779 java.io.FileWriter , 779 java.io.InputStream class, method summary, 997–998. See also specific methods java.io.InputStreamReader class, method summary, 998. See also specific methods java.io.IOException class checked exceptions, 483 reading Web pages, 472 summary, 998 java.io.ObjectInputStream class, method summary, 998. See also specific methods java.io.ObjectOutputStream class, method summary, 998. See also specific methods java.io.OutputStream class, method summary, 998. See also specific methods java.awt.geom.Point2D

bj4_index.fm Page 1106 Friday, November 6, 2009 5:09 PM

1106 Index class, 17, 998–999. See also specific methods java.io.PrintWriter class automatic object closing, 490 closing output files, 469 method summary, 469, 998–999. See also specific methods writing text files, 468–470 java.io.RandomAccessFile class, 785–786, 999. See also specific methods java.io.Serializable interface, 791, 999 java.lang package, 352t, 1000–1007 java.lang.Boolean class, method summary, 1000. See also specific methods java.lang.Character class method summary, 1000. See also specific methods reading text, line by line, 474 testing characters, 196 java.lang.Class class, method summary, 1000. See also specific methods java.lang.Cloneable interface, 453, 1000 java.lang.CloneNotSupportedException class, 453–454, 1000 java.lang.Comparable interface implementing, 620 method summary, 1001. See also specific methods parameterized type, 621 sorting real data, 619–620 java.lang.Double class, method summary, 1001. See also specific methods java.lang.Error class, 482, 1001 java.lang.IllegalArgumentException class method summary, 1001. See also specific methods throwing exceptions, 481–483 unchecked exceptions, 483 java.lang.IllegalStateException class, 481–482, 1001 java.lang.Integer class converting integers to binary, 131–132 converting strings to integers, 150 maximum values, finding, 128 method summary, 1001–1002. See also specific methods minimum values, finding, 128 java.lang.InterruptedException class checking for thread interruptions, 809 deadlocks, 820 interrupting sleeping threads, 803, 807–808 summary, 1002 java.lang.Math class, 135 E constant, 135 java.io.PrintStream

function summary, 141t method summary, 1002–1004. See also specific methods PI constant, 135 java.lang.NullPointerException class, 483, 1004 java.lang.NumberFormatException class reading numbers, 475 summary, 1004 unchecked exceptions, 483 java.lang.Object class, method summary, 1004–1005. See also specific methods java.lang.Runnable interface, method summary, 1005. See also specific methods java.lang.RuntimeException class, 483, 1005 java.lang.String class, 149, 1005–1006. See also specific methods java.lang.System class libraries, 17 method summary, 1006. See also specific methods out object, 12, 17, 41 java.lang.Thread class, method summary, 1006–1007. See also specific methods java.lang.Throwable class catching exceptions, 487 method summary, 1007. See also specific methods retrieving error messages, 491 java.math package, 130, 1007 java.math.BigDecimal class, 130, 1007. See also specific methods java.math.BigInteger class, 130, 1007. See also specific methods java.net package, 352t, 1008–1009 java.net.HttpURLConnection class, method summary, 1008. See also specific methods java.net.ServerSocket class, method summary, 1008. See also specific methods java.net.Socket class, method summary, 1008. See also specific methods java.net.URL class, method summary, 1009. See also specific methods java.net.URLConnection class, 859, 1009. See also specific methods JavaScript, 455–456 JavaServer Faces (JSF). See JSF (JavaServer Faces) java.sql package, 352t, 1009–1012 java.sql.Connection interface, method summary, 1009–1010. See also specific methods

bj4_index.fm Page 1107 Friday, November 6, 2009 5:09 PM

Index 1107 class, method summary, 1010. See also specific methods java.sql.PreparedStatement interface, 892, 1010. See also specific methods java.sql.ResultSet interface, method summary, 1010–1011. See also specific methods java.sql.ResultSetMetaData interface, method summary, 1011. See also specific methods java.sql.SQLException class, 894–895, 1011 java.sql.Statement class, method summary, 1012. See also specific methods java.swing package, 352t java.text package, 1012 java.text.DateFormat class, method summary, 1012. See also specific methods java.util package, 352t, 1012–1019 java.util.ArrayList class adding array elements, 285–286, 298 array lists, 283–288 examples, 285t–286t removing array elements, 285–286, 297–298 syntax enhancements, 288–289 java.util.ArrayList class, method summary, 1012–1013. See also specific methods java.util.Arrays class, 299, 1013–1014. See also specific methods java.util.Calendar class, method summary, 1014. See also specific methods java.util.Collection interface, 672–673, 1014. See also specific methods java.util.Collections class, method summary, 1014–1015. See also specific methods java.util.Comparator interface, 622, 1015. See also specific methods java.util.concurrent.locks package, 1019 java.sql.DriverManager

java.util.concurrent.locks.Condition

interface, 823–824, 1019. See also specific methods java.util.concurrent.locks.Lock interface, 815–817, 823–824, 1019. See also specific methods java.util.concurrent.locks.ReentrantLock

class, 815–817, 1019. See also specific methods java.util.Date class, 803, 1015. See also specific methods java.util.EventObject class, method summary, 1015. See also specific methods

class, method summary, 1015. See also specific methods java.util.HashMap class, 671, 1015. See also specific methods java.util.HashSet class, 667–668, 1015. See also specific methods java.util.InputMismatchException class, 1015 java.util.Iterable interface, 635–636 java.util.Iterator interface, method summary, 1015–1016. See also specific methods java.util.LinkedHashMap class, 965, 1016. See also specific methods java.util.LinkedList class, method summary, 1016. See also specific methods java.util.List interface, method summary, 1016. See also specific methods java.util.ListIterator interface, 638–646, 1016–1017. See also specific methods java.util.logging package, 1020 java.util.logging.Level class, 1020 java.util.logging.Logger class, 205, 1020. See also specific methods java.util.Map interface, method summary, 1017. See also specific methods java.util.NoSuchElementException class, 475, 485, 1017 java.util.PriorityQueue class, 699, 1017. See also specific methods java.util.Properties class, method summary, 1017. See also specific methods java.util.Random class, 251, 1018. See also specific methods java.util.Scanner class. See also java.io.File class automatic close, 490 creating with a string, 470–471 method summary, 1018. See also specific methods patterns for word boundaries, specifying, 473–474 testing calls to NextDouble method, 196 java.util.Scanner class, reading input character by character, 476–477 from a keyboard, 156 line by line, 474 reading text numbers, 476 regular expressions, 477 text files, 468–470 word by word, 473–474 java.util.Set interface, 667–668, 1018 java.util.GregorianCalendar

bj4_index.fm Page 1108 Friday, November 6, 2009 5:09 PM

1108 Index class, method summary, 1019. See also specific methods java.util.TreeMap class, 671, 1019. See also specific methods java.util.TreeSet class, method summary, 1019. See also specific methods java.util.TreeSet class, 667–668 javax.swing package, 1020–1024 javax.swing.AbstractButton class method summary, 1020. See also specific methods setting radio buttons, 748 testing checkboxes, 749 javax.swing.border package, 1025 javax.swing.border.EtchedBorder class, 749, 1025. See also specific methods javax.swing.border.TitledBorder class, 749, 1025. See also specific methods javax.swing.ButtonGroup class, method summary, 1020. See also specific methods javax.swing.event package, 1025 javax.swing.event.ChangeEvent class, 767, 1025 javax.swing.event.ChangeListener interface, method summary, 1025. See also specific methods javax.swing.ImageIcon class, method summary, 1021. See also specific methods javax.swing.JButton class, 396–399, 1021. See also specific methods javax.swing.JCheckBox class, 749, 1021. See also specific methods javax.swing.JComboBox class, method summary, 1021. See also specific methods javax.swing.JComponent class drawing on components, 60–62 method summary, 1021. See also specific methods timer events, 401–402 javax.swing.JFileChooser class dialog box, example, 471 method summary, 1022. See also specific methods selecting files, 471 javax.swing.JFrame class default closing operation, setting, 59 frame size, setting, 59 frame title, setting, 59 frame visibility, setting, 59 method summary, 1022. See also specific methods java.util.TimeZone

class, 396–399, 1022. See also specific methods javax.swing.JMenu class, method summary, 1022. See also specific methods javax.swing.JMenuBar class, method summary, 1023. See also specific methods javax.swing.JMenuItem class, 758 javax.swing.JMenuItem class, method summary, 1023. See also specific methods javax.swing.JOptionPane class, 160, 1023. See also specific methods javax.swing.JPanel class, 397, 1023 javax.swing.JRadioButton class, 748, 1023. See also specific methods javax.swing.JScrollPane class, 744, 1023. See also specific methods javax.swing.JSlider class, 766, 1024. See also specific methods javax.swing.JTextArea class, 743–746, 1024. See also specific methods javax.swing.JTextField class, 740, 1024. See also specific methods javax.swing.text package, 1025 javax.swing.text.JTextComponent class, method summary, 1025. See also specific methods javax.swing.Timer class, 400–403, 1024. See also specific methods javax.xml.parsers package, 1026 javax.xml.parsers.DocumentBuilder class, method summary, 1026. See also specific methods javax.swing.JLabel

javax.xml.parsers.DocumentBuilderFactory

class, method summary, 1026. See also specific methods javax.xml.xpath package, 1026–1027 javax.xml.xpath.XPath interface, method summary, 1026. See also specific methods javax.xml.xpath.XPathExpressionException

class, 1026 class, method summary, 1027. See also specific methods JButton constructor, javax.swing.JButton class, 1021 JCheckBox constructor, javax.swing.JCheckBox class, 1021 JComboBox constructor, javax.swing.JComboBox class, 1021 JDBC (Java Database Connectivity), 881 JDBC drivers getting, 881 javax.xml.xpath.XPathFactory

bj4_index.fm Page 1109 Friday, November 6, 2009 5:09 PM

Index 1109 testing, 882–885 JFileChooser constructor, javax.swing.JFileChooser

class, 1022 constructor, javax.swing.JLabel class, 1022 JMenu constructor, javax.swing.JMenu class, 1022 JMenuBar constructor, javax.swing.JMenuBar class, 1023 JMenuItem constructor, javax.swing.JMenuItem class, 1023 joins (database tables), 877–879 JRadioButton constructor, javax.swing.JRadioButton class, 1023 JScrollPane constructor, javax.swing.JScrollPane class, 744, 1023 JSF (JavaServer Faces). See also Web applications method expressions, 957–962 navigation between pages, 957–962 TimeZoneBean.java class, 959–961 JSF (JavaServer Faces), architecture deploying JSF applications, 953–954 GlassFish application server, 953 How To example, designing managed beans, 962–963 JavaBeans components, 956–957 JSF container, 951 JSF pages, 950–951 managed beans, 951–952, 962–963 properties, 956–957 separating presentation and business logic, 953 session scope, 952 TimeBean.java class, 952 value expressions, 951–952 JSF (JavaServer Faces), examples business logic tier, 965–972 button groups, 964 checkbox groups, 964 Derby database, 967 presentation tier, 965–972 radio buttons, 964 rows and columns, specifying, 963 storage tier (database), 965–972 three-tier application, 965–972 time zone, 957–962 TimeZoneBean.java class, 969–972 user interface components, 963–965 JSF container, 951 JSF pages, 950–951 JSlider constructor, javax.swing.JSlider class, 1024 JLabel

constructor, javax.swing.JTextArea class, 1024 JTextField constructor, javax.swing.JTextField class, 1024 JUnit framework, 359–360 JVM (Java Virtual Machine), 7–8, 1046 JTextArea

K

K (key in a map), type parameter, 726 Kahn, Bob, 69 key disks, 715 key values, 671 keyboards international characters, 154–155 reading input from, 156 KeyPad.java class, 546–548 keys associating with values. See maps encryption, 780, 784 keySet method, java.util.Map interface, 671, 1017 killing server programs, 850 Knuth, Donald, 914 L

labeling buttons, 396–399 text fields, 740 language support package, 352t largest integer, determining, 141t last in, first out (LIFO), 651 launching programs. See starting programs layout, Java programs, 15 layout manager, GUIs, 746 lazy Boolean evaluation, 200 leaf nodes, binary search trees, 686 left angle bracket (), right shift with sign extension operator, 1056–1057 right angle brackets (>>>), right shift with zero extension operator, 1056–1057 right children nodes, binary search trees, 686 Rivest, Ron, 783 rocket incident, 495–496 ROLLBACK command, 898–899 rollback method, java.sql.Connection interface, 898–899, 1009 rolling back database changes, 898–899 root elements, XML documents, 908 root nodes, binary search trees, 686 roots, 139–140 round method, java.lang.Math class, 141t, 1003 rounding, 140–141, 141t rounding errors binary/decimal conversions, 129 floating-point numbers, 144–145, 177–178

bj4_index.fm Page 1120 Friday, November 6, 2009 5:09 PM

1120 Index rows database, 866–867. See also columns, database; tables, database GUI, 743 Web applications, 963 RPN (reverse Polish notation), 654–655, 697–698 RSA (Rivest Shamir Adelman) encryption, 783–785 Rumbaugh, James, 1058 run method, java.lang.Runnable interface checking for interruptions, 809 method summary, 1005 running threads, 802 terminating threads, 807 tips for using, 806 running programs. See starting programs running threads, 802–807 run-time errors, 19 run-time stacks, 652 RUP (Rational Unified Process), 508, 509 S

S (general type), type parameter, 726 safety, Java language, 10 SavingsAccount.java class, 425 Scanner constructor, java.util.Scanner class, 1018 scenes, drawing, 114–115 schema languages, 938–939 Schneier, Bruce, 783 scope of variables with identical names, 349–350 local variables, 348–349 minimizing, 351 overlapping, 349–350 parameter variables, 348 shadowing, 349–351 syntax summary, 1030 scripting languages interpreted, 455 JavaScript, 455–456 loosely typed, 455 overview, 455–456 scroll bars, 744 searching. See also finding binary, 616–619 BinarySearcher.java class, 617–618 linear, 614–616 LinearSearchDemo.java class, 616 LinearSearcher.java class, 615 sequential, 614–616 security buffer overrun attacks, 282–283 copy protection, 714–715

dongles, 715 Java language, 10 key disks, 715 package access, 356 software piracy, 714–715 viruses, 282–283 worms, 282–283 @see tag, 1048 seek method, java.io.RandomAccessFile class, 786, 999 SELECT command, 874–875 selecting files. See files, selecting from a dialog box selection sorts. See sorting, selection sorts SelectionSortComponennt.java class, 829–830 SelectionSortDemo.java class, 598 SelectionSorter.java class, 597–598, 830–832 SelectionSortTimer.java class, 601 SelectionSortViewer.java class, 828–829 semicolon (;) ending method statements, 12 errors in for loops, 233–234 if statement terminator, 176 omitting, 14 sentinel values, 238–241 separating lines of text, 743 sequential access data structures, 631, 648 definition, 785 linked lists, 631 sequential searches, 614–616 SerialDemo.java class, 791–792 serialization, 791 java.io.Serializable , 999 server programs BankClient.java class, 854 Bank.java class, 853–854 BankServer.java class, 851 BankService.java class, 851–853 description, 848 designing, How To example, 855–856 How To example: Designing, 855–856 How To example: designing client/server programs, 855–856 killing, 850 server sockets, 849 server sockets, 849 ServerSocket constructor, java.net.ServerSocket class, 1008 session scope, JSF, 952 session state, 955 set method java.util.ArrayList class, 285, 1013 java.util.ListIterator interface, 641, 1017

bj4_index.fm Page 1121 Friday, November 6, 2009 5:09 PM

Index 1121 method, org.w3c.dom.Element interface, 923, 1028 setAutoCommit method, java.sql.Connection interface, 898, 1010 setBorder method, javax.swing.JComponent class, 749, 1021 set-breakpoint command, 258 setColor method, java.awt.Graphics class, 993 setDefaultCloseOperation method, javax.swing.JFrame class, 59, 1022 setDouble method, java.sql.PreparedStatement interface, 887, 1010 setEditable method javax.swing.JComboBox class, 750, 1021 javax.swing.JTextArea class, 743, 750 javax.swing.text.JTextComponent class, 743, 1025 setFont method, javax.swing.JComponent class, 1021 setIfModifiedSince method, java.net.URLConnection class, 857, 1009 setIgnoringElementContentWhitespace method, setAttribute

javax.xml.parsers.DocumentBuilderFacto ry class, 935, 1026

method, java.sql.PreparedStatement interface, 887, 1010 setJMenuBar method, javax.swing.JFrame class, 1022 setLayout method, java.awt.Container class, 746, 992 setLevel method, java.util.logging.Logger class, 205, 1020 setLine method, java.awt.geom.Line2D class, 995 setLocation method java.awt.geom.Point2D class, 996 java.awt.Rectangle class, 993 setParameter method, org.w3c.dom.DOMConfiguration interface, 925, 1027 setPreferredSize method, java.awt.Component class, 400, 992 sets. See also data structures adding elements, 668 Comparable interface, 667 contains method, java.util.Collection interface, 668, 685 definition, 666 duplicate elements, 666 “for each” loops, 668 hash tables, 667 hashCode method, 667 HashSet structures, 667–668, 670 hasNext method, 668 setInt

interface references, 670 iterating through elements, 668 Iterator vs. ListIterator, 668 java.util.HashSet class, 667–668 java.util.TreeSet class, 667–668 LinkedList references, 670 List references, 670 listing elements, 668 next method, 668 random access, 668 removing elements, 668 sorted access, 667–668 SpellCheck.java class, 668–669 stepping through the set, 668 testing for elements, 668 trees, 667 TreeSet structures, 667–668, 670 setSelected method, javax.swing.AbstractButton class, 748, 1020 setSelectedItem method, javax.swing.JComboBox class, 751 setSize method java.awt.Component , 59 java.awt.Component class, 992 java.awt.Rectangle class, 50, 993 setString method, java.sql.PreparedStatement interface, 887, 1010 setText method javax.swing.JTextArea class, 743 javax.swing.text.JTextComponent class, 1025 setTimeZone method, java.text.DateFormat class, 959, 1012 setting default text, 743 setTitle method java.awt.Frame class, 59 javax.awt.Frame class, 993 setValidating method, javax.xml.parsers. DocumentBuilderFactory class, 935, 1026 setVisible method java.awt.Component class, 59, 992 Seven Dwarfs, 57–58 shadowing, 349–351, 426 shallow copies, 452. See also clone method Shamir, Adi, 783 shape classes, 106–110 shapes, drawing. See drawing, shapes; graphical applications shell scripts, 308–309 shift operations, 1056–1057 short circuit Boolean evaluation, 200 short data type, 129t, 289

bj4_index.fm Page 1122 Friday, November 6, 2009 5:09 PM

1122 Index showInputDialog method, javax.swing.JOptionPane

class, 160,

1023 showMessageDialog method, javax.swing.JOptionPane

class, 160,

1023 showOpenDialog method, javax.swing.JFileChooser

class, 471,

1022 showSaveDialog method, javax.swing.JFileChooser

class, 471,

1022 side effects, 182, 333–334, 336 signal method, java.util.concurrent.locks.Condition

interface, 820, 1019 signalAll method, java.util.concurrent.locks.Condition

interface failing to call, 822 failure to lock the object, 823 method summary, 1019 temporarily releasing locks, 819–820 simple if statements, 173 SimpleDataSource.java class, 884, 886 simplicity, Extreme Programming, 509 simulation programs Buffon needle experiment, 250–255 casting dice, 251–252 definition, 250 pseudorandom numbers, 252 random number generation, 250–255 sin method, java.lang.Math class, 141t, 1003 sine, in radians, 141t single quotes (’) SQL literals, 867 SQL string delimiters, 867 single quotes (’), XML attribute delimiters, 908 single-step command, 259–260 single-valued database relationships, 870–871 size method java.util.ArrayList class, 283, 1013 java.util.Collection interface, 1014 Skipjack encryption, 783 slash (/), division operator, 138 slash asterisk... (/*...*/) comment delimiters, 14, 1039 line number delimiters, 469 slash asterisks... (/**...*/), comment delimiter, 89, 1039 sleep method, java.lang.Thread class, 803, 1007 sleeping threads, 803, 807–808

sliders, creating, 765–767 small releases, Extreme Programming, 509 smallest integer, determining, 141t Socket constructor, java.net.Socket class, 1008 sockets, Internet, 845–846 software development. See also programming art vs. science, 548–549 engineering discipline, 549 programmer productivity, 510–511 prototypes, 508 user interface prototypes, 508 software development models Extreme Programming, 508–510 RUP (Rational Unified Process), 508, 509 spiral, 508 waterfall, 507–508 software life cycle analysis phase, 506 deployment phase, 507 design phase, 506 implementation phase, 506 phases of, 506–507 requirements documents, 506 testing phase, 507 software piracy, 714–715 sort constructor java.util.Arrays class, 0, 1014 java.util.Collections class, 620, 1015 sorting algorithms, 596 heaps, 709–714 insertion sorts, 604–605 quicksort algorithm, 611–613 set elements, 667–668 sorting, merge sorts algorithm, 609–611 MergeSortDemo.java class, 608–609 MergeSorter.java class, 607–608 overview, 606–609 sorting, selection sorts algorithm performance, 602–604 algorithm profile, 599–602 ArrayUtil.java class, 599 big-Oh notation, 603, 605–606 overview, 596–599 SelectionSortDemo.java class, 598 SelectionSorter.java class, 597–598 SelectionSortTimer.java class, 601 StopWatch.java class, 600–601 source code, Java programs, 16 source files coding guidelines, 1062 packages, 354–355

bj4_index.fm Page 1123 Friday, November 6, 2009 5:09 PM

Index 1123 option, 1049 region, java.awt.BorderLayout class, 746 spaces, in variable identifiers, 37 special characters HTML symbols for, 1044 XML symbols for, 930 SpellCheck.java class, 668–669 spiral model, software development, 508 spreadsheet programs, history of, 357–358 SQL (Structured Query Language) ’ (single quotes), as literals, 867 ’ (single quotes), string delimiters, 867 case sensitivity, 867 definition, 866 SQL types vs. Java types, 867 statements, executing, 887–888 SQL (Structured Query Language), database queries && (ampersands), and logical operator, 876 (angle brackets), inequality operator, 876 = (equal sign), equality operator, 87 (percent sign), SQL wildcard, 876 _ (underscore), SQL wildcard, 876 || (vertical bars), or logical operator, 876 across multiple tables, 877–878 AVG function, 877 calculations, 876–877 columns, selecting, 875–876 combining, 892–893 combining expressions, 876 COMMIT command, 898–899 COUNT function, 876–877 delimiters in, 892 joins, 877–879 LIKE operator, 876 matching patterns, 876 MAX function, 877 MIN function, 877 NOT operator, 876 AND operator, 876 OR operator, 876 ROLLBACK command, 898–899 SELECT command, 874–875 simple queries, 874–875 Statement objects, 887–888 subsets, selecting, 876 SUM function, 877 UPDATE command, 878–879 updating data, 878–879 views (of results), 875 WHERE clause, 876 SQL (Structured Query Language), query results analyzing, 888–893 ExecSQL.java class, 890–891 -sourcepath SOUTH

meta data, 889–891 objects, 887–888, 888–893 SQL (Structured Query Language), tables CREATE TABLE command, 866 creating, 866 DROP TABLE command, 867 escape sequences, 867, 871–872 foreign keys, 869 indexes, 872–873 INSERT INTO command, 867 linking, 867–869 primary keys, 869, 872–873 removing, 867 replicated data, 868–869, 872 rows, inserting, 867 unique identifiers, 869 SQL database access package, 352t sqrt method, java.lang.Math class, 139–140, 141t, 1003 square brackets ([ ]) array indexing, 277 collection class enhancements, 673 square roots, 139–140, 141t, 1003 squelching exceptions, 487 stack faults, recursion, 561 stacks, 651–653 standards for coding. See also coding guidelines, Java ANSI (American National Standards Institute), 650–651 creators of, 650–651 Extreme Programming, 509 IETF (Internet Engineering Task Force), 650 ISO (International Organization for Standardization), 650–651 Java Community Process, 651 Java language, 651 RFC (Request For Comments), 650 W3C (World Wide Web Consortium), 650 start method java.applet.Applet class, 991 java.lang.Thread class, 804–805, 1007 javax.swing.Timer class, 1024 starting programs command line arguments, 472–473 from a graphical user interface, 473 Java programs, 15–17 passing arguments to, 472–473 starting threads, 804–806 state diagrams, 533–534, 1060 stateChanged method, ResultSet

javax.swing.event.ChangeListener

interface, 767, 1025

bj4_index.fm Page 1124 Friday, November 6, 2009 5:09 PM

1124 Index objects, 887–888 statements, 1036–1037. See also specific statements states, ATM case study, 532–533 static inner classes, linked lists, 646–647 static methods calling, 145–146 definition, 145 instance methods, 146 minimizing use of, 344 naming conventions, 146 overview, 342–344 placing in classes, 343 syntax, 146 syntax summary, 1034 static variables. See also variables initialization blocks, 347–348 overview, 345–347 without class prefixes, 347 step-into command, 259–260 step-over command, 259–260 stop method java.applet.Applet class, 991 java.lang.Thread class, 807 javax.swing.Timer class, 1024 stopping threads, 807 StopWatch.java class, 600–601 storage, computer hard disks, 4, 5 primary, 4 removable, 4 secondary, 4 storage tier (database), JSF example, 965–972 streaming parsers, 914–915 streams How To example, 793–794 object streams, 790–792 reading binary data, 778 string literals vs. character literals, 153 strings “...” (double quotation marks), string indicators, 13 + (plus sign), string concatenation, 149–150 backslash, displaying, 153 case, ignoring, 179 char data type, 129t, 153–154 character literals vs. string literals, 153 code units, 153–154 comparing, 179–181 computing hash codes, 681 concatenating, 149–150 converting to integers. See parseInt method Statement

converting to numbers. See parseInt method converting to upper case, 42 in dictionary order, 179 empty, 149 escape sequences, 152–153 indicating, 13 international characters, 153–155 length, determining, 41–42, 149, 288 length of zero, 149 line feed character, 153 literals, creating, 149 newline escape sequence, 153 number of characters, counting, 41–42 objects, creating, 149 quotation marks, displaying, 152–153 search-and-replace, 44–45 String class. See java.lang.String class supplementary characters, 153–154 Unicode encoding, 153–154 strings, substrings error handling, 151 extracting, 150–151 length, determining, 151 Worked Example: extracting initials, 157 Worked Example: extracting the middle, 185 string-to-number conversions, error handling, 150 Stroustrup, Bjarne, 407 Structured Query Language (SQL). See SQL (Structured Query Language) subclasses. See also inheritance; superclasses of abstract classes, 437–438 accidental overloading, 429–430 animation lesson, 429 calling methods, syntax, 428 cloning mutable instance variables, 451–452 confusing with superclasses, 425–426 constructors, 430–432 converting to superclasses, 433–435 definition, 420 failure to invoke superclass method, 430 forcing an override, 437–438 implementing, 423–426 inherited methods, 423 instance variables, 423–424 overriding superclass methods, 427–430 preventing an override, 438 shadowing instance variables, 426 submenus, 758 substring method, java.lang.String class, 150–151, 1006 substrings. See strings, substrings

bj4_index.fm Page 1125 Friday, November 6, 2009 5:09 PM

Index 1125 subtract method java.math.BigDecimal java.math.BigInteger

class, 130, 1007 class, 130, 1007 subtraction, 138. See also decrementing SUM function, 877 summing array elements, 295. See also addition (mathematical) super reserved word, 431 superclasses. See also inheritance; subclasses confusing with subclasses, 425–426 converting to subclasses, 433–435 definition, 420 for the Object class, 444–445 supplementary characters, 153–154 Swing documentation, 764–770 swing user interface package, 352t SwingSet demonstration screen, 765 switch statements, 187–188 symmetric bounds, 235 synchronized methods, 823–824 synchronized reserved word, 823–824 synchronizing object access across multiple CPUs, 824 BankAccount.java class, 821–822 BankAccountThreadRunner.java class, 820 condition objects, 818 deadlocks, 818–824 lock objects, 815–817 locks, built-in, 823–824 locks, definition, 815 locks, temporary release, 818–822 SYSTEM reserved word in XML, 934–935 T

T (general type), type parameter, 726 tab characters, indenting code, 176 Tab key, indenting code, 175 tables, database. See also columns, database; rows, database CREATE TABLE command, 866 creating, 866 description, 866–867 DROP TABLE command, 867 escape sequences, 867, 871–872 foreign keys, 869 indexes, 872–873 INSERT INTO command, 867 linking, 867–869 primary keys, 869, 872–873 removing, 867 replicated data, 868–869, 872 searching across. See joins unique identifiers, 869 tabs, indenting code, 175–176 tabular arrangement, GUI components, 747

tags HTML, 1041–1042 XML, 907, 914 tally counter, example, 82–84 tan method, java.lang.Math class, 141t, 1004 tangents, 141t TaxCalculator.java class, 190–191 TaxReturn.java class, 188–190 TCP (Transmission Control Protocol), 841–842 TCP/IP (Transmission Control Protocol/ Internet Protocol), 69, 841 Telnet program, 843–844 terminating algorithms, 23 terminating threads, 807–809 ternary expression operators, 1030 test cases, preparing, 204 TestDB.java class, 884 tester class, 99–100 testing checkboxes, 749 database installation, 882 radio buttons, 748 for set elements, 668 testing phase, software life cycle, 507 testing programs. See also debuggers; debugging archiving test cases, 308 assertions, 339–340 black-box testing, 202 boundary test cases, 203, 204 calculating sample data, 203 classes, 98–100 classes, interactively, 53–54 code coverage, 202–205 Extreme Programming, 509 hand-tracing, 192–193 input redirection, 308 logging, 204–205 for loop termination, 239 mock objects, 389–390 for null, 182 output redirection, 308 rectangle movement, 52–53 regression testing, 306–308 test cases, preparing, 204 test suites, 306 tracing, 204–205 white-box testing, 202 TEX typesetting program, 914 text default, setting, 743 drawing, 66 editing, disabling, 743 inserting in XML documents, 923

bj4_index.fm Page 1126 Friday, November 6, 2009 5:09 PM

1126 Index text (continued) reading. See reading text separating lines of, 743 writing. See writing text text areas creating, 743–746 for display only, 743 editing, disabling, 743 text fields creating, 740–742 for display only, 743 editing, disabling, 743 Therac-25 incidents, 309–310 thread pools, 806–807 threads accessing a shared object. See race conditions animating algorithms, case study, 824–832 checking for interruptions, 807, 809 conflicting. See race conditions definition, 802 GreetingRunnable.java class, 804 GreetingThreadRunner.java class, 805 interleaving, 805 interrupting, 807–808 putting to sleep, 803 running, 802–807 SelectionSortComponennt.java class, 829–830 SelectionSorter.java class, 830–832 SelectionSortViewer.java class, 828–829 sleeping, interrupting, 807–808 starting, 804–806 stopping, 807 terminating, 807–809 time slices, 805 time stamps, 803 threads, race conditions BankAccount.java class, 814–815 BankAccountThreadRunner.java class, 812–813 causes of, 809–811 definition, 812 DepositRunnable.java class, 813 WithdrawRunnable.java class, 813–814 threads, synchronizing object access. See also race conditions across multiple CPUs, 824 BankAccount.java class, 821–822 BankAccountThreadRunner.java class, 820 condition objects, 818 deadlocks, 818–824 lock objects, 815–817 locks, built-in, 823–824 locks, definition, 815 locks, temporary release, 818–822

synchronizing object access, 815–817 synchronizing threads, 823–824 three-tier application, JSF example, 965–972 throw early, catch late, 487 throw statement, syntax, 483 Throwable constructor, java.lang.Throwable class, 1007 throwing exceptions, 339, 481–483, 491. See also exception handling throws clause, 484–485 @throws tag, 1048 Thrun, Sebastian, 202 TicTacToe.java class, 311–312 TicTacToeRunner.java class, 312 time slices, threads, 805 time stamps, threads, 803 time zones, JSF example, 957–962 TimeBean.java class, 952 timer events, 400–403 Timer constructor, javax.swing.Timer class, 1024 TimeZoneBean.java class, 959–961 JSF example, 969–972 TitledBorder constructor, javax.swing.border.TitledBorder class, 1025 panel border titles, 749 toDegrees method, java.lang.Math class, 141t, 1004 toLowerCase method, java.lang.String class, 1006 toRadians method, java.lang.Math class, 141t, 1004 toString method for all classes, 449 description, 449 java.lang.Integer class, 131–132, 1002 java.lang.Object class, 1005 java.util.Arrays class, 303, 0, 1014 overriding, 445–446 toUpperCase method, java.lang.String class, 1006 TRACE command, 843 trace messages, inserting, 569 tracing loops, animated lesson, 221 programs, 204–205 recursion, 562 while loops, animated lesson, 221 transactions, database. See relational databases, transactions transistors, 4 translate method, java.awt.Rectangle class, 48, 993

bj4_index.fm Page 1127 Friday, November 6, 2009 5:09 PM

Index 1127 Transmission Control Protocol (TCP), 841–842 Transmission Control Protocol/Internet Protocol (TCP/IP), 69, 841 traversing binary search trees, 696–698 tree maps, 671–672 tree sets vs. hash sets, 667–668 tree-based parsers, 914–915 TreeMap constructor, java.util.TreeMap class, 1019 TreeSet constructor, java.util.TreeSet class, 1019 TreeSet structures, 667–668, 670 triangle numbers, recursion, 558–561 Triangle.java class, 248, 560–561 TriangleRunner.java class, 248 TriangleTester.java class, 561 trim method, removing whitespace, 474–475 try blocks, 485–487, 490 try/catch statements, 485–487, 489 Turing, Alan, 576–578 Turing machine, 576–578 two-dimensional arrays, 310–314 two’s complement integers number system, 1051–1052 type parameters, generic & (ampersand), specifying type bounds, 730–731 ? (question mark), wildcard type, 731–732 < > (angle brackets), type variable delimiters, 726 arrays, generic, 733–734 in classes. See generic classes constraining, 730–731 definition, 724 E (element), 726 erasure, 732–734 extends reserved word, 731 identifying, 726 inferring from variable types, 672–673 inheritance, 731 K (key in a map), 726 in methods. See generic methods naming conventions, 724 objects, generic, 733 primitive, modifying, 334–336 primitive types, 724 S, T, U (general types), 726 in a static context, 735 substituting primitive types for, 724 V (value in a map), 726 variables, 726 wildcard types, 731–732 types of data. See data types

typesetting systems, creating XML documents, 912–914 U

U (general type), type parameter, 726 UML (Unified Modeling Language). See also CRC cards association relationships, 517–518 attributes, 516–517 class diagrams, 514–516 dependency relationship symbol, 515t inheritance relationship symbol, 515t interface implementation relationship symbol, 515t interface types, 376 is-a relationships, 376 methods, 516–517 object diagrams vs. class diagrams, 331 relationship symbols, 515 The Unified Modeling Language User Guide, 1058 uses relationships, 376 UML (Unified Modeling Language), aggregation and association, 517–518 relationship multiplicities, 517 relationship symbol, 515t UML diagrams case study, ATM, 534–535 case study, printing an invoice, 521–522 dependency diagrams, 1060 relationship symbols, 1059 state diagrams, 1060 summary of, 1058–1060 unambiguous algorithms, 23 unary expression operators, 1030 unbalanced binary search trees, 692 unchecked exceptions, 483–485 undeclared methods, calling, 42 underscore (_) SQL query wildcard, 876 in variable identifiers, 37 in XML attribute values, 933 Unicode encoding, 153–154, 979t–981t The Unified Modeling Language User Guide, 508, 1058 uninitialized variables, 39 union method, java.awt.Rectangle class, 993 unique identifiers, database tables, 869 unit testing definition, 98 frameworks, 359–360 JUnit framework, 359–360 tester class, 99–100 Univac, 57–58

bj4_index.fm Page 1128 Friday, November 6, 2009 5:09 PM

1128 Index unlock method, java.util.concurrent.locks.Lock

interface, 816–817, 1019 unstable layout, coding guidelines, 1067 UPDATE command, 878–879 updating databases, 878–879 URL (Uniform Resource Locator), 842–845 URL connections, 856–859 URL constructor, java.net.URL class, 1009 URLConnection constructor, java.net.URLConnection class, 1009 URLGet.java class, 858–859 useDelimiter method, java.util.Scanner class, 1018 patterns for word boundaries, specifying, 473–474 reading text, character by character, 476–477 reading text, word by word, 473–474 regular expressions, 477 user interface. See also GUIs (graphical user interfaces) components, JSF example, 963–965 development of, 359 prototypes, 508 uses relationships, 376, 514 utilities package, 352t utility classes, 329 V

V (value in a map), 726 vacuum tubes, history of computers, 6–7 validating XML documents, 929–938 value expressions, 951–952 values, associating with keys. See maps variable declarations vs. assignment statements, 40–41 variables animated lesson, 100 case sensitivity, 1030 changing value of, 39–40 coding guidelines, 1063–1064 declaration syntax, 37 declaring in for loops, 234–235 definition, 8, 36 descriptive names, 38 distinguishing from constants, 133 garbage collector, 101 identifiers, naming conventions, 37–38 initialization, 39–40, 101 instance. See instance variables life span, 101 local, 100–101, 1029 naming conventions, 36–38, 1030 parameter. See parameter variables

scope, 1030 static. See static variables syntax summary, 1029–1030 type, specifying, 36–37 uninitialized, 39 variable declarations vs. assignment statements, 40–41 verbs, in the class task description, 512 @version tag, 1048 versions of Java, summary of, 10t vertical bar (|), binary or, 1055–1056 vertical bars (||), or logical operator confusing with &&, 199 definition, 196 negating, 200 SQL database queries, 876 in SQL queries, 876 views of database query results, 875 virtual memory, operating system services, 389 viruses, computer, 282–283 VisiCalc, 357–358 void reserved word, 45 voting machines, 104–106 W

W3C (World Wide Web Consortium), 650 wait method, java.lang.Object class, 823–824, 1005 waterfall model, software development, 507–508 Web applications AJAX (Asynchronous JavaScript and XML), 973–974 architecture, 948–950. See also JSF (JavaServer Faces) cookies, 955 definition, 948 session state, 955 Web browsers, 70 Web pages, reading from, 472 WebGet.java class, 847–848 WEST region, java.awt.BorderLayout class, 746 what you see is what you get (WYSIWYG), 913 WHERE clause, 876 while loops. See also loops code sample, 220–221 description, 218–219 examples, 222 flow chart, 221 syntax, 223 tracing, animated lesson, 221 while statement, syntax, 223

bj4_index.fm Page 1129 Friday, November 6, 2009 5:09 PM

Index 1129 white space coding guidelines, 1066–1067 consuming, 473–474 HTML, 1042 improving code readability, 144 reading input, 156 white space, XML documents creating, 925 ignoring, 935 white-box testing, 202 whole numbers. See integers wildcard types, 731–732 Wilkes, Maurice, 262 windows, operating system services, 389 WithdrawRunnable.java class, 813–814 word processors, creating XML documents, 912–914 words, reading, 473–474 working with big numbers, java.math.BigDecimal class, 130 WorkOrder.java class, 708 world population table, 313 World Wide Web, history of computers, 70 World Wide Web Consortium (W3C), 650 worms, computer, 282–283 wrapper classes, 289–290 write method, java.io.OutputStream class, 780, 998 writeChar method, java.io.RandomAccessFile class, 999 writeChars method, java.io.RandomAccessFile class, 999 writeDouble method, java.io.RandomAccessFile class, 786, 999 writeInt method, java.io.RandomAccessFile class, 786, 999 writeObject method, java.io.ObjectOutputStream class, 790–791, 998 writeToString method, org.w3c.dom.ls.LSSerializer interface, 1028 writing binary data CaesarCipher.java class, 781 CaesarEncryptor.java class, 782 example, 780–782 writing objects to disk object streams, 790–792 sample program, 791–792 SerialDemo.java class, 791–792 serialization, 791 writing text. See also reading text; writing binary data

/* */ (line number delimiters), 469 closing the print stream, 469 to dialog boxes, 159–160 to files, 468–470, 478–480 line numbers, 469 output redirection, 308 writing XML documents to a file, 925–927 WYSIWYG (what you see is what you get), 913

X

XHTML (Extensible Hypertext Markup Language), 939 XML (Extensible Markup Language) “ (double quotes), XML attribute delimiters, 907 advantages of, 906–907 case sensitivity, 907 data meaning vs. data presentation, 907 formatting Web pages. See XHTML (Extensible Hypertext Markup Language) vs. HTML, 907 namespaces, 939 resilience to change, 906 tag pairs, 907 XML Document Object Model package, 352t XML documents. See also DTD (document type definition) “ (double quotes), XML attribute delimiters, 908 ‘ (single quotes), XML attribute delimiters, 908 attributes, 908 child elements, 908, 912 definition, 908 editing, 913 element content, 908 elements, 908 elements vs. attributes, 911–912 exchanging between computers, 914 format, designing, 909–911 markup tags, 914 mixed content, 908 printing, 925–927 root elements, 908 starting declaration, 908 structure of, 908–909 text elements, 908 validating, 929–938. See also DTD (document type definition) white space, creating, 925 white space, ignoring, 935 XML documents, creating attributes, setting, 923

bj4_index.fm Page 1130 Friday, November 6, 2009 5:09 PM

1130 Index XML documents, creating (continued) elements, creating, 923 How To example, 928–929 inserting text, 923 ItemListBuilder.java class, 925–927 methods for, 923–927 in typesetting systems, 912–914 in word processors, 912–914 writing to a file, 925–927 XML documents, parsing child names, determining, 916 converting to Java classes, 920–921 counting matches, 917 ItemListParser.java class, 917–919 match names, 917 matching an element, 917

matching attributes, 917 parse trees, 920–923 parsers, definition, 914 selecting values from a set, 917 separating elements, 917 streaming parsers, 914–915 tree-based parsers, 914–915 XPath syntax, 915–917 XML Schema specification, 938–939 XPath syntax, 915–917 Z

Zimmermann, Phil, 784 ZIP utility. See JAR (Java Archive) tool

bj4_credits.fm Page 1131 Friday, November 6, 2009 3:40 PM

ILLUSTRATION CREDITS

Chapter 1

Page 3: Copyright © 2007, Intel Corporation. Page 4: PhotoDisc, Inc./Getty Images. Page 5 (top): PhotoDisc, Inc./Getty Images. Page 5 (bottom): Copyright © 2007, Intel Corporation. Page 7: Courtesy of Sperry Univac, Division of Sperry Corporation. Page 25: Robert Ban/iStockphoto.

Chapter 2

Page 54 (top): Constance Bannister Corp/Hulton Archive/Getty Images, Inc. Page 54 (bottom): Cay Horstmann. Page 57: Corbis Digital Stock.

Chapter 3

Page 82: Jasmin Awad/iStockphoto. Page 98: Mark Evans/iStockphoto. Page 105 (top): David Young-Wolff/PhotoEdit. Page 105 (bottom): Lisa F. Young/iStockphoto. Page 110: Punchstock. Page 114 (top): Copyright © 2001-2009 Lev Givon. All rights reserved. Page 114 (bottom): Keith Kapple/SUPERSTOCK. Page 115: Daniel Biggs/SUPERSTOCK.

Chapter 4

Page 132: Larry Hoyle, Institute for Policy & Social Research, University of Kansas. Page 149: Holger Mette/iStockphoto. Page 155: Henrik Aija/iStockphoto. Page 157: Rich Legg/iStockphoto.

Chapter 5

Page 195: Sidney Harris/ScienceCartoonsPlus.com. Page 201: Vaughn Youtz/Zuma Press.

Chapter 6

Page 244: iStockphoto. Page 250: Cay Horstmann. Page 261: Mark Poprocki/iStockphoto. Page 262: Naval Surface Weapons Center, Dahlgren, VA.

Chapter 7

Page 306: Kiyoshi Takahase/iStockphoto. Ryan Ruffatti/iStockphoto.

Chapter 8

Page 358: Visicalc screen capture, Copyright © IBM Corporation. Used with permission.

Chapter 9

Page 375: gregory horler/iStockphoto. Page 381: iStockphoto. Page 388: Courtesy of Satoru Satoh. Page 407: Courtesy of Sun Microsystems, Inc.

Chapter 10

Page 421: Tony Tremblay/iStockphoto (vehicle); Peter Dean/iStockphoto (motorcycle); nicholas belton/iStockphoto (car); Robert Pernell/iStockphoto (truck); Clay Blackburn/ iStockphoto (sedan); iStockphoto (SUV). Page 444: Sean Locke/iStockphoto.

Chapter 11

Page 480: age fotostock/SUPERSTOCK. Page 496: AP/Wide World Photos.

1131

bj4_credits.fm Page 1132 Friday, November 6, 2009 3:40 PM

1132 Illustration Credits Chapter 12

Page 509: Booch/Jacobson/Rumbaugh, The Unified Modeling Language Reference Manual, pg. 41, © 1999 by Addison Wesley Longman, Inc. Reproduced by permission of Pearson Education, Inc.

Chapter 13

Page 577: Science Photo Library/Photo Researchers, Inc.

Chapter 14

Page 614: Topham/The Image Works.

Chapter 15

Page 652: Photodisc/Punchstock. Page 654: Courtesy Nigel Tout.

Chapter 19

Page 784: Anna Khomulo/iStockphoto.

Chapter 20

Page 817: Creatas/Punchstock. Page 833: Courtesy of Professor Naehyuck Chang, Computer Systems Lab, Department of Computer Engineering, Seoul National University.

Chapter 22

Page 880: Greg Nicholas/iStockphoto.

Chapter 24

Page 973: Google EarthTM mapping service screenshot © Google, Inc., reprinted with permission.

Animation Icon

james steidl/iStockphoto.