Errata

Head First Java

Errata for Head First Java

Submit your own errata for this product.

Have a question? Try the forums at JavaRanch first.

The errata list is a list of errors and their corrections that were found after the product was released.

The following errata were submitted by our customers and have not yet been approved or disproved by the author or editor. They solely represent the opinion of the customer.

Color Key: Serious technical mistake Minor technical mistake Language or formatting error Typo Question Note Update

Version Location Description Submitted by Date submitted
PDF Page xxiv
Second paragraph

First graphic covers a portion of the text.

Anonymous  Jan 28, 2016 
Other Digital Version IV
candidates

Chapter 4. Methods Use Instance Variables: How Objects Behave >>
section "Mixed Messages": when I run candidate [ x <19 and index < 1 ] I don't get "20 and 1" as a response. My response says 26-1. How come please? What am I doing wrong?

public class Mix4TestingDrive20One {
public static void main(String[] args){
int count = 0;
Mix414One[] m4a = new Mix414One[20];
int x = 0;
while(x < 19){
m4a[x] = new Mix414One();
m4a[x].counter = m4a[x].counter +1;
count = count +1;
count = count + m4a[x].maybeNew(x);
x += 1;
}
System.out.println((count + " " + m4a[1].counter));
}

public class Mix420One {
int counter = 0;
public int maybeNew(int index){
if(index < 1){
Mix420One m4 = new Mix420One();
m4.counter = m4.counter + 1;
return 1;
}
return 0;
}

Chantal Decraie  Jan 13, 2021 
ePub Page VII
not known

there are no numbers on this e-digital version of Head First Java. So it's about chapter 7 concerning the "Sharpen your Pencil" Doctor-Surgeon-Family Doctor. I can't find the response any ware.
Also, there is no descend example of the inheritance concerning the Felin/Canin/Hypo classes. Could someone tell me where to call upon the methods, where to declare the variables please? because it doesn't work for me. IntelliJ can't find the methods/variables.
Thanks in advance.

Chantal Decraie  Jan 28, 2021 
Printed Page NA
NA

How do I go about this book for practice purposes? I have completed 200 pages till now with completion of all the exercises provided with the chapters but I am still unable to write some basic programs by myself. Whereas, my theoretical knowledge has been up to mark till now.
Can you please help me with how do I go about the book to get sufficient practice?

Chirantan Jain  Nov 15, 2021 
Printed Page Page 259
Sharpen your pencil

It's not an error but a suggestion. I cannot tell just by looking at the code which ones will have errors. I read the chapter and understood it but I'm not sure of my answers. I found the code online and put it into my IDE. Does it require calling the SonOfBoo from a main class? A user with only two posts worked on this 9 years ago. She seemed to figure out the answers but also mentioned that the book does not give the answers. Perhaps explain how to go about knowing which ones are legal. Should we be able to figure it out from what we read or is there a way to try them. Maybe provide the answers along with an explanation.

Kevin Abel  Jun 27, 2023 
Printed Page P268
Instructions of BE the Garbage Collector

Even after looking at the Answers I cannot convince myself if the lines added at the "A" are cumulative or placing one at a time. Without knowing I don't know which way to enter the lines of code.

Kevin Abel  Jun 30, 2023 
Printed Page page 348
code at bottom of page in the if statement

//both references are referring to either a
//a single object, or to two...

The word "a" is repeated on the second line.

Kevin Abel  Jul 12, 2023 
Printed Page P385
Last line of code before the output image

The line of code which reads:

System.out.println("result = " + result);

I think it should be:

System.out.println("result = " + limit);

I'm new to Java streams so I might not be correct. Please let me know.

Thanks,

Kevin Abel

Kevin Abel  Jul 15, 2023 
Printed Page Page 440 and 457
Page 440 bottom question below the dashed line

The task is to create two different legal try/catch structures. I'd expect it to start off looking like:
try{
x.doRisky;
}catch (BoinkEx a){
//recovery from BoinkEX
} catch (BarEx b){
//recovery from BarEx
.
.
.
The answer on page 457 is referring to the names of the exceptions from the example on top of the dashed line.

The answer in the book is showing a block diagram where Beta x and Gama x are at the same level of hierarchy. I don't see any clue on page 440 that tells the reader that they are at the same level.

The answer in the book is wrong or I don't understand the exercise.

Kevin Abel  Jul 27, 2023 
Printed Page Page 473
bottom right in hand written comments

I ran this past the folks on Code Ranch. The replies were "not clear", "It is wrong" , "It is correct". I'm the newest Java programmer in the group so I can't decide.

Next to :
Random random = new Random();
int red = random.nextInt(256);

The handwritten notes that says:
It has a next int method that takes a max value and returns a number between 0(inclusive) and this max value(not inclusive). In this case 0-256.

I'm thinking that the last sentence should say :
In this case 0-255.

Again...I'm not sure.

Kevin Abel  Aug 16, 2023 
Printed Page xxix
bottom right of page

A) Ready-Bake Code location is:
orei.ly/hf.Java_3e_examples

I didn't see the period between hf and java. I was contacting the publisher and they were telling me that they can see the code with the link.

B) I kept seeing the changes to the code at the ready bake site.
I was clicking on the right side that is the description . I should have been using the left side hyperlink. It seem obvious now, but I was confused for months not knowing why I could not get to the code.
Ron McLead on the Ranch solved the mystery.

I was clicking on the last change column instead of the name column.




Kevin Abel  Nov 07, 2023 
Printed Page 2
Image, item 2

Item 2 reads: "The compiler check for errors and won't let you compile..." It should read "The compiler check for SYNTAX errors and won't let you compile".

Juan Carlos  Nov 09, 2016 
PDF Page 6
Right column text

Text is not vertically centered in the cell:
print out “Dog: Fido” (the value of ‘name’ is “Fido”) at the command-line

Anonymous  Jan 28, 2016 
PDF Page 8
Top, Middle Left, Middle Right

This is in the Sharpen Your Pencil answers PDF and there may be more, but here is one example from page #8:

"Page 165" should be "Page 169"

"Page 172" should be "Page 176"

"Page 175" should be "Page 179"

Anonymous  Dec 20, 2009 
Printed Page 8-9

On page 8, it says "at least one main method", which I think it should be "exactly one main method". On page 9, it says "running a program means telling the JVM to <<Load the MyFirstApp class [...] >>", that could be "running THE program", instead, because it can be confusing for a beginner.

Anonymous  Aug 06, 2017 
PDF Page 10
Last code snippet, line 6

Bitwise AND operator & used instead of logical AND &&:

if ((x < 3) & (name.equals(?Dirk?))) {

Anonymous  Nov 22, 2011 
PDF Page 14
Last paragraph

Extra space before comma:
See if you can spot the flaw , and fix it.

Anonymous  Jan 28, 2016 
PDF Page 24

The puzzle has an alternative correct answer (code).

In my opinion the way I did it felt more natural as the words "a noise", "annoys", "an oyster" flowed more naturally in seequence within the code itself and looked more clear. Like if other person would read my code he would be able to follow it more easy. Just my opinion.

class PoolPuzzleOne{
public static void main(String[] arges){
int x = 0;
while(x < 4){
System.out.print("a");
if(x < 1){
System.out.print(" ");
}
System.out.print("n");
if(x < 1){
System.out.print("oise");
x =x -1;
}
if (x==1){
System.out.print("noys");
}
if(x > 1){
System.out.print(" oyster");
}
System.out.println("");
x = x + 2;
}

}
}

Rain Tuur  Sep 27, 2016 
Printed Page 47
line 6

There is an Error in the code solution for the Pool Puzzle:
"Echo e2 = e1;" is not correct. Because in this case, the final count variable will equal 24, that's because object is a refrence type so in this case, e2 and e1 variables are pointing to the same object.

Adir Noyman  Mar 24, 2019 
Printed, PDF, Other Digital Version Page 50
bottom

Puzzle: Pool Puzzle

mistake in pool:
System.out.print("a ");

but in answers uses:
System.out.print("a");

the puzzle is not solved without an answer....
offensively

Roman Korneev  Oct 10, 2018 
Printed Page 62 - Chapter 3
Class Dog

On p. 62, the page begins writing a class.
Class Dog{
String name;
Public static void main(String[] args){
//make a Dog object and access it
Dog dog1 = new Dog(); - questioning this statement
....//more main() items are here

Dog[] myDogs = new Dog[3]; - questioning this statement
....//remainder of main() items are here.
}
Public void bark(){
// ...bark() statements here
}
Public void eat(){
}
Public void chaseCat(){
}
}// class

—————————
I apologize in advance for the capitalization of the keywords “Public” and “Class”, but that’s the automatic capitalization going into effect.
In any case, my issue is why are we creating a Dog object “dog1” and then a Dog[] myDogs inside of the very class Dog that we are still writing? That won’t compile because the class Dog hasn’t been created.

Based on the earlier text of the book, shouldn’t we have put the main() in a class similar to your convention and call that class something like “DogTestDrive”, and create the dog1 object there and use the methods? Then we can just write class Dog with the instance variable and the define the methods?

Looking forward to your response.

Thank you.

Anonymous  Feb 04, 2023 
PDF Page 78
Last answer

Redundant word:
In this case, you’re calling the method for the work it does inside the method, rather than for what the method gives returns.

Possible correction:
In this case, you’re calling the method for the work it does inside the method, rather than for what the method returns.

Anonymous  Jan 30, 2016 
Printed Page 106
United States

P. 106 Output box in the lower right corner says "hit" followed by "passed" but the string "passed" appears no where in the code on p 106 and does not appear in the compiled output.

IBurbey  Feb 03, 2014 
Printed Page 110
Code example

Code as written does not compile. It needs the class declaration such as:

public class SimpleDotComGame {

along with the closing brace at the end of the example.

Anonymous  Aug 30, 2011 
Printed Page 139
New and Improved Startup Class

This is a question that might lead to an improvement. After updating the code it no longer runs because the CheckYourself method is being sent an int. I don't know if I did something wrong to make the new submarine code compile or is the book showing me how to improve the Startup class and leaving it to the reader to figure out how to fix it. Will the book expect me to have the code working to go on to the next 3D version or does it give new code to start with? Perhaps finish the topic by assisting the reader on how to fix the application so that the reader is not left with broken code before moving on. Also the fix explanation would give the reader a bit more confidence.

Kevin Abel  Jun 05, 2023 
PDF Page 140||152
pic of grid || placeDotCom()

Chapter 6.
Symbols of rows and columns are mixed up.
See the picture on p.140 (virtual grid 7x7) and the code of method placeDotCom():

row = (int) (coords[x] / gridLength); // get row value
column = coords[x] % gridLength; // get numeric column value
temp = String.valueOf(alphabet.charAt(column)); // convert to alpha

shark_ua  Apr 27, 2015 
Printed Page 140
Bottom left

Hi,
The grid at page 140 shows letters for rows and numbers for columns.
But the Java code on next pages assume the opposite.
Example: the method getAlphaCoordsFromIndex() in the ready-bake-code at page 153 use letters as columns and numbers as rows.

Thanks!
JF
Note: I found that incoherence because i program a graphic version using Swing.

Jean-François Landry  Mar 31, 2023 
ePub Page 145
Prep Code for method checkUserGuess()

The line which says REPEAT with each of the DotObjects in the dotComsList array

should be . . .

REPEAT with each of the DotCom objects in the dotComsList array

The objects are DotCom objects, not DotObjects

Anonymous  Aug 24, 2012 
Printed Page 149
9th line of checkUserGuess method

Line reads: dotComsList.remove(dotComToTest);

dotComToTest is not declared anywhere.

I imagine this is an error introduced from the fix of a previous errara.

Line should read: dotComsList.remove(userGuess);

Note from the Author or Editor:
9th line of code that reads:
dotComsList.remove(dotComToTest);

should be:
dotComsList.remove(userGuess);

Anonymous  Oct 05, 2011 
Printed Page 149
4th line, starting with "for(int x = 0;..."

The for loop on page 149 should match the corresponding for loop on page 147, shouldn't it? Are both versions of this loop valid?

Anonymous  Jun 30, 2017 
Printed Page 153
Code Line 6

The GameHelper code, belonging to the Dotcom exercises one can find in the printed version and in the example code of the page has a bug. The code is not able to place a dotcom in the first line horizontally.

This: if ( x>0 & (location % gridLength == 0))

Should be: if (incr == 1 & x>0 & (location % gridLength == 0))

Florian Tönjes  Feb 10, 2013 
Printed Page 153
placeDotCom function

There are 2 errors in the function:
(starting from the beginning of Pg 153)

1. coords[x++] = location;
2. location += incr;
3. if (location >= gridSize) {
4. success = false;
5. }
6. if (x > 0 && (location % gridLength == 0 ) ) {
7. success = false;
8. }
....

error 1: Line 6, the x > 0 will always be true since x is incremented on Line 1.
error 2: should move Line 2 to the end of code section. For example, DotCom Locations of 4, 5, 6 will never be generated because in the iteration where location is 6, it is increased to 7 on Line 2 (assume horizontal), and success will be false on Line 3.

Yanzhuo Wang  Apr 17, 2015 
PDF Page 153
placeDotCom()

Algorithmic error:
placeDotCom() can"t place vertical "DotComs" in first column.
------------------------------------------------------------------------------------

if (x>0 && (location % gridLength == 0))

must be changed to:

if(incr == 1 && (location % gridLength ==0))

shark_ua  Apr 27, 2015 
PDF Page 153
placeDotCom(int comSize)

Original code:

while (success && x < comSize) {
if (grid[location] == 0) {
coords[x++] = location;
location += incr;
if (location >= gridSize) {
success = false;
}
if (x > 0 && (location % gridLength == 0)) {
success = false;
}
...
}

Original code does not allow to place a dotCom in the first line horizontally and vertically when location is in E row. For example, when location is 46:
coord[0] = 46; location = 47; success = true;
coord[1] = 47; location = 48; success = true;
coord[2] = 48; location = 49; success = false !
So dotCom cannot be placed in E46, E47, E48 and it is a mistake.

if (incr == 1 && (location % gridLength ==0)) does not solve the problem.

Should be:

while (success && x < comSize) {
if (grid[location] == 0) {
coords[x++] = location;
if (location >= gridSize) {
success = false;
}
if (incr == 1 && (((location + 1) % gridLength == 0) && ((x - 1) != 2))) {
success = false;
}
location += incr;
...
}

Artyom Shootov  Dec 12, 2015 
PDF Page 153
placeDotCom(int comSize)

Small addition to my last correction:

Original code: private int[] grid = new int[gridSize];
Should be: private int[] grid = new int[100];

Grid array contains of 0 (if a field is empty) and 1 (if part of dotCom is placed in a field), so it is not a mistake that size of the array is not 49. With this correction dotComs can be placed everywhere.

Artyom Shootov  Dec 12, 2015 
Printed Page 189
3rd quesion.....last paragraph in the answer....

In page num 189,there is an error in the answer for the 3rd question.
The answer given is"The third issue is that if a class has only private constructors,it can't be subclassed"...
If a class has only private constructors,we can't instantiate that class,but we can extend that class...so,please verify...

Anonymous  Jun 20, 2011 
Printed Page 193
bottom of page

Dragon is stated to "breath fire", but should be "breathe fire" in both the code line and the console window.

Collin Tobin  Feb 13, 2020 
Printed Page 195
Be the complier exercise. monsters[2] = new Monster(); in main class

My IDE is complaining about new Monster, I'm not sure if it is legal to have an object be the same name as the Array.

public static void main(String[] args) {
Monster[] monsters = new Monster[3];
monsters[0] = new Vampire();
monsters[1] = new Dragon();
monsters[2] = new Monster(); <-- IntelliJ complains here.
for (int i = 0; i < monsters.length; i++) {
monsters[i].frignten(i);
}
}

Kevin Abel  Jun 20, 2023 
Printed Page 198
Hippo-Class

The class Hippo can't be a concrete class because the method roam() has to be overwritten.

Anonymous  Sep 03, 2011 
Printed Page 257
Animal class code

public String getName.

I think that the "{" is missing

Kevin Abel  Sep 04, 2023 
Printed Page 270
Popular Objects solution

End of arrow should point to ba[x].hunny = honeyPot instead of ... new Bear();

last two arrows have to be a line deeper.

Anonymous  Sep 05, 2011 
Printed Page 270

The exercise in page 267 asks you to find the number of active reference to the most popular object.
Part 1 of the answer states that is "Honey" object
Part 2 counts the number of references to be 12. It should be 16. This is so as "b1.beeHA" also has 4 references to the "Honey" object.

R Chandrashekar  Oct 29, 2012 
Printed Page 270
Section "Popular Objects"

Section "Popular Objects" gives the answer of the exercise at page 267. I think the answer is wrong by saying " There are a total of 12 active references to..." It should be 16 because code " b1. beeHA = ha;" adds another 4 references to Honey object.

Yang Yu  Apr 17, 2013 
Printed Page 271
Bottom

Does not explain solution to fixing LifeSupport code:

Add super class radiator, change V2Radiator to extend radiator and add super(list) constructor, change V3Radiator to extend radiator.

class Radiator{
Radiator(ArrayList<SimUnit> list){}
}

class V2Radiator extends radiator {
V2Radiator(ArrayList<SimUnit> list) {
super(list);
for(int x=0; x<5; x++) {
list.add(new SimUnit("V2Radiator"));
}
}
}

class V3Radiator extends radiator {
V3Radiator(ArrayList<SimUnit> lglist) {
super(lglist);
for(int g=0; g<10; g++) {
lglist.add(new SimUnit("V3Radiator"));
}
}
}

Douglas Ken Larson  Oct 14, 2011 
Printed Page 274
code snippet with examples of java.lang.Math usage

java.lang.Math.round makes a resultu of type long , not int

IS:
int x = Math.round(42.2);
SHOULD BE:
long x = Math.round(42.2);

Anonymous  Dec 21, 2012 
Printed Page 291
Assignments paragraph

The assignment Double d = x don't work because of type mismatch. An Integer is not a double.

Anonymous  Sep 06, 2011 
Printed Page 298
middle, [width] comment

"if it is less than the width, it'll be padded with zeroes"

...should be:

"if it is less than the width, it'll be padded with spaces. To pad with zeroes, specify a leading zero for the width (i.e., 06)".

Ken A Collins  Jul 02, 2011 
Printed Page 305
An example of working with a Calendar object

In the code lines instead of "c.HOUR_OF_DAY", "c.DATE" must be "Calendar.HOUR_OF_DAY", "Calendar.DATE"

Alexey  Sep 26, 2015 
PDF Page 327
PDF bookmarks

Duplicate bookmarks
"Finally: for the things you want to do no matter what." appears in the book index twice and both instances point to the top of page 327.

Anonymous  Feb 09, 2016 
Printed Page 328
code sample

I don't know if things are more strict now but in Java 1.6 on a Mac and in Java 1.7 on a PC the compiler requires me to define the exception or to use a predefined one.

Solution 1
add this class to the code sample

static class ScaryException extends Exception {
// nothing else is required
}

Solution 2
change all references to ScaryException to Exception
1 in the catch block
2 in doRisky after throws
3 in doRisky after throw new

Donald Cook  Jul 30, 2012 
Printed Page 328
code snippet - class TestExceptions

1. @Don Cook

> static class ScaryException extends Exception {
> }

static keyword is not necessary, following code should be enought:

class ScaryException extends Exception {
}

----

2. I think, that return statement in method doRisky is not needed, imho code should be like this:

static void doRisky(String test) throws ScaryException {
System.out.println("start risky");
if ("yes".equals(test)) {
throw new ScaryException();
}
System.out.println("end risky");
}

----

&#321;ukasz Siwi&#324;ski  Jan 17, 2013 
Printed Page 328
N.B. 2nd edition - content of Flow Control example

The Flow Control example does not compile (Java 8) because the exception name, ScaryException, is undefined. The following line has to be added:

class ScaryException extends Exception {}

Does the example compile with earlier versions of Java ? Or does no one work the Sharpen your pencil tests ?

nicholas.cole@free.fr  Feb 24, 2018 
Printed Page 338
Snippet marked with (2)

// --------------------------------------------------------------------
// in the snippet marked (2) there is following code:
try {
Foo foo = new Foo();
foo.foof();
}
int y = 43;
} catch (FooException fex) {
System.out.println("handle FooException");
}

// --------------------------------------------------------------------
// it shold be rather like this (one bracket too much):

try {
Foo foo = new Foo();
foo.foof();
}
int y = 43;
catch (FooException fex) {
System.out.println("handle FooException");
}
// --------------------------------------------------------------------

&#321;ukasz Siwi&#324;ski  Jan 23, 2013 
Printed Page 342
nearly at the end of the code

The code as it is does work, but after it is finished something stays active because the player is not stopped when finished.
This can be solved by inserting the following code between "player.start();" and "} catch ...":

long length = player.getTickLength();
Thread.sleep(length*200);
player.close();

This happens at least another time in a similar piece of code on another page.

Anonymous   
Printed Page 342
End of block 4

The app throws an exception:
java.lang.IllegalStateException: sequencer not open

Add the following line of code right before player.start();
player.open();

This exception was thrown using java JDK 1.5.0 update 11 and Windows 8.1

Anonymous  Aug 03, 2015 
Printed Page 346
4th line inside try { }

Couldn't find where MidiEvent event is used. Maybe this line isn't necessary and may be removed (the code compiles and works without it).

Anonymous  Jan 19, 2010 
Printed Page 350
main hint for across 18

Java currently has 50 keywords including enum added in Java 5.
The book reflects it well at page 53 by showing the 50 keywords all in a table.
But at page 350 the hint for across 18 of JavaCross 7.0 suggests that the number is 49.

Accordingly, changing
18. One of Java's '49'
to
18. One of Java's '50'
would be one more step towards the perfection of the book.

ref. https://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html

Anonymous  Nov 21, 2014 
PDF Page 351
True or False section

Missing plural "s":
4. False, runtime exception can be caught.

Correction:
4. False, runtime exceptions can be caught.

Anonymous  Feb 09, 2016 
Printed Page 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(...);

Anonymous   
Printed Page 360
Code at the bottom - button.setText("I've been clicked");

Entered the code on this page into both Eclipse and BlueJ IDE's and got a NullPointerException at this line of code when I click'ed on the button.

Don Morrison  Oct 09, 2013 
PDF Page 360
Margin text

Extra dot (for period) or missing dot (for ellipsis):
Implement the ActionListener interface’s actionPerformed() method.. This is the actual event-handling method!

Possible correction:
Implement the ActionListener interface’s actionPerformed() method. This is the actual event-handling method!

Anonymous  Feb 21, 2016 
Printed Page 366
Box at the right side of the page

Below Graphics reference is stated:
drawPolygon.
Correct is: drawPolygon()

Anonymous  Jan 15, 2015 
Printed Page 379
code sample

This program has a side effect. The first time you click the ?Change Label? button the frame is resized, and every time the frame is resized the paintComponent method is called by the JVM. This changes the color of the circle. You can prevent this by saving the ?startColor? and ?endColor? in instance variables, and use a boolean instance variable to change the color only when you click the ?Change Color? button. Note: you also need to set the color when you set up the panel.

Donald Cook  Aug 03, 2012 
Printed Page 392
End of try block in go()

Call to sequencer.setTempoInBPM(120) should probably be done before
sequencer.start().

Anonymous   
Printed Page 392
just before halfway the code

In the method setUpGui() I am missing the middle line of the next three lines:

f.setContentPane(m1);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setBounds(30, 30, 300, 300);

And near the end of the page I am missing

long length = (long) (sequencer.getMicrosecondLength()/1000);
Thread.sleep(length);

sequencer.close();

as well, between "sequencer.setTempoInBMP(120);" and "} catch...".

Anonymous   
PDF Page 392
setUpGui methode

Should add
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
to close the tread when we close the window, as-is we need to do a ctrl-x to get the command line back.

Jean-Sebastien Gasse  Jun 14, 2012 
PDF Page 392
In the go methode of MiniMusicPlayer3

It is just a "nice to have" but instead of using direct integers for event types, I would have liked to see the constants provided by ShortMessage used.

So we would change
track.add(makeEvent(144, 1, r, 100, i));
track.add(makeEvent(176, 1, 127, 0, i));
track.add(makeEvent(128, 1, r, 100, i+2));

to
track.add(makeEvent(ShortMessage.NOTE_ON, 1, r, 100, i));
track.add(makeEvent(ShortMessage.CONTROL_CHANGE, 1, 127, 0, i));
track.add(makeEvent(ShortMessage.NOTE_OFF, 1, r, 100, i+2));

I find it easier to read NOTE_ON, NOTE_OFF and know what it does than 144 and 128

Jean-Sebastien Gasse  Jun 14, 2012 
Printed Page 394
Hints 3 and 10

The hint reads, "The listener's key method" which is very ambiguous due to the variety of event types. Based on the answer provided on 397, the hint should really read, "The ActionEvent listener's key method"

Correspondingly:
The hint "How a listener signs up" should read "How an ActionEvent listener signs up"

Tim Bradt  Aug 30, 2015 
Printed Page 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);

Anonymous   
Printed Page 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?

Anonymous   
Printed Page 422
immediately before try{} block

"track.add(makeEvent(192, 9, 1, 0, 15));" and associated comment. This does not produce the intended result. It generates an event on tick 15, at the start of beat sixteen. The track needs to be 16 beats long, so we need to guarantee an event at the END of beat sixteen - i.e. on tick 16. The overall code as it stands works only because of the presence of "track.add(makeEvent(176, 1, 127, 0, 16));" at the end of the preceding block, which adds sixteen (!) controller events to the track, presumably cut and pasted from the "track.add(makeEvent(176, 1, 127, 0, i));" on page 390 in an effort to cure the irregular rhythm otherwise produced.
My suggestion would be to delete "track.add(makeEvent(176, 1, 127, 0, 16));" and replace:
"track.add(makeEvent(192, 9, 1, 0, 15));"
with
"track.add(makeEvent(176, 9, 120, 0, 16));"
which has the effect of inserting an "All Sound Off" command at the end of beat sixteen and applying it to channel 9 (the percussion instruments) which we are using. (This seems more appropriate here than the "Program Change" command (192,...) or applying an "All Notes Off" command (176, 1, 127,...) to channel 1 which might actually be in use in another part of a more complex program.

HandyAllan  Dec 31, 2010 
Printed Page 428
An except is an object...of type exception. Paragraph 3. last word

The sentence ends as: "... and the parameter reference variable is ex."

should it be e rather than ex?
Perhaps ex has a meaning that I am not aware of.

Kevin Abel  Jul 17, 2023 
Printed Page 445
Declaration of instance attributes of GameCharacter

The instance attributes should be private to force using the getters.

Anonymous  Sep 17, 2011 
Printed Page 450/451
JPanel declaration

1. The LayoutManager of the JPanel should not be the default, FlowLayout to pass the outfit on page 448.

2. The inner classes should be private to prevent unclassified acces from outside.

Anonymous  Sep 17, 2011 
Printed Page 452
3rd line of code under item 3, "List the contents of a directory"

For loop at location begins with the following:

for (int = 0; i < dirContents.length; i++) {

However this code snippet won't compile in a program without including "()" after "length", as follows:

for (int = 0; i < dirContents.length(); i++) {

Anonymous  Jan 09, 2019 
Printed Page 456
code listing of class QuizCardPlayer

Program QuizCardPlayer has some issues:

1. if you click "Next Card" button before loading any quiz file then Exception will be thrown on console
2. you can only load one quiz, every another (after seeing message "That was last card") won't execute & it'll throw and Exception on console.

My solution for above issues is this patch:
---------------------------------------------------------------------------
--- a/hfj-en/src/ch14/QuizCardPlayer.java
+++ b/hfj-en/src/ch14/QuizCardPlayer.java
@@ -43,6 +43,7 @@ public class QuizCardPlayer {
display.setFont(bigFont);
display.setLineWrap(true);
display.setEditable(false);
+ display.setText("Load cards using menu!");

JScrollPane qScroller = new JScrollPane(display);
qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
@@ -51,6 +52,7 @@ public class QuizCardPlayer {
mainPanel.add(qScroller);
mainPanel.add(nextButton);
nextButton.addActionListener(new NextCardListener());
+ nextButton.setEnabled(false);

JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
@@ -126,6 +128,9 @@ public class QuizCardPlayer {
System.out.println("couldn't read the card file");
ex.printStackTrace();
}
+ nextButton.setEnabled(true);
+ display.setText("");
+ currentCardIndex = 0;
}

&#321;ukasz Siwi&#324;ski  May 10, 2013 
Printed Page 456
code block declaring private variables beneath QuizCardPlayer class declaration

The "private JTextarea answer" reference declaration in the second line of the private variable code block is not used anywhere in the rest of the program. It appears to be superfluous.

John Farrell  Jan 25, 2019 
Printed Page 457
method loadFile

The interface of the Quiz Card application allows the user to load more than one card set (sequentially). Loading a second card set after you've played with the first one produces problems.
At the end of method loadFile before the call to showNextCard, insert:

nextButton.setEnabled(true);

If you are following the text of the printed edition, insert also at the same point:
currentCardIndex = 0;

The scheme followed in the download code avoids this latter problem - looks like the authors (post publication) realised that, using the more up-to-date and much neater approach, they needed to initialise their Iterator but forgot earlier to initialise their iterator (

HandyAllan  Dec 10, 2010 
Printed Page 457
instance method loadFile()

After reader.close(); should be the currentCardIndex attribute set to 0. Otherwise it's not possible to play again in the same running.

Anonymous  Sep 17, 2011 
Printed Page 463/464
code examples

The os and is descriptors should be closed after usage

os.close();
is.close();

Anonymous  Sep 18, 2011 
Printed Page 479
under item 2

Note reads "Printwriter acts as its own bridge between character data and the bytes it gets from the Socket's...."

Seems that it should read "Printwriter acts as its own bridge between character data and and the bytes it sends to the Socket's..."

John Farrell  Apr 02, 2019 
Printed Page 483
How it works 3

Socket sock = serverSock.accept();

When serverSock.accept() returns, it does not return a socket on a different port. It still uses port 4242.

This is easily demonstrated by modifying the DailyAdviceServer.java slightly:

public void go() {
try {
ServerSocket serverSock = new ServerSocket(4242);
while (true){
Socket sock = serverSock.accept();
PrintWriter writer = new PrintWriter(sock.getOutputStream());
writer.println("This socket port is: " + sock.getLocalPort());
writer.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}

The text states "The socket is on a different port than the ServerSocket, so that the server socket can go back to waiting for other clients".

This isn't the case. The thing that has to be unique for each socket is the source port, source ip, destination port & destination ip.

Regards
Richard

ps: I think Head First Java is an excellent book.

Richard Hayward  Feb 04, 2012 
Printed Page 484
middle of page

Please change:
"Then we close the Socket because we're done with this client,"

To:
"Then we close the PrintWriter--and therefore sock's OutputStream--because we're done with this client."

Anonymous  Apr 02, 2019 
Printed Page 485
6th bullet point

A client does not make a server socket but a socket.

Anonymous  Sep 19, 2011 
PDF Page 485
6th bullet point

The 6th bullet point reads:
"A client connects to a server by making a Server socket
Socket s = new Socket(“127.0.0.1”, 4200);"

This is wrong: it should read:
"A client connects to a server by making a Socket:
Socket s = new Socket(“127.0.0.1”, 4200);"

the Server creates a Server socket, while the Client creates a regular Socket.

Vittorio Torroni  Aug 27, 2019 
Printed Page 487
SimpleChatClientA.go() code

Problem
=======

Chat client won't close if You click "close" button.

My solution
=========

There is:

setUpNetworking();
frame.setSize(400, 500);
frame.setVisible(true);

It should be:

setUpNetworking();
frame.setSize(400, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

siwinski.info  Jun 06, 2013 
Printed Page 512
The dreaded "Lost Update" problem code snippets.

**Problem**

Imho below code after running it, doesn't clearly show how synchronize works.

The code to change:

// p. 512
public void run() {
for(int i = 0; i<50; i++){
increment();
System.out.println("balance is " + balance);
}
}
public void increment() {
int i = balance;
balance = i + 1;
}
// p. 514
public synchronized void increment() {
int i = balance;
balance = i + 1;
}

**My solution**

Imho below code is better way to show (after running it) how synchronize can nicely grant/schedule access to methods by two (or more threads).

// p. 512
public void run() {
for(int i = 0; i<50; i++){
increment();
}
}
public void increment() {
int i = balance;
balance = i + 1;
System.out.println("balance is " + balance);
}
// p. 514
public synchronized void increment() {
int i = balance;
balance = i + 1;
System.out.println("balance is " + balance);
}

siwinski.info  Jun 28, 2013 
PDF Page 512,514
In the program TestSync

The print statement:
System.out.println("balance is " + balance);
should be within the increment method. Otherwise, the program shows unordered balance output even after it is synchronized.

Anonymous  Apr 08, 2016 
Printed Page 518
@ code

**Problem**

The chat client won't stop working after closing window.

**Solution**

Below code:

frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
frame.setSize(800, 500);
frame.setVisible(true);

Should be changed to:

frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 500);
frame.setVisible(true);

siwinski.info  Jul 08, 2013 
Printed Page 520-21
p. 520, code line 7; p. 521 code line 6

ArrayList requires an object-type to be defined. It has already been pointed out in Code Ranch but hasn't been added to the official errata list. However, the program written in the Ready-bake Code for the VerySimpleChatServer doesn't run if the object type is missing.

p. 520, code line 7 has
"ArrayList clientOutputStreams;"
which should be corrected to
"ArrayList<Writer> clientOutputStreams;"

p. 521, code line 6 has
"clientOutputStreams = new ArrayList();"
which should be corrected to
"clientOutputStreams = new ArrayList<Writer>();"

Correction is mentioned here:
https://www.coderanch.com/t/591427/java/java/VerySimpleChatServer-ready-bake-code-JavaHeadFirst

I hope the mistake is added to the official errata list.
Thank you for your great book, I love the series.

Anonymous  Oct 18, 2012 
Printed Page 526
code snippet that is solution for "code magnets" exercise

**Problem**

Presented solution (and the initial code magnets given to be resolved) won't
produce expected results each time when it's compiled & runned on Windows 7 (64 bit)
using Oracle's JVM as follow:

$ javac -version
javac 1.7.0_07
$ java -version
java version "1.7.0_25"
Java(TM) SE Runtime Environment (build 1.7.0_25-b17)
Java HotSpot(TM) Client VM (build 23.25-b01, mixed mode, sharing)

**Solution**

Changing code as below will make it more likely to achive the behaviour similar
to that which was expected in the book. Of course it'll produce different output
than was expected in book and the output won't allways be the same, because
each line is not an atomic (synchronized) operation.

Change 1 - change code in ThreadOne class:

for(int x=0; x < 98; x++) {
a.updateCounter(1000);

To this:
for(int x=0; x < 98; x++) {
System.out.println("--1: " + a.getCount());
a.updateCounter(1000);

Change 2 - change code in ThreadTwo classf from this:

for(int x=0; x<99; x++) {
a.updateCounter(1);
To this:

for(int x=0; x<99; x++) {
System.out.println("--2: " + a.getCount());

siwinski.info  Jul 19, 2013 
Printed Page 542
comment on the code snippet

**Problem**

There is a typo in comment to code snippet. Word "is"
in below paragraph is redundant:

##
Here's the important part! Whatever "E" is
determines what kind of things you're allowed
to add to the ArrayList.

**Solution**

It should look like this:

Here's the important part! Whatever "E"
determines what kind of things you're allowed
to add to the ArrayList.

siwinski.info  Jul 29, 2013 
Printed Page 564
middle comment

Change "We can add all the songs from the HashSet..." to "We can add all the songs from the ArrayList..."

Ken A Collins  Jul 06, 2011 
Printed Page 566
2nd code block

In the second code block (class Test)

the statemest is:
tree.add(new Book("How Cats Work");
instead of:
tree.add(b1);

becase b1 is already declared and instantiated above, plus there is one closing paranthesis missing.

Anonymous  Jul 26, 2016 
Printed Page 569
bottom command prompt window

There should only be three lines of "animal eating" output from the TestGenerics2 program, not six.

Ken A Collins  Jul 06, 2011 
Printed Page 570
screenshot showing compilation class TestGenerics3

There is:

% java TestGenerics3

Should be:

% javac TestGenerics3.java

Lukasz Siwinski (siwinski.info)  Mar 11, 2014 
Printed Page 575
Answer of "There are no dumb questions" section

The two alternative versions of the signature of the generic method takeThing, i.e.

public <T extends Animal> void takeThing(ArrayList<T> one, ArrayList<T> two)

and

public void takeThing(ArrayList<? extends Animal> one,
ArrayList<? extends Animal> two)

are implicitly presented as equivalent, but they have different semantics. For example, under the assumption that Cat and Dog are subtypes of Animal,

takeThing(ArrayList<Dog>, ArrayList<Cat>)

is legal in the second version, but is illegal in the first version.

Julien Cretel  Nov 11, 2015 
Printed Page 576
3rd item in compiles list

List<Animal> list= new ArrayList<Animal>()

ArrayList being implementation of List interface, List reference variable can hold the ArrayList object reference.

Amit Khurana  Jul 19, 2012 
Printed Page 618
Step three -- run rmic

Erroneous information. As of Java 5, there is no need to run rmic command unless backwards compatibility is desired. RMI generates stubs on the fly (in memory) and skeletons are no longer needed. Running rmic command will no longer produce a skeleton.

Ken A Collins  Jun 01, 2011 
Printed Page 619
bottom try { } block

Change "Remote Hello" to "Remote_Hello". Code bombs with "java.net.MalformedURLException: invalid URL String" error if remote object name contains spaces.

Ken A Collins  Jun 01, 2011 
Printed Page 620
Naming.lookup() statement in two places on page

Same error as page 619. Change "Remote Hello" to "Remote_Hello". Code bombs with "java.net.MalformedURLException: invalid URL String" error if remote object name contains spaces.

Ken A Collins  Jun 01, 2011 
Printed Page 622
whole page

Stub and skeleton class files are not needed as of Java 5.

Ken A Collins  Jun 01, 2011 
Printed Page 625
two diagrams in bottom half of page

Class file located on Web Server that responds to client request should be named "RegisterServlet.class", not "MyServlet.class".

Ken A Collins  Jun 01, 2011 
Printed Page 629
servlet code

Problem
=======

There's a omission typo in KathyServlet code.

My solution
=========

There is:

out.println("<P>" + PhraseOmatic.makeAPhrase());

It should be:

out.println("<P>" + PhraseOmatic.makeAPhrase() + "</P>");

----

siwinski.info  Jul 07, 2014 
Printed Page 644
top

It is not necessary to import the java.io.* package in the DiceService.java program.

Ken A Collins  Jun 08, 2011 
Printed Page 645
top

It is not necessary to import the java.io.* package in the MiniMusicService.java program.

Ken A Collins  Jun 08, 2011 
Printed Page 647
top

It is not necessary to import the java.io.* package in the DayOfTheWeekService.java program.

Ken A Collins  Jun 08, 2011 
Printed Page 651
inside buildGUI() method.

The music won't stop if I close the Beatbox window without pressing the "Stop" button first.

I added
theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE), as in chapter 13.

Pxx  Mar 04, 2021 
Printed Page 651
inside buildGUI() method.

The music won't stop if I close the Beatbox window without pressing the "Stop" button first.

I added
theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE), as in chapter 13.

Pxx  Mar 04, 2021 
Printed Page 653
line 21

replace:
"track.add(makeEvent(192, 9, 1, 0, 15));"
with
"track.add(makeEvent(176, 9, 120, 0, 16));"

See my comments on similar erratum on page 422

HandyAllan  Dec 31, 2010 
Printed Page 655
lower third

the section in the final beatbox code contains a class called "MyPlayListener" that is not used anywhere.

also I found comments in the code that says "exactly the same" but its not the same ...for instance the use of the Iterator in the makeTracks method...this is not the same as found on page 423 in makeTracks.

also the use of numKey in the same method

BUT IT'S STILL A REALLY GREAT BOOK!!!

Anonymous  Jan 06, 2010 
Printed Page 658
code snippet, method [public void go()]

PROBLEM:

Missing semicolon in this line:

ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream())

This causes compilation error.

SOLUTION

Code should be look like that:

ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream());

siwinski.info  Aug 01, 2014 
Printed Page 673
one-third of way down and bottom

Comment one-third of way down:

...the "sing()" method), if sing() is called...

should state:

...the "sings()" method), if sings() is called...

Comment at bottom, to right of command prompt:

...basic "sing()" method...

should state:

...basic "sings()" method...

Ken A Collins  Jun 08, 2011 
Printed Page 678
index for the alphabet B

When i looked up the index for Brain barbell, i found that the pages listed for it (33,167,188) were actually pointing t Brainpower and not brain barbell.

Anonymous  Oct 08, 2011 
ePub Page 3176
start of code

missing "*"
import java.io;
should be
import.java.io.*;

Ted Schantz  Aug 28, 2013 
ePub Page 3685
bottom

chapter 6 zip file does not have the code for the helper class.
The downloadable code for helper class is misplaced in chapter 5 zip, instead it should be in chapter 6 zip.

A simpler basic version of the helper code should be chapter 5 zip

Anonymous  Aug 29, 2013 
Mobi Page 7838
Kindle version near locations 7838 and 7861, inside "for" loop

In the code for MiniMusicPlayer2 and MiniMusicPlayer3 (a few pages later), inside the for loop, there are three calls to "track.add()". On my version of Java (1.8.0_74) the notes will not play if event 176 (CONTROL_CHANGE) is added *between* events 144 (NOTE_ON) and 128 (NOTE_OFF). But, if the code is change to add 176 *first*, the notes play. I.e. change

track.add(makeEvent(144,1,i,100,i));
track.add(makeEvent(176,1,127,0,i));
track.add(makeEvent(128,1,i,100,i+2));

to

track.add(makeEvent(176,1,127,0,i));
track.add(makeEvent(144,1,i,100,i));
track.add(makeEvent(128,1,i,100,i+2));

Anonymous  Apr 25, 2016 
PDF, ePub, Mobi Page 18749
text

Current
cool thing is that you can change your mind later. you can come back and make a method safer, faster, better.

Suggested
"mind later. you can come" should be "mind later. You can come"

------------

Current
your app. After that, the end-user can launch your application directory from the JWS helper app without having to go back

Suggested
"your application directory from the" should be "your application directly from the"

Anonymous  Sep 23, 2019