100% found this document useful (1 vote)
34 views

Head First Java 2nd Edition Kathy Sierra pdf download

The document provides links to download various educational ebooks, including 'Head First Java 2nd Edition' by Kathy Sierra. It includes a brief overview of the book's content, such as its focus on Java programming concepts and object-oriented design. Additionally, it lists other related titles available for download on the same website.

Uploaded by

hynniamidah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
34 views

Head First Java 2nd Edition Kathy Sierra pdf download

The document provides links to download various educational ebooks, including 'Head First Java 2nd Edition' by Kathy Sierra. It includes a brief overview of the book's content, such as its focus on Java programming concepts and object-oriented design. Additionally, it lists other related titles available for download on the same website.

Uploaded by

hynniamidah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Head First Java 2nd Edition Kathy Sierra pdf

download

https://ebookfinal.com/download/head-first-java-2nd-edition-
kathy-sierra/

Explore and download more ebooks or textbooks


at ebookfinal.com
We have selected some products that you may be interested in
Click the link to download now or visit ebookfinal.com
for more options!.

Badass Making Users Awesome 1st Edition Kathy Sierra

https://ebookfinal.com/download/badass-making-users-awesome-1st-
edition-kathy-sierra/

OCA OCP Java SE 7 Programmer I II Study Guide Exams 1Z0


803 1Z0 804 1st Edition Kathy Sierra

https://ebookfinal.com/download/oca-ocp-java-se-7-programmer-i-ii-
study-guide-exams-1z0-803-1z0-804-1st-edition-kathy-sierra/

Head First Algebra Tracey Pilone

https://ebookfinal.com/download/head-first-algebra-tracey-pilone/

Head First Python A Brain Friendly Guide 2nd Edition Paul


Barry

https://ebookfinal.com/download/head-first-python-a-brain-friendly-
guide-2nd-edition-paul-barry/
Head First Physics 1st Edition Heather Lang

https://ebookfinal.com/download/head-first-physics-1st-edition-
heather-lang/

Head First C Third Edition Jennifer Greene

https://ebookfinal.com/download/head-first-c-third-edition-jennifer-
greene/

Head First Python 1st Edition Paul Barry

https://ebookfinal.com/download/head-first-python-1st-edition-paul-
barry/

Head First Design Patterns 1st Edition Eric Freeman

https://ebookfinal.com/download/head-first-design-patterns-1st-
edition-eric-freeman/

Head First Android Development 1st Edition Dawn Griffiths

https://ebookfinal.com/download/head-first-android-development-1st-
edition-dawn-griffiths/
Head First Java 2nd Edition Kathy Sierra Digital Instant
Download
Author(s): Kathy Sierra, Bert Bates
ISBN(s): 9780596009205, 0596009208
Edition: 2
File Details: PDF, 33.97 MB
Year: 2005
Language: english
:PVS#SBJOPO+BWB‰"-FBSOFST(VJEF
ND %DITION #OVERS *AVA

-FBSOIPXUISFBET
DBODIBOHFZPVSMJGF )FBE'JSTU
+BWB .BLF+BWBDPODFQUT
TUJDLUPZPVSCSBJO

'PPMBSPVOEJO
UIF+BWB-JCSBSZ

"WPJEFNCBSBTTJOH
00NJTUBLFT

#FOEZPVSNJOE
BSPVOE
+BWBQV[[MFT

.BLFBUUSBDUJWF
BOEVTFGVM(6*T

,BUIZ4JFSSB#FSU#BUFT
Table of Contents (summary)
Intro xxi
1 Breaking the Surface: a quick dip 1
2 A Trip to Objectville: yes, there will be objects 27
3 Know Your Variables: primitives and references 49
4 How Objects Behave: object state affects method behavior 71
5 Extra-Strength Methods: flow control, operations, and more 95
6 Using the Java Library: so you don’t have to write it all yourself 125
7 Better Living in Objectville: planning for the future 165
8 Serious Polymorphism: exploiting abstract classes and interfaces 197
9 Life and Death of an Object: constructors and memory management 235
10 Numbers Matter: math, formatting, wrappers, and statics 273
11 Risky Behavior: exception handling 315
12 A Very Graphic Story: intro to GUI, event handling, and inner classes 353
13 Work on Your Swing: layout managers and components 399
14 Saving Objects: serialization and I/O 429
15 Make a Connection: networking sockets and multithreading 471
16 Data Structures: collections and generics 529
17 Release Your Code: packaging and deployment 581
18 Distributed Computing: RMI with a dash of servlets, EJB, and Jini 607
A Appendix A: Final code kitchen 649
B Appendix B: Top Ten Things that didn’t make it into the rest of the book 659
Index 677

Table of Contents (the full version)

i Intro
Your brain on Java. (ERE YOU ARE TRYING TO LEARN SOMETHING WHILE HERE YOUR BRAIN
IS DOING YOU A FAVOR BY MAKING SURE THE LEARNING DOESNT STICK 9OUR BRAINS THINKING h"ETTER
LEAVE ROOM FOR MORE IMPORTANT THINGS LIKE WHICH WILD ANIMALS TO AVOID AND WHETHER NAKED
SNOWBOARDING IS A BAD IDEAv 3O HOW DO YOU TRICK YOUR BRAIN INTO THINKING THAT YOUR LIFE
DEPENDS ON KNOWING *AVA

Who is this book for? xxii


What your brain is thinking xxiii
Metacognition xxv
Bend your brain into submission xxvii
What you need for this book xxviii
Technical editors xxx
Acknowledgements xxxi

ix
1 Breaking the Surface
Java takes you to new places. &ROM ITS HUMBLE RELEASE TO THE PUBLIC AS THE
WIMPY VERSION *AVA SEDUCED PROGRAMMERS WITH ITS FRIENDLY SYNTAX OBJECT ORIENTED
FEATURES MEMORY MANAGEMENT AND BEST OF ALLˆTHE PROMISE OF PORTABILITY 7ELL TAKE A QUICK
DIP AND WRITE SOME CODE COMPILE IT AND RUN IT 7ERE TALKING SYNTAX LOOPS BRANCHING AND WHAT
MAKES *AVA SO COOL $IVE IN

The way Java works 2


Virtual Code structure in Java 7
Machines
Anatomy of a class 8
The main() method 9
Method Party() Looping 11
0 aload_0
Conditional branching (if tests) 13
1 invokespe-
cial #1 <Method Coding the “99 bottles of beer” app 14
java.lang.Object()>
Phrase-o-matic 16
4 return
Fireside chat: compiler vs. JVM 18
Compiled You Bet
Shoot Me

Exercises and puzzles 20


bytecode

2 A Trip to Objectville
I was told there would be objects. )N #HAPTER WE PUT ALL OF OUR CODE
IN THE MAIN METHOD 4HATS NOT EXACTLY OBJECT ORIENTED 3O NOW WEVE GOT TO LEAVE THAT
PROCEDURAL WORLD BEHIND AND START MAKING SOME OBJECTS OF OUR OWN 7ELL LOOK AT WHAT
MAKES OBJECT ORIENTED // DEVELOPMENT IN *AVA SO MUCH FUN 7ELL LOOK AT THE DIFFERENCE
BETWEEN A CLASS AND AN OBJECT 7ELL LOOK AT HOW OBJECTS CAN IMPROVE YOUR LIFE

Chair Wars (Brad the OO guy vs. Larry the procedural guy) 28
Inheritance (an introduction) 31
Overriding methods (an introduction) 32
What’s in a class? (methods, instance variables) 34
Making your first object 36
Using main() 38
Guessing Game code 39
Exercises and puzzles 42

x
3 Know Your Variables
Variables come in two flavors: primitive and reference.
4HERES GOTTA BE MORE TO LIFE THAN INTEGERS 3TRINGS AND ARRAYS 7HAT IF YOU HAVE A 0ET/WNER
OBJECT WITH A $OG INSTANCE VARIABLE /R A #AR WITH AN %NGINE )N THIS CHAPTER WELL UNWRAP
THE MYSTERIES OF *AVA TYPES AND LOOK AT WHAT YOU CAN DECLARE AS A VARIABLE WHAT YOU CAN PUT
IN A VARIABLE AND WHAT YOU CAN DO WITH A VARIABLE !ND WELL FINALLY SEE WHAT LIFE IS TRULY LIKE
ON THE GARBAGE COLLECTIBLE HEAP

Declaring a variable (Java cares about type) 50


24
size Primitive types (“I’d like a double with extra foam, please”) 51
Java keywords 53
int
Reference variables (remote control to an object) 54
ct Object declaration and assignment 55
Dog obje
Objects on the garbage-collectible heap 57
fido Arrays (a first look) 59
Exercises and puzzles 63
Dog reference

4 How Objects Behave


State affects behavior, behavior affects state. 7E KNOW THAT OBJECTS
HAVE STATE AND BEHAVIOR REPRESENTED BY INSTANCE VARIABLES AND METHODS .OW WELL LOOK
AT HOW STATE AND BEHAVIOR ARE RELATED !N OBJECTS BEHAVIOR USES AN OBJECTS UNIQUE STATE
)N OTHER WORDS METHODS USE INSTANCE VARIABLE VALUES ,IKE hIF DOG WEIGHT IS LESS THAN
POUNDS MAKE YIPPY SOUND ELSEv ,ETS GO CHANGE SOME STATE

Methods use object state (bark different) 73


pass-by-value means Method arguments and return types 74
pass-by-copy Pass-by-value (the variable is always copied) 77
Getters and Setters 79

copy of Encapsulation (do it or risk humiliation) 80


x Using references in an array 83
111 0 111
00 00 Exercises and puzzles 88
0 00
00
X Z
int int
foo.go(x); void go(int z){ }

xi
5 Extra-Strength Methods
Let’s put some muscle in our methods. 9OU DABBLED WITH VARIABLES
PLAYED WITH A FEW OBJECTS AND WROTE A LITTLE CODE "UT YOU NEED MORE TOOLS ,IKE
OPERATORS !ND LOOPS -IGHT BE USEFUL TO GENERATE RANDOM NUMBERS !ND TURN
A 3TRING INTO AN INT YEAH THAT WOULD BE COOL !ND WHY DONT WE LEARN IT ALL BY BUILDING
SOMETHING REAL TO SEE WHAT ITS LIKE TO WRITE AND TEST A PROGRAM FROM SCRATCH -AYBE A
he GAME LIKE 3INK A $OT #OM SIMILAR TO "ATTLESHIP
e ’r e g o n na build tame
W t Com g
Sink a Do Building the Sink a Dot Com game 96
Starting with the Simple Dot Com game (a simpler version) 98
!
Writing prepcode (pseudocode for the game) 100
"
'OCOM

Test code for Simple Dot Com 102


#
Coding the Simple Dot Com game 103
$ 0ETSCOM
Final code for Simple Dot Com 106
%
Generating random numbers with Math.random() 111
&
Ready-bake code for getting user input from the command-line 112
' !SK-ECOM
Looping with for loops 114

Casting primitives from a large size to a smaller size 117
Converting a String to an int with Integer.parseInt() 117
Exercises and puzzles 118

6 Using the Java Library


Java ships with hundreds of pre-built classes. 9OU DONT HAVE TO
REINVENT THE WHEEL IF YOU KNOW HOW TO FIND WHAT YOU NEED FROM THE *AVA LIBRARY COMMONLY
KNOWN AS THE *AVA !0) 9OUVE GOT BETTER THINGS TO DO )F YOURE GOING TO WRITE CODE YOU
MIGHT AS WELL WRITE ONLY THE PARTS THAT ARE CUSTOM FOR YOUR APPLICATION 4HE CORE *AVA LIBRARY
IS A GIANT PILE OF CLASSES JUST WAITING FOR YOU TO USE LIKE BUILDING BLOCKS

Analying the bug in the Simple Dot Com Game 126


h'OOD TO KNOW THERES AN !RRAY,IST IN ArrayList (taking advantage of the Java API) 132
THE JAVAUTIL PACKAGE "UT BY MYSELF HOW Fixing the DotCom class code 138
WOULD ) HAVE lGURED THAT OUTv
Building the real game (Sink a Dot Com) 140
- Julia, 31, hand model
Prepcode for the real game 144
Code for the real game 146
boolean expressions 151
Using the library (Java API) 154
Using packages (import statements, fully-qualified names) 155
Using the HTML API docs and reference books 158
Exercises and puzzles 161

xii
7 Better Living in Objectville
Plan your programs with the future in mind. 7HAT IF YOU COULD WRITE
CODE THAT SOMEONE ELSE COULD EXTEND EASILY 7HAT IF YOU COULD WRITE CODE THAT WAS FLEXIBLE
FOR THOSE PESKY LAST MINUTE SPEC CHANGES 7HEN YOU GET ON THE 0OLYMORPHISM 0LAN YOULL
LEARN THE STEPS TO BETTER CLASS DESIGN THE TRICKS TO POLYMORPHISM THE WAYS TO MAKE
FLEXIBLE CODE AND IF YOU ACT NOWˆA BONUS LESSON ON THE TIPS FOR EXPLOITING INHERITANCE

Understanding inheritance (superclass and subclass relationships) 168


Designing an inheritance tree (the Animal simulation) 170
Make it Stick Avoiding duplicate code (using inheritance) 171
Overriding methods 172
2OSES ARE RE
D VIOLETS ARE IS-A and HAS-A (bathtub girl) 177
3QUARE )3 ! BLUE
3HAPE THE RE
VERSE ISNT TR What do you inherit from your superclass? 180
2OSES ARE RE UE
D VIOLETS ARE
"EER )3 ! $RI DE AR What does inheritance really buy you? 182
NK BUT NOT AL
L DRINKS ARE
/+ YOUR TURN BEER Polymorphism (using a supertype reference to a subclass object) 183
-AKE ONE
WAY NESS OF THAT SHOWS Rules for overriding (don’t touch those arguments and return types!) 190
THE )3 ! RELA THE ONE
BER IF 8 EX TE TIONSHIP !ND
NDS 9 8 )3 ! REMEM Method overloading (nothing more than method name re-use) 191
9 MUST MAK
E SENSE
Exercises and puzzles 192

8
Serious Polymorphism
Inheritance is just the beginning. 4O EXPLOIT POLYMORPHISM WE NEED
INTERFACES 7E NEED TO GO BEYOND SIMPLE INHERITANCE TO FLEXIBILITY YOU CAN GET ONLY BY
DESIGNING AND CODING TO INTERFACES 7HATS AN INTERFACE ! ABSTRACT CLASS 7HATS AN
ABSTRACT CLASS ! CLASS THAT CANT BE INSTANTIATED 7HATS THAT GOOD FOR 2EAD THE CHAPTER

Some classes just should not be instantiated 200


Object o = al.get(id); Abstract classes (can’t be instantiated) 201
Dog d = (Dog) o; Abstract methods (must be implemented) 203
d.bark(); Polymorphism in action 206
Class Object (the ultimate superclass of everything) 208
Object
Taking objects out of an ArrayList (they come out as type Object) 211
D og t Compiler checks the reference type (before letting you call a method) 213
o objec
Get in touch with your inner object 214
cast t Polymorphic references 215
back tohe Object
Object
Casting an object reference (moving lower on the inheritance tree) 216
d know is a Dog we
there. Deadly Diamond of Death (multiple inheritance problem) 223
Dog
Using interfaces (the best solution!) 224
Exercises and puzzles 230

xiii
9 Life and Death of an Object
Objects are born and objects die. 9OURE IN CHARGE 9OU DECIDE WHEN AND
HOW TO CONSTRUCT THEM 9OU DECIDE WHEN TO ABANDON THEM 4HE 'ARBAGE #OLLECTOR GC
RECLAIMS THE MEMORY 7ELL LOOK AT HOW OBJECTS ARE CREATED WHERE THEY LIVE AND HOW TO
KEEP OR ABANDON THEM EFFICIENTLY 4HAT MEANS WELL TALK ABOUT THE HEAP THE STACK SCOPE
CONSTRUCTORS SUPER CONSTRUCTORS NULL REFERENCES AND GC ELIGIBILITY

The stack and the heap, where objects and variables live 236
calls
When someone od, this Methods on the stack 237
et h
the go() m oned. His Where local variables live 238
Duck is aband has been
only reference for a Where instance variables live 239
reprogrammed k. The miracle of object creation 240
Du ec differ
ent Duc Constructors (the code that runs when you say new) 241
t

ck obj
Initializing the state of a new Duck 243
d
Overloaded constructors 247
Du Heap Superclass constructors (constructor chaining) 250
ck objec
t

Invoking overloaded constructors using this() 256


ing the
‘d’ is assigned a new Duck object, leav . That Life of an object 258
original (first) Duck object abandoned Garbage Collection (and making objects eligible) 260
first Duck is toast..
Exercises and puzzles 266

Static variables
are shared by
10 Numbers Matter
Do the Math. 4HE *AVA !0) HAS METHODS FOR ABSOLUTE VALUE ROUNDING MINMAX ETC
"UT WHAT ABOUT FORMATTING 9OU MIGHT WANT NUMBERS TO PRINT EXACTLY TWO DECIMAL POINTS
OR WITH COMMAS IN ALL THE RIGHT PLACES !ND YOU MIGHT WANT TO PRINT AND MANIPULATE DATES
all instances of TOO !ND WHAT ABOUT PARSING A 3TRING INTO A NUMBER /R TURNING A NUMBER INTO A 3TRING
a class.
7ELL START BY LEARNING WHAT IT MEANS FOR A VARIABLE OR METHOD TO BE STATIC
static variable:
iceCream Math class (do you really need an instance of it?) 274
kid instance two
kid instance one static methods 275

instance variables: static variables 277


one per instance Constants (static final variables) 282
Math methods (random(), round(), abs(), etc.) 286
static variables:
one per class Wrapper classes (Integer, Boolean, Character, etc.) 287
Autoboxing 289
Number formatting 294
Date formatting and manipulation 301
Static imports 307
Exercises and puzzles 310

xiv
11 Risky Behavior
Stuff happens. 4HE FILE ISNT THERE 4HE SERVER IS DOWN .O MATTER HOW GOOD A
PROGRAMMER YOU ARE YOU CANT CONTROL EVERYTHING 7HEN YOU WRITE A RISKY METHOD YOU NEED
CODE TO HANDLE THE BAD THINGS THAT MIGHT HAPPEN "UT HOW DO YOU KNOW WHEN A METHOD IS
RISKY 7HERE DO YOU PUT THE CODE TO HANDLE THE EXCEPTIONAL SITUATION )N THIS CHAPTER WERE
GOING TO BUILD A -)$) -USIC 0LAYER THAT USES THE RISKY *AVA3OUND !0) SO WE BETTER FIND OUT

Making a music machine (the BeatBox) 316


What if you need to call risky code? 319
an excepti
ows on
hr 2 ba Exceptions say “something bad may have happened...” 320
ck
t

The compiler guarantees (it checks) that you’re aware of the risks 321
class Cow {
Catching exceptions using a try/catch (skateboarder) 322
class Bar { void moo() {
void go() { if (serverDown){

}
moo();
1 }
explode();
Flow control in try/catch blocks 326
}
int stuff() {
}
x.beep();

}
} calls risky method The finally block (no matter what happens, turn off the oven!) 327
Catching multiple exceptions (the order matters) 329
your code class with a
risky method Declaring an exception (just duck it) 335
Handle or declare law 337
Code Kitchen (making sounds) 339
Exercises and puzzles 348

12 A Very Graphic Story


Face it, you need to make GUIs. %VEN IF YOU BELIEVE THAT FOR THE REST OF YOUR
LIFE YOULL WRITE ONLY SERVER SIDE CODE SOONER OR LATER YOULL NEED TO WRITE TOOLS AND YOULL
WANT A GRAPHICAL INTERFACE 7ELL SPEND TWO CHAPTERS ON '5)S AND LEARN MORE LANGUAGE
FEATURES INCLUDING %VENT (ANDLING AND )NNER #LASSES 7ELL PUT A BUTTON ON THE SCREEN
class MyOuter { WELL PAINT ON THE SCREEN WELL DISPLAY A JPEG IMAGE AND WELL EVEN DO SOME ANIMATION

class MyInner {
void go() { Your first GUI 355
} Getting a user event 357
}
Implement a listener interface 358
}
Getting a button’s ActionEvent 360
Putting graphics on a GUI 363
The outer and inner objects
are now intimately linked. Fun with paintComponent() 365
oute
r

The Graphics2D object 366


Putting more than one button on a screen 370
jects on the
These two aobspecial bond. The inner
Inner classes to the rescue (make your listener an inner class) 376
heap have use the outer’s
inner can (and vice-versa). Animation (move it, paint it, move it, paint it, move it, paint it...) 382
variables Code Kitchen (painting graphics with the beat of the music) 386
Exercises and puzzles 394

xv
13 Work on your Swing
Swing is easy. 5NLESS YOU ACTUALLY CARE WHERE EVERYTHING GOES 3WING CODE LOOKS
EASY BUT THEN COMPILE IT RUN IT LOOK AT IT AND THINK hHEY THATS NOT SUPPOSED TO GO THEREv
4HE THING THAT MAKES IT EASY TO CODE IS THE THING THAT MAKES IT HARD TO CONTROLˆTHE ,AYOUT
-ANAGER "UT WITH A LITTLE WORK YOU CAN GET LAYOUT MANAGERS TO SUBMIT TO YOUR WILL )N
THIS CHAPTER WELL WORK ON OUR 3WING AND LEARN MORE ABOUT WIDGETS

Swing Components 400

Components in Layout Managers (they control size and placement) 401


the east and Three Layout Managers (border, flow, box) 403
west get theirth. BorderLayout (cares about five regions) 404
preferred wid
FlowLayout (cares about the order and preferred size) 408
Things in the BoxLayout (like flow, but can stack components vertically) 411
north and The center gets JTextField (for single-line user input) 413
south get their whatever’s left. JTextArea (for multi-line, scrolling text) 414
preferred height.
JCheckBox (is it selected?) 416
JList (a scrollable, selectable list) 417
Code Kitchen (The Big One - building the BeatBox chat client) 418
Exercises and puzzles 424

14 Saving Objects
Objects can be flattened and inflated. /BJECTS HAVE STATE AND BEHAVIOR
"EHAVIOR LIVES IN THE CLASS BUT STATE LIVES WITHIN EACH INDIVIDUAL OBJECT )F YOUR PROGRAM
NEEDS TO SAVE STATE YOU CAN DO IT THE HARD WAY INTERROGATING EACH OBJECT PAINSTAKINGLY
WRITING THE VALUE OF EACH INSTANCE VARIABLE /R YOU CAN DO IT THE EASY // WAYˆYOU SIMPLY
FREEZE DRY THE OBJECT SERIALIZE IT AND RECONSTITUTE DESERIALIZE IT TO GET IT BACK

serialized Saving object state 431


Writing a serialized object to a file 432
Java input and output streams (connections and chains) 433
Object serialization 434
ions?
Any quest Implementing the Serializable interface
Using transient variables
437
439
deserialized Deserializing an object 441
Writing to a text file 447
java.io.File 452
Reading from a text file 454
Splitting a String into tokens with split() 458
CodeKitchen 462
Exercises and puzzles 466
xvi
15
Make a Connection
Connect with the outside world. )TS EASY !LL THE LOW LEVEL NETWORKING
DETAILS ARE TAKEN CARE OF BY CLASSES IN THE JAVANET LIBRARY /NE OF *AVAS BEST FEATURES IS
THAT SENDING AND RECEIVING DATA OVER A NETWORK IS REALLY JUST )/ WITH A SLIGHTLY DIFFERENT
CONNECTION STREAM AT THE END OF THE CHAIN )N THIS CHAPTER WELL MAKE CLIENT SOCKETS 7ELL
MAKE SERVER SOCKETS 7ELL MAKE CLIENTS AND SERVERS "EFORE THE CHAPTERS DONE YOULL HAVE A
FULLY FUNCTIONAL MULTITHREADED CHAT CLIENT $ID WE JUST SAY MULTITHREADED
Socket c
to port 5o0nnection
on the serv 00 Chat program overview 473
196.164.1.10er at Connecting, sending, and receiving 474
3
Network sockets 475
TCP ports 476
Reading data from a socket (using BufferedReader) 478
Writing data to a socket (using PrintWriter) 479
Client Server
nnection Writing the Daily Advice Client program 480
Socket ocothe client Writing a simple server 483
back t 64.1.100,
at 196.1242 Daily Advice Server code 484
port 4 Writing a chat client 486
Multiple call stacks 490
Launching a new thread (make it, start it) 492
The Runnable interface (the thread’s job) 494
Three states of a new Thread object (new, runnable, running) 495
The runnable-running loop 496
Thread scheduler (it’s his decision, not yours) 497
Putting a thread to sleep 501
Making and starting two threads 503
Concurrency issues: can this couple be saved? 505
The Ryan and Monica concurrency problem, in code 506
Locking to make things atomic 510
Every object has a lock 511
The dreaded “Lost Update” problem 512
Synchronized methods (using a lock) 514
Deadlock! 516
Multithreaded ChatClient code 518
Ready-bake SimpleChatServer 520
Exercises and puzzles 524

xvii
16 Data Structures
Sorting is a snap in Java. 9OU HAVE ALL THE TOOLS FOR COLLECTING AND MANIPULATING
YOUR DATA WITHOUT HAVING TO WRITE YOUR OWN SORT ALGORITHMS 4HE *AVA #OLLECTIONS
&RAMEWORK HAS A DATA STRUCTURE THAT SHOULD WORK FOR VIRTUALLY ANYTHING YOULL EVER NEED
TO DO 7ANT TO KEEP A LIST THAT YOU CAN EASILY KEEP ADDING TO 7ANT TO FIND SOMETHING BY
NAME 7ANT TO CREATE A LIST THAT AUTOMATICALLY TAKES OUT ALL THE DUPLICATES 3ORT YOUR CO
WORKERS BY THE NUMBER OF TIMES THEYVE STABBED YOU IN THE BACK

Collections 533
Sorting an ArrayList with Collections.sort() 534
List 0 1 2 3 Generics and type-safety 540
Sorting things that implement the Comparable interface 547
Sorting things with a custom Comparator 552
The collection API—lists, sets, and maps 557
Set Avoiding duplicates with HashSet 559
Overriding hashCode() and equals() 560
HashMap 567
Using wildcards for polymorphism 574
Map “Ball”
“Ball1” “Fish”
“Ball2” “Fish”“Car”
“Car”
Exercises and puzzles 576

17 Release Your Code


It’s time to let go. 9OU WROTE YOUR CODE 9OU TESTED YOUR CODE 9OU REFINED YOUR CODE
9OU TOLD EVERYONE YOU KNOW THAT IF YOU NEVER SAW A LINE OF CODE AGAIN THATD BE FINE "UT IN
THE END YOUVE CREATED A WORK OF ART 4HE THING ACTUALLY RUNS "UT NOW WHAT )N THESE FINAL
TWO CHAPTERS WELL EXPLORE HOW TO ORGANIZE PACKAGE AND DEPLOY YOUR *AVA CODE 7ELL LOOK
AT LOCAL SEMI LOCAL AND REMOTE DEPLOYMENT OPTIONS INCLUDING EXECUTABLE JARS *AVA 7EB
3TART 2-) AND 3ERVLETS 2ELAX 3OME OF THE COOLEST THINGS IN *AVA ARE EASIER THAN YOU THINK
classes

Deployment options 582


com
Keep your source code and class files separate 584
101101

foo
10 110 1
0 11 0
Making an executable JAR (Java ARchives) 585
MyApp.jar 001 10
001 01

Running an executable JAR 586


MyApp.class
Put your classes in a package! 587
Packages must have a matching directory structure 589
Web Server Compiling and running with packages 590
JWS
Lorper
iure
Compiling with -d 591
eugue
tat vero
conse
euguero- Making an executable JAR (with packages) 592
MyApp.jar
MyApp.jnlp MyApp.jar
Java Web Start (JWS) for deployment from the web 597
How to make and deploy a JWS application 600
Exercises and puzzles 601

xviii
18
Distributed Computing
Being remote doesn’t have to be a bad thing. 3URE THINGS ARE EASIER
WHEN ALL THE PARTS OF YOUR APPLICATION ARE IN ONE PLACE IN ONE HEAP WITH ONE *6- TO RULE
THEM ALL "UT THATS NOT ALWAYS POSSIBLE /R DESIRABLE 7HAT IF YOUR APPLICATION HANDLES
POWERFUL COMPUTATIONS 7HAT IF YOUR APP NEEDS DATA FROM A SECURE DATABASE )N THIS
CHAPTER WELL LEARN TO USE *AVAS AMAZINGLY SIMPLE 2EMOTE -ETHOD )NVOCATION 2-) 7ELL
ALSO TAKE A QUICK PEEK AT 3ERVLETS %NTERPRISE *AVA "EANS %*" AND *INI

Client Server Java Remote Method Invocation (RMI), hands-on, very detailed 614
Servlets (a quick look) 625
RMI STUB RMI SKELETON Enterprise JavaBeans (EJB), a very quick look 631
Jini, the best trick of all 632
Se e
r

C li
ent helper rvice help Se
rvice objec
t

C li
Building the really cool universal service browser 636
ent object
The End 648

A
Appendix A
The final Code Kitchen project. !LL THE CODE FOR THE FULL CLIENT SERVER CHAT
BEAT BOX 9OUR CHANCE TO BE A ROCK STAR

BeatBoxFinal (client code) 650


MusicServer (server code) 657
DANCE BEAT


!NDY GROOVE
REVISED
#HRIS GROOVE
BEAT
.IGEL DANCE

B
Appendix B
The Top Ten Things that didn’t make it into the book. 7E CANT SEND
YOU OUT INTO THE WORLD JUST YET 7E HAVE A FEW MORE THINGS FOR YOU BUT THIS IS THE END OF THE
BOOK !ND THIS TIME WE REALLY MEAN IT
Top Ten List 660

i Index 677

xix
how to use thOIS book

Intro

-the bl>Yl\i,,~ ,~tiOf\:


DID \:h<'1 f.t Wl ,•• J••• \""~,.~-;~ boo\<r"
IY\ -this stl.bOf\I 'Wt. .lYlS'Ht:Y
'So, whY

xxi
how to use this book

Who is this book for?


If you can answer "yes" to all of these:
This is NOT a reference
E!)" Have you done some programming? book. Head First Java is a
book designed for 'earning,
® Do you want to learn Java? not an encyclopedia of
Java facts.
® Do you prefer stimulating dinner party
conversation to dry, dull, technical
lectures?
this book is for you.

Who should probably back away frotH this book?


If you can answer "yes" to anyone of these:

Is your programming background limited


to HTML only, with no scripting language
experience?
(If you've don e anything with looping, or if/then
logic , you 'll do fine with this book, but HTML
tagging alone might not be enough.)

® Are you a kick-butt C++ programmer


looking for a reference book?

® Are you afraid to try something different?


Would you rather have a root canal than I
mix stripes with plaid? Do you believe
than a technical book can't be serious If
there's a picture of a duck in the memory
management section?

this book is not for you .

xxii intr o
the intra

We k.,ow what you"re thittkhtg.


"How can this be a seriousJava programming book?"
"What's with all the graphics?"
"Can I actually learn it this way?"
"Do I smell pizza?"

A.,d we kt10w what your brain is thittkittg.


Your brain craves novelty. It's always searching, scanning, waiting for
something unusual. It was built that way, and it helps you stay alive.
Today, you're less likely to be a tiger snack. But your brain 's still
looking. You just never know.
So what does your brain do with all the routine, ordinary, normal
things you encounter? Everything it can to stop them from
interfering with the brain's realjotr-recording things that matter. It
doesn't bother saving the boring things; they never make it past the
"th is is obviously not important" filter.
How does your brain know what's important? Suppose you're out for
a day hike and a tigerjumps in front of you , what happens inside your
head?
Neurons fire. Emotions crank up. Chemicals suW
And that's how your brain knows ...
This must be Importantl Don't forget ItI
But imagine you're at home, or in a library. It's a safe, warm, tiger-free
zone. You're studying. Getting ready for an exam. Or trying to learn
some tough technical topic your boss thinks will take a week, ten days
at the most,
Just one problem. Your brain's trying to do you a big favor. It 's
trying to make sure that this obviou.sly non-important content
doesn't clutter up scarce resources. Resources that are better
spent storing the really bigthings. Like tigers. Like the danger of
fire. Like how you should never again snowboard in shorts.
And there's no simple way to tell your brain, "Hey brain, thank
you very much, but no matter how dull this book is. and how
little I'm registering on the emotional richter scale right now, I
really do want you to keep this stuff around. h

you are he re ~ xxiII


how to use this book

We tlUn1 of a "!lead Fll'St Java" reader as a learner.


-
So what does It take to learn something? First, you have to get It, then make sure
you don't forgetll It's not about pushing facts Into your head. Based on the
latest research In cognltJve science, neurobiology, and educatJonal psychology,
learning takes a lot more than text on a page . We know what turns your brain on.

Soma of the Head First learning principles:

Make It visual. Images are far more memorable than words RMI"'(loo~
~ite
alone, and make learning much more effective (Up to 89%
Improvement in recall and transfer studies) . It also makes
things more understandable. Put the words within
or near the graphics they relate to, rather than on the
bottom or on another page, and learners will be up to twice
as likely to solve problems related to the content.

Use a conversational and personalized style,In recent studies,


students performed up to 40% better on post-learning tests if the content spoke
It re4l1y SlJcks to ~ <III
Qbstl"<lct m~tkod. You directly to the reader, using a flrst-person, conversational style rather than
don't heve Q body. taking a formal tone.Tell stories instead of lecturing. Use casual language. Don't
take yourself too seriously. Which would you pay more attention to: a stimulating
o dinner party companion, or a lecture?
o

Get the learner to think more deeply. In other words, unless


you actively flex your neurons, nothing much happens in your head.
A reader has to be motivated, engaged, curious, and inspired to
solve problems, draw conclusions, and generate new knowledge.
And for that, you need challenges, exercises, and thought-
~0llll10 ; provoking questions, and actlvlties that involve both sides
of the brain, and multiple senses.
~,-.A 'l>o41'· ,~ t
tl4~i-
~ ;Ie. Oet-and kee,,-,he reader's attention. We've all
had the"' really want to learn this but I can't stay awake past
page one" experience. Your brain pays arrentlon to things that are out
of the ordinary, interesting, strange, eye-catching, unexpected. Learning a new,
tough, technical topic doesn't have to be boring. Your brain will learn much more qUicklyjf it's not.

Touch their emotlon8. We now know that your ability to remember something Is largely
dependent on Its emotional content. You remember what you care about. You remember when
you feel somethIng. No we're not talking heart-wrenching stories about a boy and hIs dog .
We're talking emotions like surprise, curiosity, fun, "what the ...T", and the feeling of "I Rulel"
that comes when you solve a puzzle, learn something everybody else thinks Is hard, or realize
you know something that ·"m more technical than thou' Bob from engineering doe$n't.

XXiv in t ra
the intro

Metacogtlitiott: thittkittg about thittki"Q.


If you really want to learn, and you want to learn more quickly and more deeply,
pay attention to how you pay attention. Think about how you think, Learn how
you learn.
Most of us did not take courses on metacognition or learning theory when we were
growing up. We were expected to learn, but rarely taught to learn. o
o
But we assume that if you're holding this book, you want to learn Java. And you
probably don't want to spend a lot of time.
To get the most from this book, or any book or learning experience, take
responsibility for your brain. Your brain 00 thai content.
The trick is to get your brain to see the new material you're learning
as Really Important. Crucial to your well-being. As important as
a tiger. Otherwise, you're in for a constant battle, with your brain
doing its best to keep tile new content from sticking.

So Just how DO you get your brain to treat Java like It


was a hungry tiger?
There's the slow, tedious way, or the faster, more effective way. The
slow way is about sheer repetition. You obviously know that you are
able to learn and remember even the dullest of topics, if you keep pounding
on the same thing. With enough repetition, your brain says, "This doesn'tfeel
important to him, but he keeps looking at the same thing overand over and over, so
I suppose it must be."
The faster way is to do anything that increases brain activity, especially different types
of brain activity. The things on the previous page are a big part of the solution,
and they're all things that have been proven to help your brain work in your favor.
For example, studies show that putting words within the pictures they describe (as
opposed to somewhere else in the page, like a caption or in the body text) causes
your brain to try to makes sense of how the words and picture relate, and this
causes more neurons to fire. More neurons firing = more chances for your brain
to get that this is something worth paying attention to, and possibly recording.

A conversational style helps because people tend to pay more attention when they
perceive that they're in a conversation, since they're expected to follow along and
hold up their end. The amazing thing is, your brain doesn't necessarily care that
the "conversation" is between you and a book! On the other hand, if the writing
style is formal and dry, your brain perceives it the same way you experience being
lectured to while sitting in a roomful of passive attendees. No need to stay awake.
But pictures and conversational style are just the beginning.

you are here ~ xxv


how to use this book

Here"s what WE did:


We used pidures, because your brain is tuned for visuals, not text As fur as your
brain's concerned, a picture really ssworth 1024 words. And when text and pictures
work together, we embedded the text in the pictures because your brain works
more effectively when the text is wiihin the thing the text refers to, as opposed to in
a caption or buried in the text somewhere.
We used repetitUm, saying the same thing in different ways and with different media
types, and multiplesenses, to increase the chance that the content gets coded coded
into more than one area of your brain.
We used concepts and pictures in ~ways because your brain is tuned for
novelty, and we used pictures and ideas with at least SO'1M emf>tional content, because
your brain is tuned to pay attention to thebiochemlstry of emotions. That which
causes you to feel something is more likely to be remembered. even if that feeling is
nothing more than a little humor; SU1"f1rise, or interest.
We used a personalized, conversational style, because your brain is tuned to pay more
attention when it believes you 're in a conversation than if it thinks you're passively
listening to a presentation. Your brain does this even when you're reading.
We included more than 50 ~ , because your brain is tuned to learn and
remember more when you do things than when you readabout things. And we
made the exercises challenging-yet-do-able, because that's what most pet1J/.e prefer.
We used multiple learning styles, because you might prefer step-by-step procedures,
while someone else wants to understand the big picture first, while someone else
just wants to see a code example. But regardless of your own learning preference,
everyone benefits from seeing the same content represented in multiple ways.
We include content for both rides ofyour brain; because the more of your brain you
engage, the more likely you are to learn and remember, and the longer you can
stay focused. Since working one side of the brain often means giving the other side
a chance to rest, you can be more productive at learning for a longer period of
time.
And we included storie: and exercises that present J'TUWe than one point ofview,

~8\"Barlle"
because your brain is tuned to learn more deeply when it's forced to make
evaluations and judgements.
We included chaIknges, with exercises, and by asking qrustions that don't always have
a straight answer, because your brain is tuned to learn and remember when it has
to work at something (just as you can't get your body in shape by watching people
at the gym). But we did our best to make sure that when you're working hard, it's
on the right things: That you'renot spending one exITa denLfrile processing a hard-to-
understand example, or parsing difficult,jargon-Iaden, or extremely terse text.
We used an 80/20 approach. We assume that if you 're going for a PhD in java,
this won't be your only book. So we don't talk about everything. Just the stuff you'll
actually use.

xxvi Intra
the intra
Herels what YOU ca., do to be.,d your
brah1 i"to subltdssiot1.
So, we did our part. The rest is up to you . These tips are a
starting point; Listen to your brain and figure out what works
for you and what doesn't. Try new things.

lki. -this OUt dhd sf.itk 't


Oh yOlJ.'r l'"e+l'"id9tt"ak .I
. _ - - _ . _ - - - - - - - - - - -~ -----------------------------------------------------------
~ . Slow down. The more you understand,
the less you have to memorize.
Don't just 'read. Stop and think. When the
book asks you a question, don't just skip to
• Drink water. Lots of It.
Your brain works best in a nice bath of fluid.
Dehydration (which can happen before you
ever feel thirsty) decreases cognitive function.


the answer. Imagine that someone really is
asking the question. The more deeply you Talk about It. Out loud.
force your brain to think, the better chance Speaking activates a different part of
you have of learning and remembering. the brain. If you're trying to understand
something, or increase your chance of
Do the exercises. Write your own notes. remembering it later, say it out loud. Better
We put them in, but if we did them for you, still, try to explain it out loud to someone
that would be like having someone else else . You'll learn more quickly, and you might
do your workouts for you . And don't just uncover ideas you hadn't known were there
look at the exercises. Use a pencil. There's when you were reading about it.
plenty of evidence that physical activity
while learning can increase the learning. Listen to your brain.
Pay attention to whether your brain is getting
Read the "There are No Dumb Questions" overloaded. If you find yourself starting to ski m
That means all of them. They're not the surface or forget what you just read, it's
optional side-bars-they're part of the core time for a break. Once you go past a certain
contentl Sometimes the questions are more point, you won't learn faster by trying to shove
useful than the answers. more in, and you might even hurt the process.

Don't do all your reading In one place. • Feel somethlngl


Stand-up, stretch, move around . change Your brain needs to know that this mauers. Get
chairs, change rooms. It'll help your brain involved with the stories. Make up your 0\\>11
feel something, and keeps your learning from captions for the photos. Groaning over a bad
being too connected to a particular place. joke is still better than feeling nothing at all.

Make this the last thing you read before . . Type and run the code.
bed. Or at least the last challengIng thing. Type and run the code examples. Then you
Part of the learning (especially the transfer can experiment with changing and improving
to long-term memory) happens afleryou put the code (or breaking it, which is sometimes
the book down. Your brain needs time on the best way to figure alit what's really
its own , to do more processing. If you put in happening). For long examples or Ready-bake
something new during that processing-time, code, you can download the source files from
some of what you just learned will be lost. headfirstjava.corn

you are here. xxvII


how to use this book

What you heed for this book:


You do not need any other development tool. such as an Integrated
Development Environment (IDE). We strongly recommend that you not
use anything but a-basic text editor until you complete this book (and
especially not until after chapter 16). An IDE can protect you from some of
the details that really matter. so you're much bener off learning from the
command-line and then. once you really understand what's happening.
move to a tool that automates some of the process.

SmlNG UP JAVA - - - - - - - - - - - - - - - - - - ,
• If you don't already have a 1.5 orgreater Java 2 Standard Edition SDK (Software
Development Kit), you need it. If you're on Linux, Windows, or Solaris, you can gellt for free
from java.sun.com (Sun's websile forJava developers). It usually takes nomore than two clicks
from the main page togel to the J2SE downloads page . Get the latest non-beta version posted.
The SDK includes everything you need tocompile and run Java.
If you're running Mac OS X10.4. the Java SDK isalready installed. It's partof OS X, and you
don't have todo anything else. If you're on an earlier version of OS X. you have an earlier
version ofJava that will wor1< for95% of the code in this book.
Note: This book is based on Java 1.5, but forstunningly unclear mar1<eting reasons, shortly
before release, Sun renamed It Java 5, while still keeping "1 .5" asthe version number forthe
developer's kit So, if you see Java 1.5 orJava 5 orJava 5.0, or "Tiger" (version 5's original
code-name), they all mean the same thing. There was never a Java 3.0 or 4.Q--it jumped from
version 1.4 to5.0,bu1 you will still find places where it'scalled 1.5 instead of 5. Don'l ask.
(Oh, and just 10 make il more entertaining, Java 5 and the Mac OS X 10.4 were both given the
same code-name of"Tiger", and since OS X 10.4 is the version of the Mac OS you need to run
Java 5, vou'llhear people talk about "Tiger on TIger". II justmeans Java 5 on OS X 10.4).

• The SDK does not include the API documentatIon, and you need that! Go back tojava.sun.
com and get the J2SE APr documentation. You can also access the API docs online, without
downloading them, but thaI's apain. Trusl us, irs worth the download.

• You need a texteditor. Virtually any text editor will do (vi, emacs, pica), including the GUI ones
that come with most operating systems. Nolepad, Wordpad, TextEdlt, etc. allwork, aslong as
you make sure they don'l append a ".txt" on tothe end of your source code.

• Once you've downloaded and unpackedfzippedfwhatever (depends on which version and for
which OS). you need to add an entry toyour PATH environment variable that points tothe fbln
directory inside the main Java directory. For example, if the J2SDK puts a directory on your
drive called "j2sdk1.5,O', look inside that directory and you'lI find the "bin" directory where the
Java binaries (the tools) live. The bin directory is the one you need a PATH to, sothaI when you
type:
% javac
atthe command-line, your terminal will know how tofind the javac compiler.
Note: if you have trouble with you installation, we recommend you gotojavaranch.com, and join
the Java-Beginning forum! Actually, you should dothat whether you have trouble or not.
Nole: much of the code from this book Is available at wlckedlysmart.com

xxvlll intra
Discovering Diverse Content Through
Random Scribd Documents
"Joan Strokes a Sillabub or Twain."

If you would make a Lemon Sillabub (as advised


by Mrs. Charlotte Mason, "a Professed Housekeeper,
who from about 1740 had upwards of Thirty Years
experience in Families of the First Fashion") take "a
Pint of cream, a pint of white wine, the rind of two
lemons grated, and the juice. Sugar to the taste. Let
it stand some time; mill or whip it. Lay the froth on a
sieve; put the remainder into glasses. Lay on the
froth." Mr. Nahum must have had a fancy for Cookery
Books; there were dozens of them in his tower room.
Indeed, the next best thing to eating a good dish is
to read how it is made; and somehow the old
"cookbook" writers learned to write a most excellent
and appetising English. Here is another recipe from
Delightes for Ladies, of 1608—a dainty that would
eat uncommonly well with a sillabub:—"To make a
marchpane.—Take two poundes of almonds being
blanched, and dryed in a sieve over the fire, beate
them in a stone mortar, and when they bee small
mixe them with two pounde of sugar beeing finely
beaten, adding two or three spoonefuls of rosewater,
and that will keep your almonds from oiling: when
your paste is beaten fine, drive it thin with a rowling
pin, and so lay it on a bottom of wafers, then raise
up a little edge on the side, and so bake it, then yce
it with rosewater and sugar, then put it in the oven
again, and when you see your yce is risen up and
drie, then take it out of the oven and garnish it with
pretie conceipts, as birdes and beasts being cast out
of standing moldes. Sticke long comfits upright in it,
cast biskets and carrowaies in it, and so serve it;
guild it before you serve it: you may also print of this
marchpane paste in your molds for banqueting
dishes. And of this paste our comfit makers at this
day make their letters, knots, armes, escutcheons,
beasts, birds, and other fancies." Also pygmy castles
and suchlike, for dessert, which the guests would
demolish with sugar-plums.
"Good thou, save mee a piece of Marchpane, and as thou
lovest me, let the Porter let in Susan Grindstone and Nell...."
Romeo and Juliet

23. "The Sun arising."

"What other fire could be a better image of the


fire which is there, than the fire which is here? Or
what other earth than this, of the earth which is
there?" So said Plotinus, and "I know," said Blake,
"that this world is a world of imagination and vision.
I see everything I paint in this world, but everybody
does not see alike. To the eye of a miser a guinea is
far more beautiful than the sun, and a bag worn with
the use of money has more beautiful proportions
than a vine filled with grapes. The tree which moves
some to tears of joy is in the eyes of others only a
green thing which stands in the way.... Some scarce
see Nature at all. But to the eyes of the man of
imagination, Nature is Imagination itself. As a man is,
so he sees. As the eye is formed, such are its
powers. You certainly mistake, when you say that the
visions of fancy are not to be found in this world. To
me this world is all one continued vision." ... Indeed,
when Blake was a child, he saw on Peckham Rye a
tree, full, not of birds, but of angels; and his poems
show how marvellously clear were the eyes with
which he looked at the things of Nature.
In the year 1872, an old lady might have been
seen driving across the Rye in her silvery carriage;
and she came to where, under a flowering tree, sat a
small boy—the locks of hair upon his head like
sheaves of cowslips, his eyes like speedwells, and he
in very bright clothes. And he was a-laughing up into
the tree. She stopped her carriage and said to him
almost as if she were more angry than happy, "What
are you laughing at, child?" And he said, "At the
sparrows, ma'am." "Mere sparrows!" says she, "but
why?" "Because they were saying," says he, "here
comes across the Rye a blind old horse, a blind old
coachman, and a blind old woman." "But I am not
blind," says she. "Nor are they not 'mere sparrows',"
said the child. And at that the old lady was looking
out of her carriage at no child, but at a small bush, in
bud, of gorse.

24. "And Thank Him Then"

—as does Robert Herrick's child, in his "Grace":


Here a little child I stand,
Heaving up my either hand;
Cold as Paddocks though they be,
Here I lift them up to Thee,
For a Benizon to fall
On our meat, and on us all. Amen.

A paddock is a frog or a toad, it seems. To either


small cold hand there are four cold fingers and a
thumb; and in old times, says Halliwell, our ancestors
had distinct names for each of the five toes and for
each of the five fingers. The fingers were called
thumb, toucher, longman, leche-man, little-man:
leche-man being the ring-finger, because in that
"there is a sinew very tender and small that reaches
to the heart." In Essex they used to call them (and
still may)—Tom Thumbkin, Bess Bumpkin, Long
Linkin, Bill Wilkin, and Little Dick. In Scotland:
Thumbkin, Lickpot, Langman, Berrybarn and Pirlie
Winkie.
And here are some more from Dr. Courtenay
Dunn's Natural History of the Child—a book which is
graced with as handsome a frontispiece as ever I've
seen:
Thumb - Tommy Tomkins or Bill Milker.
Forefinger - Billy Wilkins " Tom Thumper.
Third finger - Long Larum " Long lazy.
Fourth finger - Betsy Bedlam " Cherry Bumper.
Little finger - Little Bob " Tippity, Tippity-Town-end.

Toes:
Big toe - Tom Barker or Toe Tipe.
Toe 2 - Long Rachel " Penny Wipe.
Toe 3 - Minnie Wilkin " Tommy Tistle.
Toe 4 - Milly Larkin " Billy Whistle.
Little toe - Little Dick " Tripping-go.

So (if you wish) you can secretly name not only


your fingers, toes, rooms, chairs and tables, etc., but
also the stars in their courses, the trees in your
orchard, and have your own privy countersign for the
flowers you like best. "Give a dog a bad name, and
hang him," says the old proverb. Give anything a
good name, and it is yours for ever. There is the tale
of the unhappy gardener in the Isle of Rumm who
without ill intention called a snapdragon an
antirrhinum. And there arose out of the hillside a
Monster named Zobj—but I haven't the space for the
rest. The gardener of course meant well; but when
he heard the Voice counting his last moments, not in
common English, but in what Wensleydale Knitters
still remember of the Norse—Yahn, Jyahn, Tether,
Mether, Mumph, Hither, Lither, Auver, Dauver, Die—
well, he died before he was due, so to speak.
While we are on this subject, here is a Face Rhyme:
Bo Peeper
Nose Dreeper
Chin Chopper
White Lopper
Red Rag
And Little Gap.

This is another:
Here sits the Lord Mayor:
Here sit his men;
Here sits the cockadoodle;
Here sits the hen;
Here sits the little chickens;
Here they run in;
Chinchopper, chinchopper, chinchopper chin.

The next three are foot rhymes, very soothing at


times to fractious babies. The first is common in
London, etc.:
This little pig went to market;
This little pig stayed at home;
This little pig had roast beef;
This little pig had the bone;
This little pig cried Wee-wee-wee-wee-wee!
All the way home.

The second comes from the Isle of Wight:


This gurt pig zays, I wants meat;
T'other one zays, Where'll ye hay et?
This one zays, In gramfer's barn;
T'other one zays, Week! Week! I can't get over the dreshel.

And this is from Scotland:


This ain biggit the baurn,
This ain stealt the corn,
This ain stood and saw,
This ain ran awa',
An' wee Pirlie Winkie paid for a'.

And last; here is a dance-babbie-on-knee (or


This-is-the-way) rhyme; also from Scotland:
The doggies gaed to the mill,
This way and that way;
They took a lick out o' this wife's poke
And they took a lick out o' that wife's poke,
And a loup in the lead, and a dip in the dam,
And gaed walloping, walloping, walloping, Hame.

And no doubt came to the conclusion expressed


in the sixth stanza of Robert Herrick's Ternary of
Littles, upon a Pipkin of Jelly sent to a Lady:
A little Saint best fits a little Shrine,
A little Prop best fits a little Vine,
As my small Cruse best fits my little Wine.

A little Seed best fits a little Soyle,


A little Trade best fits a little Toyle,
As my small Jarre best fits my little Oyle.

A little Bin best fits a little Bread,


A little Garland fits a little Head,
As my small stuffe best fits my little Shed.

A little Hearth best fits a little Fire,


A little Chappell fits a little Quire,
As my small Bell best fits my little Spire.

A little streame best fits a little Boat,


A little lead best fits a little Float,
As my small Pipe best fits my little note.

A little meat best fits a little bellie,


As sweetly, Lady, give me leave to tell ye,
This little Pipkin fits this little Jellie.

And the fact that this or any other poem is


printed at this end of the book instead of at the
other does not mean that I am any the less thankful
to have it or that Mr. Nahum left it out of his.

25. "I Sing of a Maiden."


Only the spelling of this lovely and ancient little
carol has been slightly changed.

29. "Sleep Stays Not, Though a Monarch Bids."


(line 11).

Why rather, sleep, liest thou in smoky cribs,


Upon uneasy pallets stretching thee,
And hushed with buzzing night-flies to thy slumber,
Than in the perfumed chambers of the great,
Under the canopies of costly state,
And lulled with sound of sweetest melody?
O thou dull god, why liest thou with the vile
In loathsome beds, and leavest the kingly couch
A watch-case or a common 'larum-bell?
Wilt thou upon the high and giddy mast
Seal up the ship-boy's eyes, and rock his brains
In cradle of the rude imperious surge,
And in the visitation of the winds,
Who take the ruffian billows by the top,
Curling their monstrous heads, and hanging them
With deafening clamour in the slippery clouds,
That, with the hurly, death itself awakes?
Canst thou, O partial sleep, give thy repose
To the wet sea-boy in an hour so rude;
And in the calmest and most stillest night,
With all appliances and means to boot,
Deny it to a king? Then happy low, lie down!
Uneasy lies the head that wears a crown.
Henry IV. Part ii.

30.
For many years I read this poem as if the accents
in the first line of each stanza fell on the first and
third word—the two "I's." It was stupid of me, for
clearly the accent should fall (lightly) on the second
syllable of the "remembers." Apart from the accents
or stresses in a line of verse, there is the rise and fall
of the voice, a kind of tune in the saying of it. If the
right tune is not caught, then the difference is as
much as if one sniffed a wallflower and it smelt like
African mimosa. And to me, as to hundreds of
thousands of Englishmen, this poem is as familiar,
long-endeared and refreshing as wallflower, Sweet
William, or Old Man. This is the second or third time
I have made remarks about the rhythm, lilt or tune
of a poem; and it won't be the last. May I be
forgiven, for as Chaucer wrote to his small son Louis
when he was sharing with him his love of astronomy:
"Soothly me seemeth betre to writen unto a child
twice a good sentence, then he forget it ones." As
for his elders, even thrice may be short commons.

"Those Flowers made of Light." (line 12)

Hold up a flower between eye and sun, or even


candle-flame, and it seems little but its own waxen
hue and colour. Moonlight is too pale; the petals
remain opaque. In the moon's light, indeed, blueness
is scarcely distinguishable from shadowiness; red
darkens but yellow pales, and the fairest flowers of
all wake in her beams—jasmine, convolvulus,
evening-primrose—as if they not only shared her
radiance but returned a glowwormlike fuminess of
their own.
Once, long before I came to Thrae, having
plucked for my mother a few convolvulus flowers, I
remember when I was just about to give them into
her hand I discovered that the beautiful cups of
delight had enwreathed themselves together, and
had returned as it were to the bud, never to reopen.
I was but a child, and this odd little disappointment
was so extreme that I burst out crying.

32.

See just above, No. 30: and for proof of the


curious obedience of words to any bidden rhythm it
is interesting to compare this poem with its next
neighbours. Mr. Frost's colt is called "a little Morgan,"
because he was of a famous breed of horses of that
name which are the pride of the State of Vermont.

35.
Only a single copy of the old play, Mundus et
Infans, from which this fragment is taken, is known
to be in existence. It was printed by Wynkyn de
Worde in 1522; and was written roundabout 1500.
The lines need a slow reading to get the run and
lilt of them: and even at that they jog and creak like
an old farm-cart. But the boy, Dalyaunce, if one
takes a little pains, will come gradually out of them
as clear to the eye as if you had met him in the
street to-day, on his way to "schole" for yet another
"docking."
Clothes, houses, customs, food a little, thoughts a
little, knowledge, too—all change as the years and
centuries go by, but Dalyaunce under a thousand
names lives on. It never occurred to me when I was
young to think that the children in Rome talked Latin
at their games, and that Solomon and Caesar,
Prester John and the Grand Khan knew in their
young days what it means to be homesick and none
too easy to sit down. Yet there are knucklebones and
dolls in London that the infant subjects of the
Pharaohs played with, and at Stratford Grammar
School, for all to see, is Shakespeare's school desk.
As for Dalyaunce, "dockings" are not nowadays so
harsh as once they were.
In proof of this, there is a passage from a book,
telling of his own life as a small boy, written by
Guibert de Nogent. He is speaking of his childhood,
about the year when William the Conqueror landed
at Hastings:
'So, after a few of the evening hours had been
passed in that study, during which I had been beaten
even beyond my deserts, I came and sat at my
mother's knees. She, according to her wont, asked
whether I had been beaten that day; and I, unwilling
to betray my master, denied it; whereupon, whether
I would or no, she threw back my inner garment
(such as men call shirt), and found my little ribs
black with the strokes of the osier, and rising
everywhere into weals. Then, grieving in her inmost
bowels at this punishment so excessive for my
tender years, troubled and boiling with anger, and
with brimming eyes, she cried, "Never now shalt
thou become a clerk, nor shalt thou be thus tortured
again to learn thy letters!" Whereupon, gazing upon
her with all the seriousness that I could call to my
face, I replied, "Nay, even though I should die under
the rod, I will not desist from learning my letters and
becoming a clerk!"'
Still, there were more merciful schoolmasters
than Guibert de Nogent's, even in days harsh as his;
as this further extract from Mr. G. G. Coulton's
enticing Medieval Garner shows:
'One day, when a certain Abbot, much reputed for
his piety, spake with Anselm concerning divers points
of Monastic Religion, and conversed among other
things of the boys that were brought up in the
cloister, he added: "What, pray, can we do with
them? They are perverse and incorrigible; day and
night we cease not to chastise them, yet they grow
daily worse and worse."
Whereat Anselm marvelled, and said, "Ye cease
not to beat them? And when they are grown to
manhood, of what sort are they then?" "They are
dull and brutish," said the other.
Then said Anselm, "With what good profit do ye
expend your substance in nurturing human beings till
they become brute beasts?... But I prithee tell me,
for God's sake, wherefore ye are so set against
them? Are they not human, sharing in the same
nature as yourselves? Would ye wish to be so
handled as ye handle them? Ye will say, 'Yes, if we
were as they are.' So be it, then; yet is there no way
but that of stripes and scourges for shaping them to
good? Did ye ever see a goldsmith shape his gold or
silver plate into a fair image by blows alone? I trow
not. What then? That he may give the plate its
proper shape, he will first press it gently and tap it
with his tools; then again he will more softly raise it
with discreet pressure from below, and caress it into
shape. So ye also, if ye would see your boys adorned
with fair manners, ye should not only beat them
down with stripes, but also raise their spirits and
support them with fatherly kindness and pity'...."
There was an old woodcut, hanging on Mr.
Nahum's wall in his tower room, showing a boy in
the middle ages being whipped in a kind of machine
(something like a roasting-jack), and a schoolmaster
standing by, nicely smiling, in a gown. When
Coleridge was a bluecoat boy at Christ's Hospital with
Charles Lamb, he seems to have had a headmaster
of this kind: "'Boy!' I remember Bowyer saying to me
once when I was crying the first day after my return
after the holidays,—'Boy! the school is your father!
Boy! the school is your mother! Boy! the school is
your brother! the school is your sister! the school is
your first cousin, and your second cousin, and all the
rest of your relations! Let's have no more crying.' ...
"Mrs. Bowyer was no comforter, either. Val. Le
Grice and I were once going to be flogged for some
domestic misdeed, and Bowyer was thundering away
at us, by way of prologue, when Mrs. B. looked in
and said, 'Flog them soundly, sir, I beg!' This saved
us. Bowyer was so nettled at the interruption that he
growled out, 'Away, woman, away!' and we were let
off."
Coleridge tells of yet another schoolmaster,
whose name, like Bowyer and birch, also began with
a B.: "Busby was the father of the English public
school system. He was headmaster of Westminster
through the reign of Charles I., the Civil War, the
Protectorate, the reign of Charles II., and the
Revolution of 1688. Under him Westminster became
the first school in the kingdom. When Charles II.
visited the school, Busby stalked before the King with
his hat upon his head, whilst his most sacred majesty
meekly followed him. In private Busby explained that
his conduct was due to the fact that he could not
allow, for discipline's sake, the boys to imagine there
could be a greater man than himself alive." Quite
rightly, of course.
There is, too, the story of the little Lion that went
to school to the Bear. Being, though of royal blood, a
good deal of a dunce, Master Lion bore many sound
cuffings from Dr. Bruin on the road to learning, and
found it hot and dusty. After such administrations, he
would sometimes sit in the sun under a window,
learning his task and brooding on a day when he
would return to the school and revenge himself upon
the Doctor for having treated him so sore. But
Master Lion was all this time growing up, and so
many were the cares of State when he had left his
books and become a Prince and Heir Apparent, that
for a time he had no thought for his old school.
Being, however, in the Royal Gardens one sunny
morning, and seeing bees busy about their hive, he
remembered an old saying on the sweetness of
knowledge and wisdom, and this once more
reminded him of his old Master. Bidding his servants
sling upon a rod half a dozen of the hives, he set out
to visit Dr. Bruin. The hives were taken into his study,
and the bees, being unused to flitting within walls
out of the sunshine, angrily sang and droned about
the head of the old schoolmaster as he sat at his
desk. Their stings were of little account against his
thick hide, but their molestation was a fret, and he
presently cried aloud, "Would that the Prince had
kept his gifts to himself!" The Prince, who was
standing outside the door, listening and smiling to
himself, thereupon cried out: "Ah! Dr. Bruin, when I
was under your charge, you often heavily smit and
cuffed me with those long-clawed paws of yours.
Now I am older, and have learned how sweet and
worthy is the knowledge they instilled. This too will
be your experience. My bees may fret and buzz and
sting a little now, but you will think of me more
kindly when you shall be tasting their rich honey in
the Winter that is soon upon us." And Dr. Bruin,
peering out at the Prince from amid the cloud of the
bees, when he heard him thus call Tit for Tat, he
couldn't help but laugh.
And last—to return to Coleridge once more, who,
in the bad old days, so far as food goes, never "had
a belly full" at Christ's Hospital, and whose appetite
was only "damped, never satisfied,"—here is one of
his earliest letters (to his elder brother George),
which may have an (indirect) reference to Dr.
Bowyer's birch:
Dear Brother,—You will excuse me for reminding you that, as
our holidays commence next week, and I shall go out a good
deal, a good pair of breeches will be no inconsiderable accession
to my appearance. For though my present pair are excellent for
the purpose of drawing mathematical figures on them, and
though a walking thought, sonnet or epigram would appear in
them in very splendid type, yet they are not altogether so well
adapted for a female eye—not to mention that I should have
the charge of vanity brought against me for wearing a looking-
glass. I hope you have got rid of your cold—and I am
Your affectionate brother,
Samuel Taylor Coleridge

40.

This too should go to the lilt of its music, as then


the accents would come clearly. I think, in the
reading of it, there should be four stressed syllables
to the first, second and fifth lines in each stanza: "
Whâr hae ye bêen a' day, mŷ boy Tâmmy"; and "The
wêe thing gie's her hând, and says, There, gâng and
ask my Mâmmy." A line of verse like this resembles a
piece of elastic; if you leave it very slack you will get
no music out of it at all; stretch it a little too far, it
snaps.

41. "Rosy Apple, Lemon, or Pear."

This little jingle and Nos. 15, 16, 68, 75, etc., are
Singing Game Rhymes, of which scores have been
collected from the mouths of children near and far
from all over the Kingdom, and are now to be found
in print in Lady Gomme's two stout engrossing
volumes entitled Traditional Games. In these more
than seven hundred games are described, including
Rakes and Roans, Rockety Row, Sally Go Round the
Moon, Shuttlefeather, Spannims, Tods and Lambs,
Whigmeleerie, Allicomgreenaie, Bob-Cherry, Oranges
and Lemons, Cherry Pit, Thumble-bones, Lady on
Yandor Hill, Hechefragy, and Snail Creep.
A good many of these games have singing
rhymes to them. And the words of them vary in
different places. For the children in each of twenty or
more villages and towns may have their own
particular version of the same rhyme. As for the
original from which all such versions must once have
come—that may be centuries old. Like the Nursery
Rhymes, they were most of them in the world ages
before our great-great-great-grand-dams were
babies in their cradles. The noble game of Hop
Scotch, for instance, Lady Gomme tells us, was in
favour before the year I.
The most mysterious rhymes of all are said to
refer to ancient tribal customs, rites and ceremonies
—betrothals, harvest-homes, sowings, reapings, well-
blessings, dirges, divinations, battles, hunting, and
exorcisings—before even London was else than a few
hovels by its river's side. Rhymes such as these
having been passed on from age to age and from
one piping throat to another, have grown worn and
battered of course, and become queerly changed in
their words.
These from Mr. Nahum's book have their own
differences too. He seems to have liked best those
that make a picture, or sound uncommonly sweet
and so carry the fancy away. Any little fytte or jingle
or jargon of words that manages that is like a charm
or a talisman, and to make new ones is as hard as to
spin silk out of straw, or to turn beech leaves into
fairy money. When one thinks, too, of the myriad
young voices that generation after generation have
carolled these rhymes into the evening air, and now
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookfinal.com

You might also like