Head First Java 2nd Edition
Head First Java 2nd Edition
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
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
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 ALLTHE 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
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
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
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 NOWA BONUS LESSON ON THE TIPS FOR EXPLOITING INHERITANCE
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
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
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
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
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
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
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 CONTROLTHE ,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
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 // WAYYOU SIMPLY
FREEZE
DRY THE OBJECT SERIALIZE IT AND RECONSTITUTE DESERIALIZE IT TO GET IT BACK
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
foo
10 110 1
0 11 0
Making an executable JAR (Java ARchives) 585
MyApp.jar 001 10
001 01
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
!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
xxi
how to use this book
xxii intr o
the intra
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.
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
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.
~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.
•
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.
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
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
the intro
fecht-tical Editors
"Credit goes to all, but mistakes are the sale reponsibility of the
author...", Does anyone really believe that? See the two people on
this page? If you find technical problems, it's probably theirfaulL : )
Vjj\el'lt,i,,'s ·be
XXX intra
the in tra
t\'"~dit
Other people to b~e: $OfrIe ~ 0".... Java
!')I.~t .... t . . !vi~e ....s...
•41 O'Reilly:
Our biggest thanks to Mike Loukides at O'Reilly, for taking a
chance on this , and helping to shape the Head First concept into
a book (and series) . As this second edition goes to print there
are now five Head First books, and he's been with us all the way.
To Tim O'Reilly, for his willingness 10 launch into something
completely new and different. Thanks to the clever Kyle Hart for
figuring out how Head First fits into the world, and for launching
the series . Finally, to Edie Freedman for designing the H ead First
"emphasize the head" cover.
Our intrepid beta testers and reviewer team:
Our top honors and thanks go to the director of our javaranch
tech review team.johannes deJong. This is your fifth time around
with us on a Head First book, and we're thrilled you're still speaking
to us, Jeff Cumps is on his third book with us now and relentless
about finding areas where we needed to be more clear or correct.
Corey McGlone, you rock. And we think you give the clearest
explanations on javaranch, You'll probably notice we stole one or
two of them. Jason Menard saved our technical butts on more
than a few details, and Thomas Paul, as always, g-ave us expert
feedback and found the subtle Java issues the rest of us missed.
Jane Griscti has herJava chops (and knows a thing or two about
",-riting) and it was great to have her helping on the new edition
along with long-timejavarancher Barry Gaunt
:\farilyn de Queiroz gave us excellent help on both editions of the
book. Chris Jones,Jobn Nyquist, James Cubeta, Terri Cubeta,
and Ira Becker gave us a ton of help on the first edition.
Special thanks to a few of the Head First ers who've been helping
us from the beginning: Angelo Celeste, Mikalai Zaikin, and
Thomas Duff (twduff.corn). And thanks to our terrific agent, David
Roge1berg of StudioB (but seriously, what about the movie rights?)
MoreJava technical experts woo helped out on the first edition (in pseudo-random order):
Emiko Hori, Michael Taupitz, Mike Gallihugh, Manish Hatwalne,James Chegwidden,
Shweta Mathur, Mohamed Mazahim,John Paverd,Joseph Bih, Skulrat Patanavanich,
Sunil Palicha, Suddhasatwa Ghosh, Ramki Srinivasan, Alfred Raouf, Angelo Celeste,
Mikalai Zaikin,John Zoetebier,Jim Pleger, Barry Gaunt, and Mark Dielen.
"The large number of acknOWledgements is because we're testing the theory that everyone mentioned in
a book acknowledgement will bUy at least one copy, probably more , what with relatives and everyth ing. If
you'd like to be in the acknowledgement of our next book, and you have a large family, write to us.
xxxii intro
1 dive in A Quick Dip
Java takes you to new places. From its humble release to the public as the
(wimpy) version 1.02,Java seduced programmers with Its friendly syntax, object-orlented features,
memory management, and best of aU-the promise of portability. The lure of wrlte-once/run-
anywhere Isjust too strong. A devoted followlnq exploded, as programmers fought against bugs,
limitations, and, on yeah, the fact that it was dog slow. But that was ages ago. If you're just starting in
Java, you're lucky. Some of us had to walk five miles in the snow, uphill both ways (barefoot), to
get even the most trivial applet to work. But you, why,yov get to ride the sleeker, faster. much
more powerful Javaof today. .....".--..•.
Source Output
(code)
o
Create a source
COIMpiler Virtual
Machh'u
document. Use an
established protocol The compiler creates a
Run your document new document, coded
(In th is case, the Java
t hro ugh a source code into Java bytecode.
language). Your friends don't have
complier. The complier Any device capable of
checks for errors and running Java will be able a physical Java Machine,
won't let you compile to Interpret/translate but they all have a
until It's satisfied that this file into something virtual Java machine
everything will run It can run .The complied (implemented In
correctly. bytecode is platform- software) running inside
Independent. their electronic gadgets.
The virtual mach ine reads
and runs thebytecode.
2 chapter 1
dive In A Quick Dip
Source
Java.aWl.FrameQ>
o
o Output
(code)
Run the program by
starting the Java Virtual
Machine (JVM) with the
Party.doss file. The JVM
Type your source code. translates the bytecode
into something the
Saveas: Party.Java
underlying platform
Complied code: Party.dass understands, and runs
your program .
.,>
CII 1500
..
G)
.z:.
.5
1000
1ft
G)
500
1ft
1ft
lIlI 0
U
Java 1.02 Java 2 Java 5.0
250 classes 500 classes (wnloKs 1.2 .. t~) (wrsloKs 1.5 attd up)
Slow. A little faster. 2300dasses 3500 classes
Cute name and logo. More capable, friendlier. Much faster. More power, ~/e, to
Fun to use. Lots of Becoming very popultJr. Can (sometimes) run at develop with.
bugs. Applets are Better GUI code. native speeds. Serious, Besides adding more than a
the Big Thing. powerful. Comes in three thousand additional classes,
flavors: Micro Edition (J2ME), Java 5.0 (known as"Tiger"')
~
> Standard Edition (J2SE) and added major changes to ....
«l '-
~ Enterprise Edition (J2EE). the language itself, making 2
a.
'0 Becomes the langutlge of it easier (at least in theory) III
s:
~ chola for new enterprise for programmers and giving o
.s
01
(especially web-based) and
mobile applications.
it new features that were
popular in other languages.
:c ~
dive In A Quick Dip
while (x > 3) {
myDog.play();
}
-:.....-y {
readTheFila(UrnyFile.txt H ) ;
catch(FileNotFoundException ex) {
syetem.out.print(UFile not found.");
}
while (x > 3) {
myDog.play ( l ;
}
System.out.print(HDogl U + name);
String num ::; US";
fnt z = Integer.parselnt(num);
} locks li~ t"Icryl:.hi~ i" the { } is wlIat to do ~ the 'fry' did,,'t ~ ...
6 chapter 1
dive In A Quick Dip
you ar e here • 7
a Java class
Attafottty of aclass
When thejVM starts running, it looks for the class you give it at the com-
mand line. Then it starts looking for a specially-Written method that looks
exactly like:
public static void main (String() argsl (
II your code goes here
Next, theJVM runs everything between the curly braces { }of your main
method. EveryJava application has to have at least one class. and at least
one main method (not one main per class;just one main per applU:ation).
8 chapter 1
dive In A Quick Dip
-
MyFlrstApp.Java
~~
4t.. ,,\~ E)Run
~
t %j a va MyFirstApp
I Rule!
''''''
The World
MyFlratApp.clau
-
you are here ~ 9
statements, looping, branching
o do solttethi.,g
Statements: declaratlons, assignments.
method calls.etc,
int x ~ 3;
String name = ~Dirk";
x = x * 17;
System .ouc .print("x is " + x);
double d = Math.random();
II this is a comment
Syntax
Fun
e do solttethlttQ agal., and agal"
Loops: (or and while
while (x > 12)
x = )( - 1; .. Each statement must end in a
semicolon.
x=x+1;
for (int x ee 0; x < 10; x = x + 1) (
System.out.print("x is now + x); II
.. A single-line comment begins
with two forward slashes.
public void go ( ) (
II amazing code here
}
10 chapter 1
dive In A Quick Dip
A: ~ava is an object-oriented
(00) language. It's not Iikethe
System.out.println("Before the Loop");
while (x < 4) {
System.out.println("In the loop");
old days when you had steam-
System.out .prlntln("Value of x is " + x);
driven compliers and wrote one
monolithic source file with a pile x = x + 1;
of procedures. In chapter 2 you'll )
learn that a class Is a blueprint for System.out.println("This is after the loop");
an object, and that nearly every-
thing in Java Is an object.
POI~
classes,
, - - - - - - BULLD ----------,
Q: In my other language I can
• Statements end ina semicolon;
do a boolean test on an Integer.
In Java, can I say something like: • Code blocks are defined by apair of cu~y braces { }
int x .. 1;
• Declare an int variable with a name and a type: Intx;
while (J&:) (
• The assignment operator Is one equals sign =
A: No.A boolean and an
integer are not compatible types In
• The equals operator uses two equals signs ==
• Awhile loop runs everything within its block (defined by cu~y
Java. Since the result of a condi-
tional test must be a boolean, the
braces) as long as the conditional test Is true.
only varIable you can directly test • If the conditional test is fa1S8, the while loop code block won't
(without using a comparison op-
run, and execution will move down to the code Immediately
erator) Is a boolean. For example,
efterthe loop block.
you can say:
boolean isBot • true; • Put a boolean test Inside parentheses:
while (x = 4) ( }
while (llIHot) ( )
12 chapter 1
dive In A Quick Dip
Conditlo"al bra"chl"Q
Java, an if test is basically the same as the boolean test in a
'le loop - except instead of saying, ~UJhile there's still beer.,",
u ']] say, ~ifthere's still beer.,"
cLa s s I f Test (
public static void main (String[) args) {
int x = 3;
i f (x == 3)
System.out.println("x must be 3 H ) ;
, java If'rest
JI: must be 3
This runs no matter what
Glv~n the output:
The code above executes the line that prints "x must be 3" only
if the condition (x is equal to 3) is true. Regardless of whether % javaDooBee
it's true, though, the line that prints, "This runs no matter what" DooBeeDooBeeDo
~ill run. So depending on the value of x; either one statement
or two will print out. FJIIln th~ missing code:
But we can add an else to the condition, so that we can public class DooBee {
say something like, "Iftbere's still beer, keep coding, else
public static void main (StringO args) I
(otherwise) get more beer, and then continue on..."
intx=l;
::lass IfTest2 { while (x < _ _ }{
public static void main (String!) a rqs ) ( System.out. ("Doo");
int x = 2;
System.out. (MBee");
i f (x == 3)
System.out.println("x must be 3 H ) ; x = x + 1;
else ( }
, java If'l'est2
II is ~ 3
'1'hi1 runs no matter what
if (beerNum == 1) (
word - "bottle H ; II s i ng ul a r , as in ONE bo ttl e .
if (beerNum > 0) (
System.out .println(beerNum + " H + word + " of beer on che wall H ) ;
else (
System.out.println("No more bottles of beer on the wall H ) ;
) II end else
f II end while loop
) II end main method
II en~ class
14 chapter 1
dive In A Quick Dip
Bob's alarm clock rings at 8:30 Monday morning, just like every other weekday.
But Bob had a wild weekend, and reaches for the SNOOZE button.
And that's when the action starts, and the Java-enabled appliances
come to life.
First, the alarm clock sends a message to the coffee maker* "Hey, the geek's
sleeping in again , delay the coffee 12 minutes."
The coffee maker sends a message to the Motorola'>'
toaster, "Hold the toast, Bob's snoozing." ( -
The alarm clock then sends a message to Bob's
Nokia Navigator™ cell phone, "Call Bob's 9
o'clock and tell him we're running a little late."
Finally, the alarm clock sends a message to
Sam's (Sam is the dog) wireless collar, with the too-familiar signal that
means, "Get the paper, but don't expect a walk."
A few minutes later, the alarm goes off again . And again Bob
hits SNOOZE and the appliances start chattering. Finally,
the alarm rings a third time. But just as Bob reaches for the
sn ooze button, the clock sends the "jump and bark" signal to Sam's
collar. Shocked to full consciousness, Bob rises, grateful that hisJava
skills and a Little trip to Radio Sbackn< have enhanced the daily
routines of his life.
His toast is toasted.
His coffee steams.
His paper awaits.
Just another wonderful morning in TheJava--ErUlbled HOMSB.
You can have aJava~enabledhome. Stick with a sensible solution using Java,
Ethernet, andJini technology. Beware of imitations using other so-called "plug
and play" (which actually means "plug and play with it for the next three days
trying to get it to work") or "p ortable" platforms. Bob 's sister Berry Died one of
those others, and the results were, well, not very appealing, or safe.
Bit of a shame about her dog, too...
Could this story be true? Yes and no.While there are versions of Java running in de-
vices Including PDAs, cell phones (especially cell phones), pagers, rings, smart cards,
and more -you might not find a Java toaster or dog collar. But even jf you can't
find a Java-enabled version of your favorite gadget. you can stili run it as if it were a
Java device by controlling it through some other Interface (say, your laptop) that is
runnIng Java.This Is known as the Jini surrogate architecture. Y~ you con have that
geek dream home.
Try my new
phrase-a-matic and
you'll be a slick talker
just like the boss or
those guys in marketing.
16 ch apter 1
dive In A Quick Dip
i. The first step is to create three String arrays - the containers that will hold all the
-..ords . Declaring and creating an array is easy; here's a small one:
bch word is in quotes (as all good Strings must be) and separated by commas.
• For each of the three lists (arrays), the goal is to pick a random word, so we have
know how many words are in each list, If there are 14 words in a list, then we need
random number between 0 and 13 (Java arrays are zero-based, so the first word is at
ition 0, the second word position I, and the last word is position 13 in a 14-element what we need
here Is a •••
~') . Quite handily, ajava array is more than happy to tell you its length. You just
to ask. In the pets array, we'd say.
sat z =: pets . length ; pervasive targeted
z would now hold the value 3. process
, . We need three rand~m numbers. Java ships out-of-the-box, off-the-shelf, shrink- dynamic outside-
the-box tipplng-
pped, and core competent with a set of math methods (for now, think of them as
point
ctions). The random () method returns a random number between 0 and not-
'te-l , so we have to multiply it by the number of elements (the array length) in the
we're using. We have to force the result to be an integer (no decimals allowed!) so smart distributed
put in a cast (you'll get the details in chapter 4). It's the same as ifwe had any float- core competency
point number that we wanted to convert to an integer.
~t z • (int) 24.6;
24/1 empowered
mindshare
ow we get to build the phrase, by picking a word from each of the three lists,
smooshing them together (also inserting spaces between words). We use the ,,+n
30,000 fool win-win
rator, which concatenaus (we prefer the more technical' S1TU>OShes') the String objects
vision
ether. To get an element from an array, you give the array the index number (posi-
- n) of the thing you want using:
SUinq s '" pet. [0 l : / / s is now the String "FiOO" stx-slqrna net-
.... + " " + "is a dog"; / / • is now "Fido ill a dog" worked portal
5. Finally, we print the phrase to the command-line and... voila I Wen in marketing.
you are here ~ 17
the complier and the JVM
~
~e JVM battle over the question.
"Who's more lmportaJlU"
18 chapter 1
dive In A Quick Dip
you a re here ~ 19
exercise: Code Magnets
Code Magnets
A working Java program is all scrambled up
on the fridge. Can you rearrange the code
snippets to make a working Java program
that produces the output listed below?
Some of the curly braces fell on the floor if (
JC <: <: 1) (
and they were too small to pick up, so feel
free to add as many of those as you need! SYSt.,~
...... OUt .
JC .. ..
·Pr.lnt( "d" ) •
... - 1: '
i f (x == 2) {
class Shuftlel (
public static Void
main(String I) args) (
if pc. > 2) {
sygtem.out.print(~a~);
int x 3;
>r .. x-I;
System. Out .
. pr.l n t(,,_,,);
while (x > 0) {
~
'I., java Shufflel
a-b c-d
dive In A Quick Dip
B
public static void main(String [] args)
int x = 5;
while ( x > 1 )
x = x-I;
A
c
class Exerciselb {
~_ass Exerciselb {
int x • 5;
public static void main(String [) args)
while ( x > 1 )
int x '" Ii
x =x - Ii
while ( x < 10
if ( x < 3) (
if ( x > 3) (
System.out.println(~small x~);
systam.out.println(~big X")i
1 2 J
4 S f-
I
Ja~Cr~ss t. O
II ~ '---
8 - 9 10 ~
l..-
- - - - ~
18 9
Across I-
20 -
4. Command-line invoker
6. Back again?
L- '--
bL
21
8. Can't go both ways 1 \
9. Acronym for your laptop'S power
12. number variabletype
13. Acronym for a chip Down
14. SaysomethIng 1. Not an integer (or _ _ your boat)
22 chapter 1
dive In A Quick Dip
class Test {
public static void main (String [) args)
int x 0;
int y = 0;
while x < 5 )
00 11 21 32 42
lJ. 21 32 42 53
00 11 23 36 410
02 14 25 36 41
class PoolPu2zleOne {
public static void main(String (I arga) {
int x = OJ
P~l puzzle while ( ) {
Your job is to take code snippets from the
pool and place them into the blank
lines in the code. You may not use the
if ( x < 1 ) {
same snippet more than once,and
you won't need to use all the snip-
}
pets. Your goal is to make a cia 5S that
will compile and run and produce the
output listed. Don't be fooled-this one's
harder than it looks. if ( ) {
Output }
if ( x 1 ) {
%java PoolPuzzleOne
a noise }
if ) {
annoys
an oyster
}
System.out.println("");
24 chapter 1
dive In A Quick Dip
class Exercise1b {
public static void main(String I] arqs) {
int x = 1;
while ( x < 10 )
x=x+l;
if ( x > 3) {
A
System.out.println("big x")j
e Magnets:
__~ss Shuftlel {
~~lic static void main(String (J args) {
This will compile and run (no output), but
} without Q line added to the program, it
int x = 3; would run forever inan infinite 'while' loop!
....nile (x > 0) {
i f (x > 2) {
Systern.out.print(Ua")i
class Foo {
}
public static void main(String I] args) {
x = x - Ij int x = s;
System.out.print("-"); while ( x > 1 )
x =x - Ii
i f (x == 2) { B if ( x < 3) {
systern.out.print(Nb e")j
system.out.println("small x");
}
class Exerciss1b {
public static void main(String Uargs) {
int x = Sj
j a v a Shuffle!
while ( x > 1
a- b c - d
x .. x - 1;
C if ( x < 3)
System.out.println(~smallX·]i
fF IV
-P
•J s
'L 0 0 p
A V A
R
,,- -U
W .E- I
-B
D It 'V
IS
B R A IN C H A
'"- l
A 1: N T 0 A I
- - - It
Y L M R t
's y s ir
8
E M a u T P R r N T
L.
I
class PoolPuzzleOne {
public static void main(String (] args) {
-
T
A
A
-
I
-
L
-AB ~
M
~
int x == 0; 18
S T R I N G
9
D E C L A R e
while ( X • 4 ) { I R E T
f-- f--
~J
System.out. prlntf'Q'');
C
'---- - -H
if ( x < 1 ) { V 0
System.out.prirrt( "): 11 C 0 M M A N D
}
System.out .prlrrt(n"); class Tesc I
public scat:ic void main (Scr ing [ 1 args) (
if(X>l){ i n c l< ~ 0;
i n c y - 0;
wh i Ie ( x < 5 l (
System.out. prfnt(' oyster");
x =x + 2;
}
i f ( x == 1 ) { Syscern .ou c.print( x · -" • y .- "I;
x = x + 1;
System. out. prfnt('noysj;
}
if ( X • 1 ) {
"""slble output:
32 U 53
.I.f I Y < 5 )
II - X + 1,
UIy<3
:It - x-II
)
1. • Y. + 2.
26 ch apter 1
2 classes and objects
A Trip to Objectville
We’re going to
Objectville! We’re
leaving this dusty ol’
procedural town for good.
I’ll send you a postcard.
Chair Wars
(or How Objects Can Change Your Life)
the spec
O
NCE UPON A TIME IN A SOFTWARE SHOP TWO
PROGRAMMERS WERE GIVEN THE SAME SPEC AND TOLD TO
hBUILD ITv 4HE 2EALLY !NNOYING 0ROJECT -ANAGER
FORCED THE TWO CODERS TO COMPETE
BY PROMISING THAT WHOEVER DELIVERS
lRST GETS ONE OF THOSE COOL !ERON©
CHAIRS ALL THE 3ILICON 6ALLEY GUYS HAVE
,ARRY THE PROCEDURAL PROGRAMMER AND
"RAD THE // GUY BOTH KNEW THIS WOULD
BE A PIECE OF CAKE
,ARRY SITTING IN HIS CUBE THOUGHT TO
HIMSELF h7HAT ARE THE THINGS THIS PROGRAM
HAS TO DO 7HAT PROCEDURES DO WE NEEDv
!ND HE ANSWERED HIMSELF hROTATE AND
PLAY3OUNDv 3O OFF HE WENT TO BUILD THE
PROCEDURES !FTER ALL WHAT IS A PROGRAM IF NOT
A PILE OF PROCEDURES
"RAD MEANWHILE KICKED BACK AT THE CAFE
AND THOUGHT TO HIMSELF h7HAT ARE THE THINGS
IN THIS PROGRAM WHO ARE THE KEY PLAYERSv (E
lRST THOUGHT OF 4HE 3HAPES /F COURSE THERE
WERE OTHER OBJECTS HE THOUGHT OF LIKE THE 5SER THE 3OUND
AND THE #LICKING EVENT "UT HE ALREADY HAD A LIBRARY OF CODE
FOR THOSE PIECES SO HE FOCUSED ON BUILDING 3HAPES 2EAD
ON TO SEE HOW "RAD AND ,ARRY BUILT THEIR PROGRAMS AND the chair
FOR THE ANSWER TO YOUR BURNING QUESTION h3O WHO GOT THE
!ERONv