Answers to Test Your Understanding Exercises Chapter 1 1. In Example 1 the output is value=8, the value set in the catch block when an exception occurs. Example 2 also prints the stack trace to show explicitly the error that has occurred. 3. b 5. The program aborts with the exception java.io.NotSerializableException: Person 7. The changed part is: for (int i=0; i<10; i++) raf.writeDouble(i); raf.seek(40); double number = raf.readDouble(); System.out.println ("The number starting at byte 40 is " + number); raf.seek(8); number = raf.readDouble(); System.out.println ("The number starting at byte 8 is " + number); 9. import java.awt.*; import java.awt.event.*; import java.applet.Applet; public class Separate extends Applet { private Button print = new Button("Print"); private Button clear = new Button("Clear"); private Label message = new Label("Message goes here"); private PrintAdapter printAdapter = new PrintAdapter(message); private ClearAdapter clearAdapter = new ClearAdapter(message); public void init() { add(message); add(print); add(clear); print.addActionListener(printAdapter); clear.addActionListener(clearAdapter); } } class PrintAdapter implements ActionListener { private Label message; public PrintAdapter(Label l) { message = l; } public void actionPerformed(ActionEvent event) { message.setText(event.getActionCommand()); } } class ClearAdapter implements ActionListener { private Label message; public ClearAdapter(Label l) { message = l; } public void actionPerformed(ActionEvent event) { message.setText(""); } } 11. main 1, Bonnie 1, Clyde 1, main 2, main 3, main 4, Clyde 2, main 5, Bonnie 2, Clyde 3, Bonnie 3, Clyde 4, Clyde 5, Bonnie 4, Bonnie 5 13. For example, with java PutGet 100 500, the buffer becomes full six times, while with java PutGet 500 100, the buffer becomes empty nine times. 15. The result is the same. The overall row weight is the maximum of the weights for each component in that row, so giving b1 a weighty of 1.0 and b2 a weighty of 0.0 is the same as the original in which these weights were reversed. 17. Because gridx remains equal to 1, the remaining buttons appear in the same column, below b4. Since b6 has a weightx of 1.0 and the other buttons have a weightx of 0.0, the second column, containing b6, gets all the extra space. 19. Vector v = new Vector(25,7); Chapter 2 1. Using the applet viewer shows a blank screen because the applet viewer does not display HTML documents but only runs applets embedded in those documents. 3. The program displays the HTML file, index.html, with all the HTML tags. 5. The changes are: URLConnection c = url.openConnection(); input = new BufferedReader (new InputStreamReader(c.getInputStream())); 7. The change is: System.out.println("Content type: " + c.getHeaderField("Content-type")); 9. The output includes part of the request headers, which should be informational only to the client. 11. The client receives a message that it is connected, but no data because only headers were requested. We could use this to inspect the headers if we modified the program. 13. Clients will be active simultaneously, and will alternately receive data. 15. The port 3000 overrides the default port of 1099. Chapter 3 1. The ID is unique, but the name may be duplicated. 3. INSERT INTO Salesperson VALUES ('12', 'Peter Patterson', '66 FifthSt.') INSERT INTO Salesperson VALUES ('98','Donna Dubarian', '77 Sixth St.') 5. DELETE FROM OrderItem WHERE OrderNumber = '5' AND ItemNumber = '444444' 7. SELECT OrderNumber FROM Orders, Salesperson WHERE Orders.SalesPersonID = Salesperson.SalesPersonID AND SalespersonName = 'Peter Patterson' 9. Changes are: Class.forName(args[0]); (instead of new JdbcOdbcDriver()) Connection con = DriverManger.getConnection (args[1], user, password); 11. SELECT DISTINCT SalespersonName, CustomerName FROM Salesperson, Customer, Orders WHERE Orders.CustomerID = Customer.CustomerID AND Orders.SalesPersonID = Salesperson.SalesPersonID 13. Change rs.getString("CustomerName") to rs.getString(1) in two places and change rs.getString("OrderNumber") to rs.getString(1) 15. SELECT DISTINCT CustomerName, CustomerAddress FROM Customer, Salesperson, Orders WHERE Customer.CustomerID = Orders.CustomerID AND Salesperson.SalesPersonID = Orders.SalesPersonID AND SalespersonName = 'Peter Patterson' 17. Use dbMetaData.getTables(null, null, "Order%", tables); 19. Add displayStrings ("Type Info Column Names and Types", colNamesTypes(rs)); after getTypeInfo(). 21. java.sql.SQLException: [Microsoft][ODBC Microsoft Access 97 Driver]Invalid cursor state 25. After pressing the Display button, the new labels are truncated to have the same size as the generic table labels they are to replace. 27. The fieldValue text field remains 12 character wide, centered in its two-column field, rather than expanding to fill the two columns. Chapter 4 1. Using JRun, Welcome.class belongs in the JRUN_HOME\servlets directory. The URL is http://localhost:8000/servlet/Welcome. JRun must be started first. 3. Use Welcome.java for an entertaining example. Using JRun, put the Welcome.java in JRUN_HOME\jsm-default\services\jws\htdocs. Enter the URL http://localhost:8000/Welcome.java. Be sure to start JRun. 5. Change the action to http://localhost:8000/servlet/PostOrGetOrder. 7. Every time we press the refresh button or use another copy of the browser to connect, the display increases the connection count. 9. The browser cannot display the page. 11. The servlet still functions properly because it has a doGet method to respond to GET requests. 13. The order will be updated and the same session ID will be listed for this session. 15. With GET the client appends the data to the URL http://localhost:8080/getOrder.jsp?Order=ice+cream while with POST it is sent separately. 17. We call bean methods inside a <% %> tag. There may be other bean methods besides those that retrieve property values. Chapter 5 1. There is no difference between the commented and the uncommented version. 3. Use the command java GrowthFrameSwing 2. 5. Using MatteBorder(brightGreen) makes the border have the thickness needed to draw the icon around the border. The message appears over the icons. Using MatteBorder(5,5,5,5,brightGreen) causes only a portion of the icon to be drawn. 7. We can select multiple colors from the list. The selected color with the lowest index becomes the drawing color. 9. We can select both the square and the circle, or neither. The last shape selected or deselected is drawn. 11. The dialog gives the choices Yes or No, which are not appropriate answers for the question, How are your studies progressing? 13. Change the setSelecteIndex statement to tabPane.setSelectedIndex(1); 15. Add another entry, such as {"326", "Operating Systems"}, to the courses array. Chapter 6 1. The change to the outcode method would not be a good idea, because it would limit a point to being in one position only, whereas a point might be both below and to the left. The current outcode method returns a flag that encodes this information. 3. The ellipses which replace the rectangles combine in similar patterns to those shown in Figure 3. The combining operations apply to any Area. 5. The shear will transform the original rectangle to {(45,60), (145,110), (170,160), (70,110)} and the translation will transform it to {(165,60), (265,110), (190,110), (290,160)}. 7. Changing the fifth argument in the BasicStroke constructor for buBeDa to new float[] {10,5,5,5} will create a dashed rectangle with dashes alternating in size between 5 and 10 with a space of 5 between them. 9. The lower CAT only shows when it intersects the ellipse. 11. No 13. No. Java throws an exception, Exception in thread "main" java.lang.IllegalArgumentException: Zero length string passed to TextLayout constructor. Chapter 7 1. The Unicode representation for ñ is 241. Because Cp1252 is the same, the value 241 is output. Displaying in Notepad shows señor, because Notepad uses the Cp1252 encoding. Display in DOS shows se±or, because DOS uses the Cp437 encoding in which 241 is ±. 3. The Unicode representation for ñ is 241. Because the output encoding is Cp437, Java ouputs the value 164, which is the Cp437 code for ñ. Displaying in DOS shows señor, but displaying in Notepad shows se¤or, since ¤ has the code 164 in Cp1252. 5. Using java Numbers fr FR >out, the output from Example 3 for the Swiss French locale is 12'345.679 SFr. 12'345.68 1'234'567.90% and, using java DateTime fr FR >out, the output from Example 4 for the Swiss French locale is mardi, 4. juillet 2000 14.10. h GMT-07:00 4. juillet 2000 14:10:05 GMT-07:00 4 juil. 00 14:10:05 04.07.00 14:10 7. The default Spanish collator distinguishes upper-case from lower-case and accented characters from corresponding unaccented letter, but does not distinguish control characters. Its strength is TERTIARY. 9. The NumberFormat currency instance, nf, formats currency according to the locale. 11. Change the getBundle call to bundle = ResourceBundle.getBundle(resources); Include a third parameter, String resources, in the GrowthProperty constructor. Change main to: public static void main(String [] args) { String language = "en"; String country = "US"; String resources = "Labels"; if (args.length == 3) { language = args[0]; country = args[1]; resources = args[2]; } GrowthProperty f = new GrowthProperty(language, country, resources); f.setSize(300,200); f.show(); } Chapter 8 1. The screen will flicker and unless you remove the override to update, it will also show extra pieces of the image.. 3. The image is not erased between frames, so when the image is shrinking the screen still shows the extra pieces from the larger image. 5. If we stop the applet, the whistle continues to play until we terminate the applet. 7. The frame pops up but does not display the media file. 9. The cube fills the entire window so it does not look like an object in space. 11. (0,0,.8f) 13. Increasing the shininess reduces the highlights. 15. The objects spin faster as the second Alpha argument decreases. Chapter 9 1. Click on the background entry in the Properties window and choose orange in the color editor that pops up. 3. Bind using the Bind Properties item of the Edit menu. Higher prices make the juggler go slower. 5. The change is vetoed. 7. Bind using the Bind Properties item of the Edit menu. 9. The BeanBox cannot load Smiley.jar if Smiley does not implement Serializable. 11. Use the Events, nosePress item in the Edit menu to hookup one Friendly to the startJuggling method of the Juggler, and another to the stopJuggling method. 13. The instantiate method allows us to load a .ser file for a serialized bean whose state we changed by configuring in a tool such as the BeanBox. Using new loads only the original version of the bean. 15. The Juggler does not appear in the applet. Chapter 10 1. We extend the EJBObject interface. 3. HelloClient.java is the client application's source file. HelloClient.jar contains the system-generated files needed for the client to communicate with enterprise beans on the server. 5. WHERE "due" >= ?1 AND "due" <= ?2 7. ejbRemove, ejbActivate, ejbPassivate, and setSessionContext. 9. Most importantly, Hello is stateless and Agent is stateful. The Agent bean communicates with the Customer entity bean to satisfy client requests. 11. No. Chapter 11 1. The conditions on implementations of Set methods may be more stringent. The add method must check for duplicates in a Set but not generally in a Collection. 3. Not directly, because the element type is Object. Primitive types need to be wrapped in wrapper classes such as Integer. 5. The punctuation is included, giving words like "detract.," and "us--that". 7. The List methods specify the position at which to insert or update. The ListIterator does not need this argument because it always inserts or updates at the current position of the iteration. 9. Change the argument in the line linkImp.get(5000); to get the time for 10,000 gets. The actual time will vary depending on the system used. Relatively, the time taken increases as the element index increases. 11. The time decreases. 13. It is much easier to find a range of words near the word for which one is searching to provide possible correct spellings. 15. Java throws a ClassCastException because the String cannot be cast to a NewOrderedName. The compareTo method for NewOrderedName checks first name, last name, and middle initial and does not work with strings. We could add a constructor to create a NewOrderedName from a String. 17. The algorithms that require the data to be ordered specify a List parameter. Chapter 12 1. When using the command java -Dfile.encoding=ISO8859 ShowProperties the output shows file.encoding=ISO8859 3. In IE5, cannot access file out (to read from out) cannot access "java.sun.com":80 (to connect) 5. grant codebase "file:/c:/test/" { permission java.io.FilePermission "c:\\test\\results", "write"; }; 7. The policy file is grant { permission java.security.AllPermission; }; Running Example 2 with this policy file gives the output OK to read from file 'out' OK to connect to java.sun.com OK to write to file 'out' Can access java.version Can access file.encoding 9. iload_3 bipush 17 iadd istore 4 11. dload_2 // load variable 2 dconst_1 // load 1.0 dcmpl // compare (puts -1 or 0 on stack if variable 2 is <= 1.0) ifle 00 06 // jump six bytes ahead to do the assignment goto 00 05 // jump five bytes ahead to skip the assignment iconst_2 // load 2 istore_3 // store in variable 3 13. 42 183 0 6 177 16 25 60 16 12 61 27 16 15 96 61 178 0 7 18 1 182 0 8 178 0 7 28 182 0 9 177 15. 182 0 9 refers to entry 9 Fieldref 10 class 3 name_and_type 13 Class entry 3 is Class 7 entry 25 Entry 25 is java/io/PrintStream Name_and_type entry 13 is name 32 type 15 Entry 32 is println Entry 15 is (I)V so this instruction invokes the println method of the PrintStream class and the method takes one integer argument and returns void.