Head First Java, 2nd Edition by Kathy Sierra, Bert Bates The unconfirmed error reports are from readers. They have not yet been approved or disproved by the author or editor and represent solely the opinion of the reader. Here's a key to the markup: [page-number]: serious technical mistake {page-number}: minor technical mistake : important language/formatting problem (page-number): language change or minor formatting problem ?page-number?: reader question or request for clarification This page was updated Febraury 21, 2008. UNCONFIRMED errors and comments from readers: ?3? graphic with source (#1); This code, once compiled, does not run. I get the error "Exception in thread "main" java.lang.NoSuchMethodError: main". I am running jdk.1.6.0_02-b06 on Windows XP and all my environmental variables have been set. Should I be able to run this code (see what I typed in below)? ============================================= import java.awt.*; import java.awt.event.*; class Party { public void buildInvite() { Frame f = new Frame(); Label l = new Label("Party at Tim's"); Button b = new Button("You bet"); Button c = new Button("Shoot me"); Panel p = new Panel(); p.add(l); } } =============================================== (23) middle of page in class Test code; Wrong way double-quotes in System.out.print(x + "" + y + " "); {41} Third bullet point; There is the common misconception of a blueprint once again. Most believe that "blueprint" stands for the original when it is actually the opposite. Original drawings where made on semi-transparent film (frosted film). When making copies to paper you use light-sensitive paper the same size as the original. You place the original on top of the paper and insert into a giant exposure machine. The result is a paper drawing with blue lines and blueish background. So you see the blueprint is actually the instance object and not the class. {47} First Column, "Pool Puzzle" Solution, esp. lines 11 and 14; The error is one of omission: While the solution is **a** possible solution to the puzzle, there are others. Lines 11 and 14 as printed read if ( x == 3 ) { and if ( x < 0 ) { Other solutions include (A) if ( x > 0 ) { and if ( x > 1 ) { (B) if ( x == 4 ) { and if ( x < 5 ) { However, only (A) also solves the bonus question. {63} Compiler problem B; The problem in the exercise is to find the code which will give compilation errors by the compiler. However the problem B is fine for the compilation. The error mentioned in the exercise solution, i.e the ArrayIndexOutOfBoundsException is a runtime exception, which will never be caught by the compiler. (66) Tip; In the 'Tip', the sentence that starts "Unless you're way smarter than us... it mentions diagrams "like the ones on page 55 and 56 of this chapter". remove "and 56"; it doesn't have any diagrams on it. [and a minor note that I'm sure will be chuckled at.... the first sentence should be "Unless you're way smarter than we are", not "us". {91} Code of Puzzle4 of the Pool Puzzle Exercise; The statement x=6; is superfluous. After the while loop, x is already 6. {106} output box in lower right corner; The output of running "java SimpleDotComTestDrive" should read: hit passed instead of just "hit" (114) 1st paragraph, last sentence.; "you can just skim these last few pages..." should be changed to: "you can just skim these next few pages..." [115] Pre and Post Increment/Decrement Operator box; "int x = 0; int z = ++x; produces x is 1, z is 1" should be: "int x = 0; int z = ++x; produces x is 0, z is 1" Very similar mistake below that one as well. [149] checkUserGuess method; The method includes the following for loop for (DotCom dotComToTest : dotComsList) { result = dotComToTest.checkYourself(userGuess); if (result.equals("hit")) { break; } if (result.equals("kill")) { dotComsList.remove(dotComToTest); } } When the program is run under JRE 1.5.0_04, the loop throws a ConcurrentModificationException after the "dotComsList.remove(dotComToTest);" statement is executed. According to what I've been able to find, when using an ArrayList iterator (as the for-each loop does), it is only legal to modify the ArrayList by using the iterator's own remove or add methods (From the JavaDoc for ConcurrentModificationException: "if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception.") In order to avoid the exception the example code should use a standard for loop. {152} Third line of the placeDotCom method, slightly below the middle of the page.; The line reads: String [] alphacoords = new String [comSize]; // holds 'f6' type coords The local string array "alphacoords" appears nowhere else in the placeDotCom method. I suspect the comment regarding 'f6' coords belongs with the preceding line: ArrayList alphaCells = new ArrayList(); {153} Lines three through eight of the GameHelper code on the page.; These six lines that test for a valid cell position: if (location >= gridSize) { // out of bounds - 'bottom' success = false; // failure }if (x>0 && (location % gridLength==0)) { //out of bounds - right edge success = false; // failure } are unnecessarily restrictive and therefore inefficient. Cells are often falsely rejected. In order to not restructure the code any more than absolutely necessary these six lines can be replaced by the following - admittedly complex - line. // Disallow running off edge: success = !((x < 3) && ((location >= gridSize) || ((incr == 1) && (location % gridLength == 0)))); [212] Inside command window depiction 2/3 of way down the page; Dog sameDog = takeObjects(aDog); should be: Dog sameDog = getObject(aDog); (229) 2nd paragraph of 'A'nswer on right side of page; "... the compiler knows that its (should be 'it's') safe to cast anything that comes out of ArrayList do (should be 'to') a dog reference." (231) Near the bottom of the page; Very minor printing error? For #4, there is a break in the arrow between the "Baz" and the "Bar" classes. This line should be solid. {249} Answer to first "dumb question"; The answer to the first question is missing "protected" which is a perfectly valid access modifier for a constructor. (this should also reference appendix B). {250} 2nd paragraph; the sentence 'there is no other way to create an object other than someone, somewhere saying new on the class type' is not correct - objects can also be created by deserialization and cloning. Josh Bloch calls these 'pseudo-constructors' in 'Effective Java'. (254) The very last text line; "*There's an exception to this rule; you'll learn it on page 252" should read: "*There's an exception to this rule; you'll learn it on page 256" [266] Execise method "public static void doStuff2"; The line "GC localGC" is incomplete. This will certainly have a compilation error. (269) Last but one paragraph, just after the code; '...and a small smile creeped across his lips.' should be '...and a small smile crept across his lips.' {306} Key Calendar Methods graphic; roll(int field, boolean up) -- It might be clearer to use the other overloaded version of this method, namely: roll(int field, int amount) That's the one that was used on the previous page, i.e., "c.roll (c.DATE, 35);". [320] snapshot of MidiSystem class of the API docs; It would be nicer if we can have the snapshot of API for Java 2 Platform SE 5.0, instead of having Java 2 Platform SE v1.4.0) from the first edition. {323} Bottom of page (next to last line); Close parenthesis missing for the "catch block". this code fragment should read: public void crossFingers() { try { anObject.takeRisk(); } catch (BadException ex) { System.out.println("Aaargh!"); } } Note the addition of the next-to-last close parenthesis... [354, 368] section of Making a GUI is easy and the EVENTS section of the Bullet Points page; Java 5 has changed a way to add a component to a JFrame. And that could change the code you have written for chapter 12 to chapter 15. Java 1.4.x and earlier versions require that we have to add components to the frame's content pane. But Java 5 doesn't require that. So instead of writing: frame.getContentPane().add(aJButton); frame.getContentPane().add(aJPanel); ... we could implicitly add a component to a frame without getting the content pane of the frame: frame.add(aJButton); frame.add(aJPanel); etc. And if we're concerned about the compatibility issue, then it is safe to continue using frame.getContentPane.add(...); (362) Bottom of page "Sharpen your pencil" box, 2nd sentence; Match the widgets with the events they might cause. should be changed to: Match the widgets with the event methods they might invoke. or: Match the widgets with the event listener callbacks they might invoke. {368} 5th paragraph in righthand column; graphics.setColor(Color.blue); should be: g.setColor(Color.blue); (370) Sharpen your pencil; Refers to pictures on p351, should be p369. [371] Entire; This code does not work on my system (Dual g5 Macosx10.4.3 with java5) It compiles (begrudgingly: "failed to name mach port") and presents a window with circle and button, but when I click on the button, it freezes and the console gives a host of error that sum up to a NullPointerException at the line frame.repaint(); (371) The bottom source code; The comment in the paintComponent method of the MyDrawPanel refered to the wrong page. //See page 347 for the code should read: //See page 367 for the code (387) Right hand side bottom section; Third bullet point is incorrectly labeled as bullet point 4. (389) Bottom of page; Indentation of "makeEvent" method should match indentation of same method at the end of the previous page (page 388). {391} MyDrawPanel line 18; g.fillRect is called with height and width reversed - should be: g.fillRect(x, y, width, ht); {392} End of try block in go(); Call to sequencer.setTempoInBPM(120) should probably be done before sequencer.start(). (398) Pool Puzzle; This is the answer for a pool puzzle, but the pool puzzle seems to be missing. (417) Constructor; list = new JList(listEntries); should be: JList list = new JList(listEntries); to remain consistent with the preceding pages (420) Middle of page, inside "main()" method; new BeatBox2().buildGUI(); should be: new BeatBox().buildGUI(); {420} 1st line in buildGui, 6th paragraph from the bottom of the page; reads: theFrame = new JFrame("Cyber Beatbox"); Compiler rejects this. It works as: JFrame theFrame = new JFrame("Cyber Beatbox"); [421] 2nd paragraph; When the program is run the labels don't line up with the checkboxes, and since the program is using swing change the Label to JLabel. Box nameBox = new Box(BoxLayout.Y_AXIS); for (int i = 0; i < 16; i++) { nameBox.add(new Label(instrumentNames[i])); } To make everything line-up you can change your code to this GridLayout grid2 = new GridLayout(16,1); grid2.setVgap(1); grid2.setHgap(2); JPanel mainPanel2 = new JPanel(grid2); for (int i = 0; i < 16; i++) { mainPanel2.add(new JLabel(instrumentNames[i])); }// end loop background.add(BorderLayout.EAST, buttonBox); background.add(BorderLayout.WEST, mainPanel2); {421} BeatBox all versions at least through Ch 14; On my system: Windows Vista, Java 1.6.03, Java SE RE 1.6.03-b05, these programs do not release the CMD prompt on close. I fixed it by adding: abstract class MyExitListener implements WindowListener { public void windowClosing(WindowEvent e) { sequencer.stop(); } } as an inner class. Maybe there's a better way? {422} a little more than 1/3 of the way down; JCheckBox jc = (JCheckBox) checkboxList.get(j + 16*i); may be changed to: JCheckBox jc = checkboxList.get(j + 16*i); The "(JCheckBox)" cast is superfluous. {444} Bottom of page (command window depiction); The contents of the command window should be changed from: % java GameSaver Elf Troll Magician to: % java GameSaverTest One's type: Elf Two's type: Troll Three's type: Magician {448} QuizCard UML-like diagram, middle of page; Format of UML-like diagram for QuizCard class has had no prior explanation of the components and does not correspond to similar example on page 255 (which is also presented without explanation). {451} Middle of page, within highlighted box; JFileChooser fileSave = new JFileChooser(); fileSave.showSaveDialog(frame); saveFile(fileSave.getSelectedFile()); could potentially benefit from an added conditional test: JFileChooser fileSave = new JFileChooser(); fileSave.showSaveDialog(frame); if (fileSave.getSelectedFile() != null) saveFile(fileSave.getSelectedFile()); This will prevent the java.lang.NullPointerException which results from cancelling out of the file chooser dialog. {456} Instance variables in class QuizCardPlayer; private JTextArea answer is declared but never used in the class. {471} Photo; The phone has little bubbles coming out if it like it's going to say something, but there's no thought bubble. [483] Paragraph labeled "3" under "How it works".; Well, it's a serious technical mistake regarding TCP. It doesn't really affect the Java that's used here. "...the method returns a plain old Socket (on a different port)... The Socket is on a different port than the ServerSocket, so that the ServerSocket can go back to waiting for other clients" That's not how TCP works. The Socket ends up with the same local port number as the ServerSocket. A TCP connection is defined by the tuple of the client's IP and port and the server's IP and port: it's the *combination* of those four items that identifies a connection, so the server doesn't have to reserve the port for listening purposes. (510) 6th paragraph; "So if you don't lock the back account" should read "So if you don't lock the bank account" [512] Paragraph beginning "The trick..." (and then the source code for TestSync); The text implies--at least this is my reading--that ++ is an atomic operation. It's not. An easy way to see this is to revise TestSync as follows: (1) in increment(), just do balance++; (2) and then in run(), crank the upper bound on the for loop up (I just started adding zeros and--on a Mac mini--started seeing funny results given a few runs of the program with the upper bound at five million--er, with the print statement moved down after the loop in run(), so it didn't take forever to run). [579] 4th question; The 4th box should be checked. The statement ArrayList dogs = new ArrayList(); does indeed compile... (584) Last line on page - Running your code; %java Mini should read: %java MyApp (585) Last bullet 3; %cd MiniProject/classes should read: %cd MyProject/classes (596) Inside Thought Bubble over illustration; The text in the thought bubble appears to be missing a final word (and period) like " release." or " version." (599) code; "~kathy" should be removed from the "codebase=" line so that the following comment is true: "This example shows that MyApp.jnlp is available in the root directory of the web server ..." (602) Exercise 11; Exercise 11: The corresponding answer to exercise 11 on page 604 indicates that 11 is "True". Either the wording of this question could use clarification or this is incorrect as it does not matter where the source file resides (absolute path to source file is unrelated to the classes location in package hierarchy--you can put the source file anywhere). Though it is a good idea/good practice to make them match as alluded to at the bottom of page 589. {619} bottom of the page in public static void main; Naming.rebind("Remote Hello", service) s/b Naming.rebind("RemoteHello", service) The space is not allowed - executing javac MyRemoteImpl with the space results in an error. See also page 621, and remove the space from Naming.lookup("rmi:127.0.0.1/Remote Hello"); (674) Last sentence in 1st paragraph; To be "state of the art," the Traverser's code would need to be Java 5, not Java 1.4.