100% found this document useful (2 votes)
5K views690 pages

Head First Java 2nd Edition

Uploaded by

weipanda
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 (2 votes)
5K views690 pages

Head First Java 2nd Edition

Uploaded by

weipanda
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/ 690

: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. (EREYOUARETRYINGTOLEARNSOMETHING WHILEHEREYOURBRAIN
ISDOINGYOUAFAVORBYMAKINGSURETHELEARNINGDOESNTSTICK9OURBRAINSTHINKING h"ETTER
LEAVEROOMFORMOREIMPORTANTTHINGS LIKEWHICHWILDANIMALSTOAVOIDANDWHETHERNAKED
SNOWBOARDINGISABADIDEAv3OHOWDOYOUTRICKYOURBRAININTOTHINKINGTHATYOURLIFE
DEPENDSONKNOWING*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. &ROMITSHUMBLERELEASETOTHEPUBLICASTHE
WIMPY VERSION *AVASEDUCEDPROGRAMMERSWITHITSFRIENDLYSYNTAX OBJECT ORIENTED
FEATURES MEMORYMANAGEMENT ANDBESTOFALLˆTHEPROMISEOFPORTABILITY7ELLTAKEAQUICK
DIPANDWRITESOMECODE COMPILEIT ANDRUNIT7ERETALKINGSYNTAX LOOPS BRANCHING ANDWHAT
MAKES*AVASOCOOL$IVEIN

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 WEPUTALLOFOURCODE
INTHEMAIN METHOD4HATSNOTEXACTLYOBJECT ORIENTED3ONOWWEVEGOTTOLEAVETHAT
PROCEDURALWORLDBEHINDANDSTARTMAKINGSOMEOBJECTSOFOUROWN7ELLLOOKATWHAT
MAKESOBJECT ORIENTED// DEVELOPMENTIN*AVASOMUCHFUN7ELLLOOKATTHEDIFFERENCE
BETWEENACLASSANDANOBJECT7ELLLOOKATHOWOBJECTSCANIMPROVEYOURLIFE

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.
4HERESGOTTABEMORETOLIFETHANINTEGERS 3TRINGS ANDARRAYS7HATIFYOUHAVEA0ET/WNER
OBJECTWITHA$OGINSTANCEVARIABLE/RA#ARWITHAN%NGINE)NTHISCHAPTERWELLUNWRAP
THEMYSTERIESOF*AVATYPESANDLOOKATWHATYOUCANDECLAREASAVARIABLE WHATYOUCANPUT
INAVARIABLE ANDWHATYOUCANDOWITHAVARIABLE!NDWELLFINALLYSEEWHATLIFEISTRULYLIKE
ONTHEGARBAGE COLLECTIBLEHEAP

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. 7EKNOWTHATOBJECTS
HAVESTATEANDBEHAVIOR REPRESENTEDBYINSTANCEVARIABLESANDMETHODS.OWWELLLOOK
ATHOWSTATEANDBEHAVIORARERELATED!NOBJECTSBEHAVIORUSESANOBJECTSUNIQUESTATE
)NOTHERWORDS METHODSUSEINSTANCEVARIABLEVALUES,IKE hIFDOGWEIGHTISLESSTHAN
POUNDS MAKEYIPPYSOUND ELSEv,ETSGOCHANGESOMESTATE

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. 9OUDABBLEDWITHVARIABLES
PLAYEDWITHAFEWOBJECTS ANDWROTEALITTLECODE"UTYOUNEEDMORETOOLS,IKE
OPERATORS!NDLOOPS-IGHTBEUSEFULTOGENERATERANDOMNUMBERS!NDTURN
A3TRINGINTOANINT YEAH THATWOULDBECOOL!NDWHYDONTWELEARNITALLBYBUILDING
SOMETHINGREAL TOSEEWHATITSLIKETOWRITEANDTEST APROGRAMFROMSCRATCH-AYBEA
he GAME LIKE3INKA$OT#OMSIMILARTO"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. 9OUDONTHAVETO
REINVENTTHEWHEELIFYOUKNOWHOWTOFINDWHATYOUNEEDFROMTHE*AVALIBRARY COMMONLY
KNOWNASTHE*AVA!0)9OUVEGOTBETTERTHINGSTODO)FYOUREGOINGTOWRITECODE YOU
MIGHTASWELLWRITEONLYTHEPARTSTHATARECUSTOMFORYOURAPPLICATION4HECORE*AVALIBRARY
ISAGIANTPILEOFCLASSESJUSTWAITINGFORYOUTOUSELIKEBUILDINGBLOCKS

Analying the bug in the Simple Dot Com Game 126


h'OODTOKNOWTHERESAN!RRAY,ISTIN ArrayList (taking advantage of the Java API) 132
THEJAVAUTILPACKAGE"UTBYMYSELF HOW Fixing the DotCom class code 138
WOULD)HAVElGUREDTHATOUTv
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. 7HATIFYOUCOULDWRITE
CODETHATSOMEONEELSECOULDEXTEND EASILY7HATIFYOUCOULDWRITECODETHATWASFLEXIBLE
FORTHOSEPESKYLAST MINUTESPECCHANGES7HENYOUGETONTHE0OLYMORPHISM0LAN YOULL
LEARNTHESTEPSTOBETTERCLASSDESIGN THETRICKSTOPOLYMORPHISM THEWAYSTOMAKE
FLEXIBLECODE ANDIFYOUACTNOWˆABONUSLESSONONTHETIPSFOREXPLOITINGINHERITANCE

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
2OSESARERE
D VIOLETSARE IS-A and HAS-A (bathtub girl) 177
3QUARE)3 ! BLUE
3HAPE THERE
VERSEISNTTRU What do you inherit from your superclass? 180
2OSESARERE E
D VIOLETSARE
"EER)3 !$RI DEAR What does inheritance really buy you? 182
NK BUTNOTA
LLDRINKSARE
/+ YOURTUR BEER Polymorphism (using a supertype reference to a subclass object) 183
N-AKEONE
WAY NESSOF THATSHOWS Rules for overriding (don’t touch those arguments and return types!) 190
THE)3 !RELA THEONE
BER IF8EX TE TIONSHIP!ND
NDS9 8)3 ! REMEM Method overloading (nothing more than method name re-use) 191
9MUSTMAK
ESENSE
Exercises and puzzles 192

8
Serious Polymorphism
Inheritance is just the beginning. 4OEXPLOITPOLYMORPHISM WENEED
INTERFACES7ENEEDTOGOBEYONDSIMPLEINHERITANCETOFLEXIBILITYYOUCANGETONLYBY
DESIGNINGANDCODINGTOINTERFACES7HATSANINTERFACE!ABSTRACTCLASS7HATSAN
ABSTRACTCLASS!CLASSTHATCANTBEINSTANTIATED7HATSTHATGOODFOR2EADTHECHAPTER

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. 9OUREINCHARGE9OUDECIDEWHENAND
HOWTOCONSTRUCTTHEM9OUDECIDEWHENTOABANDONTHEM4HE'ARBAGE#OLLECTORGC
RECLAIMSTHEMEMORY7ELLLOOKATHOWOBJECTSARECREATED WHERETHEYLIVE ANDHOWTO
KEEPORABANDONTHEMEFFICIENTLY4HATMEANSWELLTALKABOUTTHEHEAP THESTACK SCOPE
CONSTRUCTORS SUPERCONSTRUCTORS NULLREFERENCES ANDGCELIGIBILITY

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)HASMETHODSFORABSOLUTEVALUE ROUNDING MINMAX ETC
"UTWHATABOUTFORMATTING9OUMIGHTWANTNUMBERSTOPRINTEXACTLYTWODECIMALPOINTS
ORWITHCOMMASINALLTHERIGHTPLACES!NDYOUMIGHTWANTTOPRINTANDMANIPULATEDATES
all instances of TOO!NDWHATABOUTPARSINGA3TRINGINTOANUMBER/RTURNINGANUMBERINTOA3TRING
a class.
7ELLSTARTBYLEARNINGWHATITMEANSFORAVARIABLEORMETHODTOBESTATIC
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. 4HEFILEISNTTHERE4HESERVERISDOWN.OMATTERHOWGOODA
PROGRAMMERYOUARE YOUCANTCONTROLEVERYTHING7HENYOUWRITEARISKYMETHOD YOUNEED
CODETOHANDLETHEBADTHINGSTHATMIGHTHAPPEN"UTHOWDOYOUKNOWWHENAMETHODIS
RISKY7HEREDOYOUPUTTHECODETOHANDLETHEEXCEPTIONALSITUATION)NTHISCHAPTER WERE
GOINGTOBUILDA-)$)-USIC0LAYER THATUSESTHERISKY*AVA3OUND!0) SOWEBETTERFINDOUT

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. %VENIFYOUBELIEVETHATFORTHERESTOFYOUR
LIFEYOULLWRITEONLYSERVER SIDECODE SOONERORLATERYOULLNEEDTOWRITETOOLS ANDYOULL
WANTAGRAPHICALINTERFACE7ELLSPENDTWOCHAPTERSON'5)S ANDLEARNMORELANGUAGE
FEATURESINCLUDING%VENT(ANDLINGAND)NNER#LASSES7ELLPUTABUTTONONTHESCREEN
class MyOuter { WELLPAINTONTHESCREEN WELLDISPLAYAJPEGIMAGE ANDWELLEVENDOSOMEANIMATION

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. 5NLESSYOUACTUALLYCAREWHEREEVERYTHINGGOES3WINGCODELOOKS
EASY BUTTHENCOMPILEIT RUNIT LOOKATITANDTHINK hHEY THATSNOTSUPPOSEDTOGOTHEREv
4HETHINGTHATMAKESITEASYTOCODEISTHETHINGTHATMAKESITHARDTOCONTROLˆTHE,AYOUT
-ANAGER"UTWITHALITTLEWORK YOUCANGETLAYOUTMANAGERSTOSUBMITTOYOURWILL)N
THISCHAPTER WELLWORKONOUR3WINGANDLEARNMOREABOUTWIDGETS

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. /BJECTSHAVESTATEANDBEHAVIOR
"EHAVIORLIVESINTHECLASS BUTSTATELIVESWITHINEACHINDIVIDUALOBJECT)FYOURPROGRAM
NEEDSTOSAVESTATE YOUCANDOITTHEHARDWAY INTERROGATINGEACHOBJECT PAINSTAKINGLY
WRITINGTHEVALUEOFEACHINSTANCEVARIABLE/R YOUCANDOITTHEEASY//WAYˆYOUSIMPLY
FREEZE DRYTHEOBJECTSERIALIZEIT ANDRECONSTITUTEDESERIALIZE ITTOGETITBACK

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. )TSEASY!LLTHELOW LEVELNETWORKING
DETAILSARETAKENCAREOFBYCLASSESINTHEJAVANETLIBRARY/NEOF*AVASBESTFEATURESIS
THATSENDINGANDRECEIVINGDATAOVERANETWORKISREALLYJUST)/WITHASLIGHTLYDIFFERENT
CONNECTIONSTREAMATTHEENDOFTHECHAIN)NTHISCHAPTERWELLMAKECLIENTSOCKETS7ELL
MAKESERVERSOCKETS7ELLMAKECLIENTSANDSERVERS"EFORETHECHAPTERSDONE YOULLHAVEA
FULLY FUNCTIONAL MULTITHREADEDCHATCLIENT$IDWEJUSTSAYMULTITHREADED
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. 9OUHAVEALLTHETOOLSFORCOLLECTINGANDMANIPULATING
YOURDATAWITHOUTHAVINGTOWRITEYOUROWNSORTALGORITHMS4HE*AVA#OLLECTIONS
&RAMEWORKHASADATASTRUCTURETHATSHOULDWORKFORVIRTUALLYANYTHINGYOULLEVERNEED
TODO7ANTTOKEEPALISTTHATYOUCANEASILYKEEPADDINGTO7ANTTOFINDSOMETHINGBY
NAME7ANTTOCREATEALISTTHATAUTOMATICALLYTAKESOUTALLTHEDUPLICATES3ORTYOURCO
WORKERSBYTHENUMBEROFTIMESTHEYVESTABBEDYOUINTHEBACK

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. 9OUWROTEYOURCODE9OUTESTEDYOURCODE9OUREFINEDYOURCODE
9OUTOLDEVERYONEYOUKNOWTHATIFYOUNEVERSAWALINEOFCODEAGAIN THATDBEFINE"UTIN
THEEND YOUVECREATEDAWORKOFART4HETHINGACTUALLYRUNS"UTNOWWHAT)NTHESEFINAL
TWOCHAPTERS WELLEXPLOREHOWTOORGANIZE PACKAGE ANDDEPLOYYOUR*AVACODE7ELLLOOK
ATLOCAL SEMI LOCAL ANDREMOTEDEPLOYMENTOPTIONSINCLUDINGEXECUTABLEJARS *AVA7EB
3TART 2-) AND3ERVLETS2ELAX3OMEOFTHECOOLESTTHINGSIN*AVAAREEASIERTHANYOUTHINK
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 THINGSAREEASIER
WHENALLTHEPARTSOFYOURAPPLICATIONAREINONEPLACE INONEHEAP WITHONE*6-TORULE
THEMALL"UTTHATSNOTALWAYSPOSSIBLE/RDESIRABLE7HATIFYOURAPPLICATIONHANDLES
POWERFULCOMPUTATIONS7HATIFYOURAPPNEEDSDATAFROMASECUREDATABASE)NTHIS
CHAPTER WELLLEARNTOUSE*AVASAMAZINGLYSIMPLE2EMOTE-ETHOD)NVOCATION2-) 7ELL
ALSOTAKEAQUICKPEEKAT3ERVLETS %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. !LLTHECODEFORTHEFULLCLIENT SERVERCHAT
BEATBOX9OURCHANCETOBEAROCKSTAR

BeatBoxFinal (client code) 650


MusicServer (server code) 657
DANCEBEAT

!NDYGROOVE
REVISED
#HRISGROOVE
BEAT
.IGELDANCE

B
Appendix B
The Top Ten Things that didn’t make it into the book. 7ECANTSEND
YOUOUTINTOTHEWORLDJUSTYET 7EHAVEAFEWMORETHINGSFORYOU BUTTHISISTHEENDOFTHE
BOOK!NDTHISTIMEWEREALLYMEANIT
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
the intro

Last.. tMinute thhtgs you need to know:


This is a learning experience, not a reference book. We deliberately
stripped out everything that might get in the way of lmrningwhatever it
is we're working on at that point in the book. And the first time through,
you need to begin at the beginning, because the book makes assumptions
about what you've already seen and Learned.

We use simple UML.-IIke diagrams. Dog


Ifwe'd used pure UML, you'd be seeing something that looks like Java , but
with syntax that's just plain 1UTfYflf;. So we use a simplified version ofUML size
that doesn't conflict with Java syntax. If you don't already know UML. you
won't have to worry about leamingJava and UML at the same time. barkQ
eatO
chaseCatQ
We don't worry about organizing and packaging your own
code until the end of the book.
In this book, you can get on with the business of learningJava , without
-
stressing over some of the organizational or administrative details of
deveLopingJava programs. You will, in the real world, need to know-and
use--these details, so we cover them in depth. But we save them for the end
of the book (chapter 17) . Relax while you ease intoJava, gently.

The end-of-chapter exercises are mandatory; puzzles are


optional. Answers for both are at the end of each chapter.
One thing you need to know about the puzzles-tmy 're puxxles. As in Logic
puzzles, brain teasers, crossword puzzles, etc. The exercises are here to help
}'ou practice what you've learned, and you should do them all. The puzzles
are a different story, and some of them are quite challenging in a puzzle
way. These puzzles are meant for pualets, and you probably already know if
you are one. If you're not sure, we suggest you give some of them a try, but
whatever happens, don't be discouraged if you can't solve a puzzle or if you
simply can't be bothered to take the time to work them out.

The 'Sharpen Your Pencil' exercises don't have answers.


Not printed in the book, anyway. For some of them, there is no right
answer, and for the others, part of the learning experience for the Sharpen
activities is for you to decide if and when your answers are right, (Some of
our suggested answers are available on wickedlysman.com)

The code examples are as lean as possible


It's frustrating to wade through 200 lines of code looking for the two lines
you need to understand. Most examples in this book are shown within the
smallest possible context, so that the part you're trying to learn is clear and
simple. So don't expect the code to be robust, or even complete. That's
Jour assignment for after you finish the book. The book examples are
written specifically for learning, and aren't always fully-functional.
you are here ~ xxix
tech editing: Jessica and Valentin

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

Valentin Valentin Creuaz has a Masters degree


in Information and Computer Science from
Jess works at Hewlett-Packard on the Self- the Swiss Federal Institute of Technology in
Healing Services Team. She has a Bachelor's Lausanne (EPFL). He has worked as a software
in Computer Engineering from Villanova engineer with SRI International (Menlo Park,
University, has her SCPJ 1.4 and SCWCD CA) and as a principal engineer in the Software
certifications, and is literally months away Engineering Laboratory of EPFL.
from receiving her Masters in Software Valentin is the co-founder and CTO of Condris
Engineering at Drexel University (whewl) Technologies, a company specializing in the
When she's not working, studying or development of software architecture solutions.
motoring in her MINI Cooper S,jess can His research and development interests
be found fighting her cat for yam as she include aspect-oriented technologies, design
completes her latest knitting or crochet and architectural patterns, web services, and
project (anybody want a hat?) She is software architecture. Besides taking care of
originally from Salt Lake City, Utah (no, his wife. gardening, reading. and doing some
she's not Mormon ... yes, you were too sport, Valentin moderates the SCBCD and
going to ask) and is currently living near SCDJWS forums atJavaranch.com . He holds
Philadelphia with her husband. Mendra, and the SCJP, SCjD, SCBCD, scwco, and SCD]WS
two cats: Chai and Sake. certifications. He has also bad the opporruniry
You can catch her moderating technical to serve as a co-author for Whizlabs SCBCD
forums acjavaranch.com. Exam Simulator.
(We're still in shock from seeing him in a tie.)

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?)

you are here ~ xxxi


" still more acknowledgements

Just whet1 you thought there wouldt1't be at1Y


tMore ackt1owledgetMet1ts*.

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 first edition puzzle team:


Dirk Schreckmann, Mary 'JavaCross Champion" Leners, Rodney J. Woodruff, Gavin Bong,
and Jason Menard. Javaranch is lucky to have you all helping out.

Other co-conspirators to thank:


Paul Wheaton, the javaranch Trail Boss for supporting thousands ofJava learners.
Solveig Haugland, mistress ofJ2EE and author of "Dating Design Patterns".
Authors Don Smith and Tom Negrino (backupbrain.com) , for helping us navigate the
tech book world.
Our Head First partners in crime, Eric Freeman and Beth Freeman (authors of Head First
Design Patterns) , for giving us the Bawls" to finish this on time.
Sherry Dorris, for the things that really matter.

Brave Early Adopters of the Head First series:


Joe Litton, Ross P. Goldberg, Dominic Da Silva, honestpuck, Danny Bromberg, Stephen
Lepp, Elton Hughes, Eric Christensen, Vulinh Nguyen, Mark Rau, Abdulhaf, Nathan
Oliphant, Michael Bradly, Alex Darrow, Michael Fischer, Sarah Nottingham, Tim Allen,
Bob Thomas, and Mike Bibby (the first).

"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

Breaking the Surface


Come on, the water's
great! We'll dive right in and
write some code, then compile and
run it. We're talking syntax, looping
and branching, and a look at what
makes J alia so cool. You'll be
coding in no time.

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. .....".--..•.

this is a new chapter 1


the way Java works

fhe Way Java Works


The goal Is to write one application (in this
example, an interactive party Invitation) and have
It work on whatever device your friends have.

source code (or Method Pany()


Oalo;l<'-O
the Interactive
1 invobspe-
party hwltaUon. ----.. clal #1 <Method
java.lang.Obf&dO>
4 rerum

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

What you'll do in Jav~


You'll type a source code file, compile It using the
Javac complier, then run the complied bytecode
on a .Java virtual machine.

java.awl·; Method Party()


r:.pon java.awtevenL·; oaload_O
:tass Party (
1Invokespedal #1 <Method
pc.;b!ic void bu~dlnvlte() ( Java,lang.ObjedO> PartY at Tim's1
Fl3me r=IlllW FtameO;
4 return
Labell =new LabellParty atTlm's1;
B tton b =new ButIoI'I('You ber) ; Method void bulidInviteO
Button C =te« Button("Shool me'):
onew #2 <Class java.aWl.Frame>
Panel p =new PanelO; Virtual
p.addO): 3 dup
} II more code here...
4 Invokespec1al #J <Method
MachlttU
)

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 .

(NoU: U,is is ~ ....e.l"t to be d h-kial... '101<'11 bt


'OI\'"H:i~ Yedl tilde ill a ....OIO'O\t, bl.t .f~ MW, 'ole jll1t
wa,,-t: 'fO'J. U> ~tt d .fccl .f~ how it all .fib ~etkcYJ

you are here ~ 3


Avery brief history of Java
~ 3500
I!
~ 3000
'!lIlI
"a
2500
c
S
lill 2000
~

.,>
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

Look how easy It


Try to guess what each line of code Is doinq.;
is towrite Java. (answersare on the next page),

.int size = 27;


String name = UFido";
Dog rnyDog = new Dog(name, size);
x = size - 5j
if (x < 15) rnyDog.bark(8);

while (x > 3) {
myDog.play();
}

.int [ ] nurnList = {2,4,6,S};


System. out. print ( u Be110" ) ;
System.out.print(UDog: U + name);
String nurn = US";
int Z = Integar.parselnt(nurn);

-:.....-y {
readTheFila(UrnyFile.txt H ) ;

catch(FileNotFoundException ex) {
syetem.out.print(UFile not found.");
}

once again that the changes were so dramatic that a


Q..: I see Java 2 and Java 5.0, but was there a Java 3 new name was needed (and most developers agreed), so
-.d 41 And why Is It Java 5.0 but not Java 2.07 they looked at the options. The next number In the name
sequence woul d be ·3: but caIIing Java 1.5 Java 3 seemed
more confusing, so they decided to name It Java 5.0 to
: The joys of marketing... when the version of Java match the "5~ in version "l.S~
ed from 1.1 to 1.2, the changes to Java were so So, the original Java was versions 1.02 (the first official
rna t ic that the marketers decided we needed a whole release) through 1.1 were just "Java" Versions 1,2,1.3, and
"name: so they started calling It Java 2, even though 1.4 were "Java 2~ And beginning with version 1.5, Java is
actual version of Java was 1.2. But versions 1.3 and 1.4 called "Java 5.0~ But you'll also see it called "Java 5· (without
ftfe still considered Java 2. There never was a Java 3 or the ",0") and "Tiger" (its original code-name). We have no
~_ Be9inning with Java version 1.5,the marketers decided idea what will happen with the next release...

you are here ~ 5


.'
why Java Is cool

pen your pencil answers

Don't wotry about whether you understand any ofthis yeti


look how easy It Everything here Is explained in great detall!n the book, most
Is towrite Java. within the first 40 pages).If Java resembles a language you've
used in the past, some of th is will be simple. If not, don't worry
about it. We'llget there...

int size::; 27;


String name = #FidoHj dett.rt ~ ~~ of l~,)lW1"aridbl, Nlr.ed '~ ..c' ~r.d ~i'" it ~ ."Iot "Fido'
Dog myDog ::; new Dog (name, size); du.lm .1 _ D~ v~blc '..yD~' a.v:l ~U ~ _ D~ 1Iii~ (~' ..rod 'siu'
x = size - 5; wbu-att".fro,. 2.1 (.,,,Iot of 'siu') ~,J it to ~ y~bl, ...a",«l'1.'
if (x < 15) myDog .bark(8);

while (x > 3) {
myDog.play ( l ;
}

intl] numList = {2,4,6,8};


System.out.print(HHello R ) ;

System.out.print(HDogl U + name);
String num ::; US";
fnt z = Integer.parselnt(num);

try { try to do ~i~ ...~ybc ~ thi~ 'IlI('l"t try~ isJ,'t ~.lI'.Ued to ~ .


~ ~ tot file IIolMCll "..yFile.bi· (ar .Ii. lust TRy' 1;0 ~e.ld ~ fild
} ..lIS! be the erod of ~ "I:.h~ to try", so r ~lOC.U 'f'" te<Jd &-y Md~Y th~ ..
catch(FileNotFoundException ex) { this ~ be wkrt Oil fi,.o Nt ~ u.e tho h-led did,,'i warle._
System.out.print(HFile not found."); ~ !he I:.hi~ u-ied t~iled , rri"t "Fil, root fOllNl" out at the ~-liM
'Ill(

} locks li~ t"Icryl:.hi~ i" the { } is wlIat to do ~ the 'fry' did,,'t ~ ...

6 chapter 1
dive In A Quick Dip

Code structure i., Java

public class Dog {


What goes in a
source file?
A source code file (with the .java
extension) holds one class defini-
tion. The class represents a piece
of your program, although a very
tiny application might need just
a single class. The class must go
within a pair of curly braces. class

Put a class in a source file. What goes in a public class Dog {


class? void bark () {
Put methods in a class.
A class has one or more methods.
In the Dog class, the bark method
Put statements In a method. will hold instructions for how the
Dog should bark. Your methods
must be declared inside a class
(in other words, within the curly
braces of the class). tttefho~

public class Dog l


What goes In a
method? void bark () {
s ta temen tl ;
Within the curly braces of a
method, write your instructions statemen t2 ;
for how that method should be
performed. Method code is basi-
cally a set of statements, and for }
now you can think of a method sfafetttet1fs
kind of like a function or proce-
dure.

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).

DOI'l'i warry aW ",e"'O'riz.j..~ a..yt.hiIl9 \"'i~ht l'IOW ...

this tholf'W" is }st to ~d yC'J. sta....ud.

8 chapter 1
dive In A Quick Dip

Writi"Q aclass with amain


InJava, everything goes in a class. You'll type your source code file (with a
.java extension), then compile it into a new class file (with a . class extension).
When you run your program, you're really running a class.
Running a program means telling the Java VIrtual Machine (JVM) to "Load the
Hello class, then start executing its main () method. Keep running 'til all the
code in main is finished."
In chapter 2. we go deeper into the whole class thing, but for now, all you need to
think is, how cUJ 1 writeJava code $0 that it will run 1 And it all begins with mainf).
The mamO method is where your program starts running.
No matter how big your program is (in other words, no matter how many classes
your program uses), there's got to be a mainO method to get the ball rolling.

public class MyFirst.Aflp ( o Save


MyFirstApp. java
public static void main (strinq[] arqs)
Systall.out.priJ)t1n("I Ma!H);
System. out . println ('''l.'be World") ;
)
o Compile
javac MyFirstApp.java

-
MyFlrstApp.Java
~~
4t.. ,,\~ E)Run
~
t %j a va MyFirstApp
I Rule!
''''''
The World

MyFlratApp.clau
-
you are here ~ 9
statements, looping, branching

What ca., you say I., the",al., ",ethod1


Once you 're inside main (or any method), the fun
begins. You can say all the normal things that you say
in most programming languages to make the computer
do something.
Your code can tell the JVM to :

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.

e do solttethlttQ uttder this CO.,dltlon


Branching: If/else tests
x = 22;
II this line disturbs me

if (x == 10) 1 .. Most white space doesn't maner.


System.out.print("x mUSt be 10"); x 3
else {
System.out.print("x isn 't lO ll); .. Variables are declared with a
name and a type (you'll learn about
if «x < 3) & (name.equals("Dirk ll » ) )
all the Java types In chapter 3).
System.out.println(~Gently "); int weight;
Iitype: int, name: weight
System .out.print("this line runs no matter what ll ) ;
.. Classes and methods must be
deflned within a pair of curly braces.

public void go ( ) (
II amazing code here
}

10 chapter 1
dive In A Quick Dip

while (more Balls == true) {


keepJugg/ing() ;
}

ShMple boolean tests


.» You can do a simple boolean test by checking
Loopit1g a.,d loopi.,g at'd... the value of a variable, using a comparison operator
including:
Java has three standard Looping constructs: uihile;
do-iahile, and for. You'll get the full loop scoop later < (less than)
in the book, but not for awhile, so let's do whi~for
> (greater than)
now.
The syntax (not to mention logic) is so simple = (equality) (yes, that's two equals signs)
you're probably asleep already. As long as some Notice the difference between the assignment
condition is true, you do everything inside the operator (a single equals sign) and the equals
loop block. The loop block is bounded by a pair of operator (two equals signs). Lots of programmers
curly braces, so whatever you want to repeat needs accidentally type • when they want -. (But not
to be inside that block. you.)
The key to a loop is the conditional test. lnJava, a iot x ~ 4; II assign 4 to x
conditional test is an expression that results in a while > 3) {
(x
boolean vaJue-in other words, something that is II loop code will run because
either true or false.
II x is greater than 3
lfyou say something like , "While i.aCnamlnTMTub x = x-I; II or we'd loop forever
is true; keep scooping", you have a clear boolean
test. There either is ice cream in the cub or there inc z = 27; II
isn't. But if you were to say. "While Bob keep while (z =~ 17)
scooping" , you don't have a real test, To make
II loop code will not run because
that work, you'd have to change it to something
like. "While Bob is snoring... ~ or "While Bob is not II z is not equal to 17
wearing plaid..."
you are here ~ 11
Java basics

Exall1ple of a while loop


public class Loopy {
Q: Whydoes everything have
public static void main (String[] args) (
to be In a dass7
int x .. 1;

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.

Q: Do I have to put a main In % java Loopy


every class I write1 Before the Loop
In the loop

A: Nope .A Java prog ram


might use dozens of classes (even
Va.lue
In the loop
ot x is 1

hundreds), but you might only Va.lue of x i8 2


have one with a maIn method- In th8 loop
the one that starts the program Value of x is 3
running.You might wrIte test
This is aft.r the loop
classes, though, that have main
methods for testing your other

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 ) ;

System.out .println( "This runs no matter what");

, 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 ( }

System.out.println("x is NOT JH); If(x== _ _ }{


H
System.o ut.pri nt("Do };

System.out.println("This runs no matter what ");


I
}

, java If'l'est2
II is ~ 3
'1'hi1 runs no matter what

you are here ~ 13


serious Java app

Coding aSerious fushtess


Applicatfott
Let's put all your"new Java skills to good use with
something practical. We need a class with a mains); an int
and a String variable. a whik loop, and an if test. A little
more polish, and you'll be building that business back-
end in no time. But beJoreyou look at the code on this
page, think for a moment about how youwould code that
classic children's favorite, "99 bottles of beer."

pUblic class BeerSong (


public static void main (String[) args) (
int beerNum 99;
String word ~ "bottles";

while (beerNum > 0) I

if (beerNum == 1) (
word - "bottle H ; II s i ng ul a r , as in ONE bo ttl e .

System.out.println(beerNum + " H + word + " of beer on the wall H ) ;

System.out.println(beerNum + " H + word + " of beer.");


System.out.println("Take one down. H ) ;
System .out .println( "Pass it around. ") ;
beerNum = beerNum - 1;

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

There's stili one little flaw In our


code. It complies and runs. but the
output Isn't 100% perfect. See If
you can spot the flaw, and fix It.

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.

·IPmulticast If you're gonna be all picky about protocol

you are her e ~ 15


let's write a program

Try my new
phrase-a-matic and
you'll be a slick talker
just like the boss or
those guys in marketing.

public class PhraseQlatic (


public static void main (String(l args) {

/ / iliaD thNt sets of words to choose from. leW yoar own!


String[] wordListOne ::: {"24/7" /'multi-
Tiar","30,OOO foot", "B-to-B" , "win-win" , "front-
end" , "web- based" , "pervasive", "smart", "six-
sigma", " cri tical -path" , "dynamic"} j

Strinq[] wordListTwo ::: I "empowered", "sticky",


"value-added.", "oriented", "centric", "distributed",
"clustered", "branded", "outaide-the-box", ''positioned'',
"networked", " f ocused" / "leveraged", "aligned",
"targeted", "shared" / "cooperative", "accelerated"};

Strinq[] wordListThree = {"process", "tipping-


OK, so the beer song wasn't really a serious
business application. Still need something
point", "solution", "architecture", "core competency" ,
practical to show the boss? Check out the "strategy", "mindshare", "portal" , "apace" / "vision",
Phrase-O-Matlc code. '~adigm", ~ssion"};

/ / find out !low many word. aN In ...d11bt


iot one.Lenqth '" wordListOne . length;
int twoLength '" wordListTwo .length;
int threeLength =
wordListThree.lenqthj

/ / generate .... random numbers


int randl :lII (int) (Math.random() '" ooeLenqth) j
int rand2 ::: (int) (Math .randomO • twoLength);
int rand3 '" (int) (Math.randa:n() " threeLength);

O //now build a pllrue


String phrase'" wordListOne [randl] + " " +
wordListTwo[rand2] + " " + wordListTbree[rand3] ;

/ / print oat the phra..


Sys.tem.out.println("What we need is a " + phrase);
}

16 ch apter 1
dive In A Quick Dip

Phrase.. O.. Matlc


low Itworks,
In a nutshell, the program makes three lists of words, then randomly picks one word
from each of the three lists; and prints out the result, Don't worry if you don't under-
m.nd exactly what's happening in each line. For gosh sakes, you've got the whole book
~d of you, so relax. This isjust a quick look from a 30,000 foot outside-the-box
a.rgeted leveraged paradigm.

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

Fireside Chats Ton1gb.t's Talk: The compller and

~
~e JVM battle over the question.
"Who's more lmportaJlU"

!he Java Vlrtual Machine The Complier


What, are you kidding? HELLO. I amJava.
I'm the guy who actually makes a program
run. The compiler just gives you a file. That's
it. Just a file. You can print it out and use it
for wall paper, kindling, lining the bird cage
whateuer, but the file doesn't do anything un-
less I'm there La run it.
I don't appreciate that tone.
And that's another thing. the compiler has
no sense of humor. Then again. if ycm had to
spend all day checking nit-picky little syntax
violations... Excuse me, but without me, what exactly
would you run? There's a TMSonJava was
designed to use a bytecode compiler, for your
information. IfJava were a purely interpreted
language, where-s-at runtime-s-the virtual
machine had to translate straight-from-a-text-
editor source code, a java program would
run at a ludicrously glacial pace. java's had a
challenging enough time convincing people
that it's finally fast and powerful enough for
I'm not saying you're, like, complmly useless. mostjobs.
But really, what is it that you do? Seriously. I
have no idea. A programmer could just write
bytecode by hand, and I'd take it. You might
be out ofajob soon, buddy.
Excuse me, but that's quite an ignorant (not
to mention arrogant) perspective. While it
is true that-tJuoretically--you can run any
properly formatted bytecode even if it didn't
come out of a Java compiler, in practice that's
absurd. A programmer writing bytecode by
hand is like doing your word processing by
writing raw postscript. And I would appreciate
it if you would not refer to me as "buddy."
(I rest my case on the humor thing.) But you
still didn't answer my question, what do you
actually do?

18 chapter 1
dive In A Quick Dip

The Java Virtual Machine The Compiler


Remember thatJava is a strongly-typed lan-
guage, and that means I can't allow variables
to hold data of the wrong type. This is a
crucial safety feature, and I'm able to stop the
But some still get through! I can throw Class- vast majority of violations before they ever get
CastExceptions and sometimes I get people to you. And I also-
trying to put the wrong type of thing in an
array that was declared to hold something
else, and-
Excuse me, but I wasn't done. And yes, there
are some datatype exceptions that can emerge
at runtime, but some of those have to be
allowed to support one ofJava's other impor-
tant features--dynamic binding. At runtime,
aJava program can include new objects that
weren't even known to the original program-
mer, so I have to allow a certain amount of
flexibility. But my job is to stop anything that
would never-could never-succeed at run-
time. Usually I can tell when something won 't
work, for example, if a programmer acciden-
tally tried to use a Button object as a Socket
connection, I would detect that and thus
OK. Sure. But what about security? Look at all protect him from causing harm at runtime.
the security stuff I do , and you're like, what,
checking for semicolons? Oooohhh big security
risk ! Thank goodness for youl Excuse me, but I am the first line of defense,
as they say. The datatype violations I previous-
ly described could wreak havoc in a program
if they were allowed to manifest. I am also
the one who prevents access violations, such
as code trying to invoke a private method, or
change a method that - for security reasons
- must never be changed. I stop people from
touching code they're not meant to see,
including code trying to access another class'
critical data. It would take hours, perhaps days
even, to describe the significance of my work.
Whatever. I have to do that same stuff too,
though, just to make sure nobody snuck in
after you and changed the byte code before
running it.
Of course, but as I indicated previously, if I
didn't prevent what amounts to perhaps 99%
of the potential problems, you would grind to
a halt. And it looks like we're out of time, so

we'll have to revisit this in a later chat.
Oh, you can count on it. Buddy.

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;

"BE the oomriler if ( x < 3) {


System.out.println(~small X~)i

Each of the JIlVll files on this page


represents 11 complete source file.
Your job is to pIa}' cotJ1Piler and
determine whether each of these
files will cottlPile. If-they
won't cottlPile. how
woald you l"lX them?

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

you are here ~ 21


puzzle: crossword

1 2 J

4 S f-

I
Ja~Cr~ss t. O
II ~ '---

8 - 9 10 ~
l..-

let's give your right brain somethIng to do. 2


I- -
It'syour standard crossword, but almost all f- ~ I-- 13
of the solution words are from chapter 1.Just
4 5 6
to keep you awake, we alsothrew in a few
(non-Java) words from the high-tech world.

- - - - ~

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)

18. Quite a crew of characters 2. Come back empty-handed

19. Announce a new class or method 3. Open house

21. What'sa prompt good for? 5. 'ThIngs' holders


7. Until attitudes improve
10. Sourcecode consumer
11 . Can't pin it down
13. Dept. of LANJockeys
1S. Shocking modifier
16. Justgona haveone
17. How to get things done
20. Bytecode consumer

22 chapter 1
dive In A Quick Dip

A short Java program is listed below. One block of the program


is missing. Your challenge is to match the candidate block of
code (on the left),with the output that you'd see if the block
were inserted. Not all the lines of output will be used, and some
of the lines of output might be used more than once. Draw lines
connecting the candidate blocks of code with their matching
command-line output. (The answers are at the end of the chapter).

class Test {
public static void main (String [) args)
int x 0;
int y = 0;
while x < 5 )

System.out.print(x + "" + y +" ");


x = x + 1;

candidates: Possible output:

00 11 21 32 42

lJ. 21 32 42 53

00 11 23 36 410

02 14 25 36 41

you are here ~ 23


puzzle: Pool Puzzle

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("");

Note: Each snippet


from the pool can be
used only oncel

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");
}

i f (x == 1), { This file won't compile without 0


Systern.out.print("d")j } class d~c1Qratlon, and don't forget
x = x - Ij ) the matching curly brace!
}
}

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

The 'while' loop code must be in-


} side a method. It can't just be
hanging out inside the class.

you are here ~ 25


puzzle answers

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:

Syst£ln. out. prlnt('olsej;


}
System.out.println(UU);

X =X + 1; 'y j ava PoolPuzzl c One


}
Ct noise
}
anno~'s
} an o ~'s t e r

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.

I was told there would be objects. )NCHAPTER WEPUTALLOFOURCODEINTHE


MAIN METHOD4HATSNOTEXACTLYOBJECT ORIENTED)NFACT THATSNOTOBJECT ORIENTEDATALL7ELL
WEDIDUSEAFEWOBJECTS LIKETHE3TRINGARRAYSFORTHE0HRASE / -ATIC BUTWEDIDNTACTUALLY
DEVELOPANYOFOUROWNOBJECTTYPES3ONOWWEVEGOTTOLEAVETHATPROCEDURALWORLDBEHIND
GETTHEHECKOUTOFMAIN ANDSTARTMAKINGSOMEOBJECTSOFOUROWN7ELLLOOKATWHATMAKES
OBJECT ORIENTED// DEVELOPMENTIN*AVASOMUCHFUN7ELLLOOKATTHEDIFFERENCEBETWEEN
ACLASSANDANOBJECT7ELLLOOKATHOWOBJECTSCANGIVEYOUABETTERLIFEATLEASTTHEPROGRAM
MINGPARTOFYOURLIFE.OTMUCHWECANDOABOUTYOURFASHIONSENSE 7ARNINGONCEYOUGET
TO/BJECTVILLE YOUMIGHTNEVERGOBACK3ENDUSAPOSTCARD

this is a new chapter 27


once upon a time in Objectville

Chair Wars
(or How Objects Can Change Your Life)
the spec

O
NCEUPONATIMEINASOFTWARESHOP TWO
PROGRAMMERSWEREGIVENTHESAMESPECANDTOLDTO
hBUILDITv4HE2EALLY!NNOYING0ROJECT-ANAGER
FORCEDTHETWOCODERSTOCOMPETE
BYPROMISINGTHATWHOEVERDELIVERS
lRSTGETSONEOFTHOSECOOL!ERON©
CHAIRSALLTHE3ILICON6ALLEYGUYSHAVE
,ARRY THEPROCEDURALPROGRAMMER AND
"RAD THE//GUY BOTHKNEWTHISWOULD
BEAPIECEOFCAKE
,ARRY SITTINGINHISCUBE THOUGHTTO
HIMSELF h7HATARETHETHINGSTHISPROGRAM
HASTODO7HATPROCEDURESDOWENEEDv
!NDHEANSWEREDHIMSELF hROTATEAND
PLAY3OUNDv3OOFFHEWENTTOBUILDTHE
PROCEDURES!FTERALL WHATISAPROGRAMIFNOT
APILEOFPROCEDURES
"RAD MEANWHILE KICKEDBACKATTHECAFE
ANDTHOUGHTTOHIMSELF h7HATARETHETHINGS
INTHISPROGRAMWHOARETHEKEYPLAYERSv(E
lRSTTHOUGHTOF4HE3HAPES/FCOURSE THERE
WEREOTHEROBJECTSHETHOUGHTOFLIKETHE5SER THE3OUND
ANDTHE#LICKINGEVENT"UTHEALREADYHADALIBRARYOFCODE
FORTHOSEPIECES SOHEFOCUSEDONBUILDING3HAPES2EAD
ONTOSEEHOW"RADAND,ARRYBUILTTHEIRPROGRAMS AND the chair
FORTHEANSWERTOYOURBURNINGQUESTION h3O WHOGOTTHE
!ERONv

In Larry’s cube At Brad’s laptop at the cafe


!SHEHADDONEAGAZILLIONTIMESBEFORE ,ARRY "RADWROTEACLASSFOREACHOFTHETHREESHAPES
SETABOUTWRITINGHIS)MPORTANT0ROCEDURES
(EWROTEROTATEANDPLAY3OUNDINNOTIME
rotate(shapeNum) {
// make the shape rotate 360º
}
playSound(shapeNum) {
// use shapeNum to lookup which }
// AIF sound to play, and play it
}
}
}

28 chapter 2
classes and objects

Larry thought he’d nailed it. He could almost feel the rolled
steel of the Aeron beneath his...

But wait! There’s been a spec change.


h/+ TECHNICALLYYOUWERElRST ,ARRY vSAIDTHE-ANAGER hBUTWEHAVETOADDJUSTONE
TINYTHINGTOTHEPROGRAM)TLLBENOPROBLEMFORCRACKPROGRAMMERSLIKEYOUTWOv
h)F)HADADIMEFOREVERYTIME)VEHEARDTHATONEv THOUGHT,ARRY KNOWINGTHATSPEC
CHANGE NO PROBLEMWASAFANTASYh!NDYET"RADLOOKSSTRANGELYSERENE7HATSUPWITH
THATv3TILL ,ARRYHELDTIGHTTOHISCOREBELIEFTHATTHE//WAY WHILECUTE WASJUST
SLOW!NDTHATIFYOUWANTEDTOCHANGEHISMIND YOUDHAVETOPRYITFROMHISCOLD
DEAD CARPAL TUNNELLEDHANDS
shape
l b e a n amoeba rs.
There wil en, with the othe what got added to the spec
r e
on the sc ser clicks on the
t h e u ke the
When il l rotate li und file 
a , it w
amoeb .hif so
t h e r s , a nd play a
o

Back in Larry’s cube At Brad’s laptop at the beach


4HEROTATEPROCEDUREWOULDSTILLWORKTHECODEUSED "RADSMILED SIPPEDHISMARGARITA ANDWROTEONE
ALOOKUPTABLETOMATCHASHAPE.UMTOANACTUAL NEWCLASS3OMETIMESTHETHINGHELOVEDMOST
SHAPEGRAPHIC"UTPLAY3OUNDWOULDHAVETOCHANGE ABOUT//WASTHATHEDIDNTHAVETOTOUCHCODE
!NDWHATTHEHECKISAHIFlLE HEDALREADYTESTEDANDDELIVEREDh&LEXIBILITY
playSound(shapeNum) { EXTENSIBILITY vHEMUSED REmECTINGONTHE
// if the shape is not an amoeba, BENElTSOF//
// use shapeNum to lookup which Amoeba
// AIF sound to play, and play it rotate() {
// else // code to rotate an amoeba
// play amoeba .hif sound }
}
playSound() {
)TTURNEDOUTNOTTOBESUCHABIGDEAL BUTITSTILL
// code to play the new
MADEHIMQUEASYTOTOUCHPREVIOUSLY TESTEDCODE/F // .hif file for an amoeba
ALLPEOPLE HESHOULDKNOWTHATNOMATTERWHATTHE }
PROJECTMANAGERSAYS THESPECALWAYSCHANGES

you are here4 29


once upon a time in Objectville

Larry snuck in just moments ahead of Brad.


(AH3OMUCHFORTHATFOOFY//NONSENSE "UTTHESMIRKON,ARRYSFACEMELTEDWHENTHE
2EALLY!NNOYING0ROJECT-ANAGERSAIDWITHTHATTONEOFDISAPPOINTMENT h/H NO THATSNOT
HOWTHEAMOEBAISSUPPOSEDTOROTATEv
4URNSOUT BOTHPROGRAMMERSHADWRITTENTHEIRROTATECODELIKETHIS
1) determine the rectangle that surrounds the shape
2) calculate the center of that rectangle, and rotate the shape around that point.
"UTTHEAMOEBASHAPEWASSUPPOSEDTOROTATEAROUNDAPOINTONONEEND LIKEACLOCKHAND
h)MTOASTvTHOUGHT,ARRY VISUALIZINGCHARRED7ONDERBREAD©h!LTHOUGH HMMMM)COULD
JUSTADDANOTHERIFELSETOTHEROTATEPROCEDURE ANDTHENJUSTHARD CODETHEROTATIONPOINT
CODEFORTHEAMOEBA4HATPROBABLYWONTBREAKANYTHINGv"UTTHELITTLEVOICEATTHEBACKOF
HISHEADSAID h"IG-ISTAKE$OYOUHONESTLYTHINKTHESPECWONTCHANGEAGAINv

Larry
r o t a t io n point in
Ameoba version:
’s
and Brad
What the spec conveniently
forgot to mention

tatio n
e r e t h e ameba ro
Wh
uld be:
point sho

Back in Larry’s cube At Brad’s laptop on his lawn


(ElGUREDHEBETTERADDROTATIONPOINTARGUMENTS chair at the Telluride Bluegrass Festival
TOTHEROTATEPROCEDURE!LOTOFCODEWASAFFECTED 7ITHOUTMISSINGABEAT "RADMODIlEDTHEROTATE
4ESTING RECOMPILING THEWHOLENINEYARDSALLOVER METHOD BUTONLYINTHE!MOEBACLASS(ENEVER
AGAIN4HINGSTHATUSEDTOWORK DIDNT TOUCHEDTHETESTED WORKING
rotate(shapeNum, xPt, yPt) { COMPILEDCODEFORTHEOTHER Amoeba
// if the shape is not an amoeba, PARTSOFTHEPROGRAM4O int xPoint
// calculate the center point GIVETHE!MOEBAAROTA int yPoint
TIONPOINT HEADDEDAN rotate() {
// based on a rectangle,
ATTRIBUTETHATALL!MOEBAS // code to rotate an amoeba
// then rotate WOULDHAVE(EMODI // using amoeba’s x and y
// else lED TESTED ANDDELIVERED }
// use the xPt and yPt as WIRELESSLY THEREVISED playSound() {
// the rotation point offset PROGRAMDURINGASINGLE // code to play the new
"ELA&LECKSET // .hif file for an amoeba
// and then rotate }
}
30 chapter 2
classes and objects

So, Brad the OO guy got the chair, right ?


.OTSOFAST,ARRYFOUNDAmAWIN"RADSAPPROACH!ND
SINCEHEWASSURETHATIFHEGOTTHECHAIRHEDALSOGET,UCY
INACCOUNTING HEHADTOTURNTHISTHINGAROUND
,!2299OUVEGOTDUPLICATEDCODE4HEROTATE
PROCEDUREISINALLFOUR3HAPETHINGS
"2!$)TSAMETHOD NOTAPROCEDURE!NDTHEYRECLASSES
NOTTHINGS
,!2297HATEVER)TSASTUPIDDESIGN9OUHAVETO
MAINTAINFOURDIFFERENTROTATEhMETHODSv(OWCANTHAT
EVERBEGOOD
"2!$/H )GUESSYOUDIDNTSEETHElNALDESIGN,ETME
SHOWYOUHOW//INHERITANCEWORKS ,ARRY
What Larry wanted
(figured the chair would impress her)

1
Square Circle Triangle Amoeba
I looked at what all four
rotate() rotate() rotate() rotate() classes have in common.
playSound() playSound() playSound() playSound()

2
They’re Shapes, and they all rotate and Shape
playSound. So I abstracted out the
common features and put them into a
rotate()
playSound()
3
new class called Shape. Then I linked the other
Shape
superclass four shape classes to
rotate()
playSound() the new Shape class,
in a relationship called
inheritance.
You can read this as, “Square inherits from Shape”,
“Circle inherits from Shape”, and so on. I removed subclasses
rotate() and playSound() from the other shapes, so now
there’s only one copy to maintain.
Square Circle Triangle Amoeba
The Shape class is called the superclass of the other four
classes. The other four are the subclasses of Shape. The
subclasses inherit the methods of the superclass. In other
words, if the Shape class has the functionality, then the
subclasses automatically get that same functionality.
you are here4 31
once upon a time in Objectville

What about the Amoeba rotate()?


,!2297ASNTTHATTHEWHOLEPROBLEMHEREˆTHATTHEAMOEBASHAPE
HADACOMPLETELYDIFFERENTROTATEANDPLAY3OUNDPROCEDURE
rride Now
"2!$-ETHOD ve

O
,!2297HATEVER(OWCANAMOEBADOSOMETHINGDIFFERENTIF
As w
IThINHERITSvITSFUNCTIONALITYFROMTHE3HAPECLASS k Me Ho

"2!$4HATSTHELASTSTEP4HE!MOEBACLASSOVERRIDESTHE
METHODSOFTHE3HAPECLASS4HENATRUNTIME THE*6-KNOWSEXACTLY
WHICHROTATE METHODTORUNWHENSOMEONETELLSTHE!MOEBATOROTATE

superclass
(more abstract)
Shape 4
rotate()
playSound()
madethe
I Imade Amoebaclass
theAmoeba override
classoverride
the and playSound()
rotate()method
therotate() of the
methods of the
superclass Shape. superclass Shape.
subclasses justmeans
Overridingjust thataa
meansthat
(more specific) Overriding
subclassredefines
subclass oneof
redefinesone its
ofits
inherited methods when it
inherited methods when it needs needs
Square Circle Triangle Amoeba to change or extend the behavior
to change or extend the behavior
of method.
thatmethod.
ofthat
rotate() {
// amoeba-specific
// rotate code {
Overriding methods
playSound() {
// amoeba-specific
// sound code {

I can take
,!229(OWDOYOUhTELLvAN!MOEBATO
care of myself.
DOSOMETHING$ONTYOUHAVETOCALLTHE I know how an Amoeba
PROCEDURE SORRYˆMETHOD ANDTHENTELLIT I know how a Shape is is supposed to rotate
WHICHTHINGTOROTATE supposed to behave. Your and play a sound.
job is to tell me what to
"2!$4HATSTHEREALLYCOOLTHINGABOUT//
do, and my job is to make it happen.
7HENITSTIMEFOR SAY THETRIANGLETOROTATE Don’t you worry your little program-
THEPROGRAMCODEINVOKESCALLS THEROTATE mer head about how I do it.
METHODONTHETRIANGLEOBJECT4HERESTOFTHE
PROGRAMREALLYDOESNTKNOWORCAREHOWTHE
TRIANGLEDOESIT!NDWHENYOUNEEDTOADD
SOMETHINGNEWTOTHEPROGRAM YOUJUSTWRITE
ANEWCLASSFORTHENEWOBJECTTYPE SOTHENEW
OBJECTSWILLHAVETHEIROWNBEHAVIOR

32 chapter 2
classes and objects

The suspense is killing me.


Who got the chair?

!MYFROMTHESECONDmOOR
UNBEKNOWNSTTOALL THE0ROJECT
-ANAGERHADGIVENTHESPECTO
THREEPROGRAMMERS

YiX`e
What do you like about OO? gfn\i
4IMETOPUMPSOMENEURONS
“It helps me design in a more natural way. Things 9OUJUSTREADASTORYBOUTAPROCEDURAL
have a way of evolving.” PROGRAMMERGOINGHEAD TO HEADWITHAN//
-Joy, 27, software architect PROGRAMMER9OUGOTAQUICKOVERVIEWOFSOME
KEY//CONCEPTSINCLUDINGCLASSES METHODS AND
ATTRIBUTES7ELLSPENDTHERESTOFTHECHAPTER
“Not messing around with code I’ve already LOOKINGATCLASSESANDOBJECTSWELLRETURNTO
tested, just to add a new feature.” INHERITANCEANDOVERRIDINGINLATERCHAPTERS 
-Brad, 32, programmer "ASEDONWHATYOUVESEENSOFARANDWHATYOU
MAYKNOWFROMAPREVIOUS//LANGUAGEYOUVE
WORKEDWITH TAKEAMOMENTTOTHINKABOUT
“I like that the data and the methods that oper-
THESEQUESTIONS
ate on that data are together in one class.”
-Josh, 22, beer drinker 7HATARETHEFUNDAMENTALTHINGSYOUNEEDTO
THINKABOUTWHENYOUDESIGNA*AVACLASS7HAT
“Reusing code in other applications. When I write ARETHEQUESTIONSYOUNEEDTOASKYOURSELF
a new class, I can make it flexible enough to be )FYOUCOULDDESIGNACHECKLISTTOUSEWHEN
used in something new, later.” YOUREDESIGNINGACLASS WHATWOULDBEONTHE
-Chris, 39, project manager CHECKLIST

“I can’t believe Chris just said that. He hasn’t


written a line of code in 5 years.”
-Daryl, 44, works for Chris metacognitive tip
If you’re stuck on an exercise, try talking about
“Besides the chair?”
it out loud. Speaking (and hearing) activates
-Amy, 34, programmer
a different part of your brain. Although it
works best if you have another person to
discuss it with, pets work too. That’s how
our dog learned polymorphism.

you are here4 33


thinking about objects

When you design a class, think about the objects that


will be cre ated from that class t ype. Think about:
Nthings the object knows
Nthings the object does

ShoppingCart Button Alarm

label alarmTime
cartContents knows color knows alarmMode knows
setColor() setAlarmTime()
addToCart() does setLabel() does getAlarmTime()
setAlarm() does
removeFromCart() dePress() isAlarmSet()
checkOut() unDepress() snooze()

Things an object knows about itself are called Song

Ninstance variables instance title knows


variables artist
(state)
setTitle()
Things an object can do are called methods setArtist() does
(behavior) play()
Nmethods

4HINGSANOBJECTKNOWSABOUTITSELFARECALLEDINSTANCE Sharpen your pencil


VARIABLES4HEYREPRESENTANOBJECTSSTATETHEDATA AND
CANHAVEUNIQUEVALUESFOREACHOBJECTOFTHATTYPE &ILLINWHATATELEVISIONOBJECT
MIGHTNEEDTOKNOWANDDO
Think of instance as another way of saying object.
4HINGSANOBJECTCANDOARECALLEDMETHODS7HENYOU
DESIGNACLASS YOUTHINKABOUTTHEDATAANOBJECTWILLNEED
TOKNOWABOUTITSELF ANDYOUALSODESIGNTHEMETHODS
THATOPERATEONTHATDATA)TSCOMMONFORANOBJECTTO
HAVEMETHODSTHATREADORWRITETHEVALUESOFTHEINSTANCE
VARIABLES&OREXAMPLE !LARMOBJECTSHAVEANINSTANCE
VARIABLETOHOLDTHEALARM4IME ANDTWOMETHODSFOR
GETTINGANDSETTINGTHEALARM4IME
3OOBJECTSHAVEINSTANCEVARIABLESANDMETHODS BUTTHOSE
INSTANCEVARIABLESANDMETHODSAREDESIGNEDASPARTOFTHE
CLASS

34 chapter 2
classes and objects

What’s the difference between


a class and an object?

A class is not an object.


(but it’s used to construct them)

!CLASSISABLUEPRINTFORANOBJECT)TTELLSTHE
VIRTUALMACHINEHOWTOMAKEANOBJECTOFTHAT
JVM
PARTICULARTYPE%ACHOBJECTMADEFROMTHAT
CLASSCANHAVEITSOWNVALUESFORTHE
INSTANCEVARIABLESOFTHATCLASS&OR
EXAMPLE YOUMIGHTUSETHE"UTTON
CLASSTOMAKEDOZENSOFDIFFERENT
BUTTONS ANDEACHBUTTONMIGHTHAVE
class
ITSOWNCOLOR SIZE SHAPE LABEL ANDSOON

Look at it this way... !NOBJECTISLIKEONEENTRYINYOURADDRESSBOOK


/NEANALOGYFOROBJECTSISAPACKETOFUNUSED2OLODEX»CARDS
%ACHCARDHASTHESAMEBLANKFIELDSTHEINSTANCEVARIABLES 7HEN
YOUFILLOUTACARDYOUARECREATINGANINSTANCEOBJECT ANDTHE
ENTRIESYOUMAKEONTHATCARDREPRESENTITSSTATE
4HEMETHODSOFTHECLASSARETHETHINGSYOUDOTOAPARTICULARCARD
GET.AME CHANGE.AME SET.AME COULDALLBEMETHODSFOR
CLASS2OLODEX
3O EACHCARDCANDOTHESAMETHINGSGET.AME CHANGE.AME
ETC BUTEACHCARDKNOWSTHINGSUNIQUETOTHATPARTICULARCARD

you are here4 35


making objects

Making your first object


3OWHATDOESITTAKETOCREATEANDUSEANOBJECT9OUNEEDTWOCLASSES/NE
CLASSFORTHETYPEOFOBJECTYOUWANTTOUSE$OG !LARM#LOCK 4ELEVISION The Dot Operator (.)
ETC ANDANOTHERCLASSTOTESTYOURNEWCLASS4HETESTERCLASSISWHEREYOUPUT
THEMAINMETHOD ANDINTHATMAIN METHODYOUCREATEANDACCESSOBJECTS 4HEDOTOPERATOR GIVES
OFYOURNEWCLASSTYPE4HETESTERCLASSHASONLYONEJOBTOTRYOUTTHEMETH YOUACCESSTOANOBJECTS
ODSANDVARIABLESOFYOURNEWOBJECTCLASSTYPE STATEANDBEHAVIORINSTANCE
VARIABLESANDMETHODS 
&ROMTHISPOINTFORWARDINTHEBOOK YOULLSEETWOCLASSESINMANYOF
OUREXAMPLES/NEWILLBETHEREALCLASSnTHECLASSWHOSEOBJECTSWE
REALLYWANTTOUSE ANDTHEOTHERCLASSWILLBETHETESTERCLASS WHICHWE MAKEANEWOBJECT
CALLWHATEVER9OUR#LASS.AME)STestDrive&OREXAMPLE IFWEMAKEA $OGDNEW$OG 
Bungee CLASS WELLNEEDABungeeTestDriveCLASSASWELL/NLYTHE
SOME#LASS.AMETestDrive CLASSWILLHAVEAMAIN METHOD ANDITSSOLE
PURPOSEISTOCREATEOBJECTSOFYOURNEWTYPETHENOT THE TESTERCLASS AND TELLITTOBARKBYUSINGTHE
THENUSETHEDOTOPERATOR TOACCESSTHEMETHODSANDVARIABLESOFTHENEW DOTOPERATORONTHE
VARIABLEDTOCALLBARK
OBJECTS4HISWILLALLBEMADESTUNNINGLYCLEARBYTHEFOLLOWINGEXAMPLES
DBARK 

1 Write your class


SETITSSIZEUSINGTHE
class Dog { DOTOPERATOR
instance va DOG DSIZE
riables
int size; size
String breed; breed
name
String name;
a method bark()
void bark() {
System.out.println(“Ruff! Ruff!”);
}
} 2 Write a tester (TestDrive) class
class DogTestDrive {
d
a m a i n metho de public static void main (String[] args) {
just co
na puetxt step) // Dog test code goes here
’r e g o n
(we it in the n }
in }

In your tester, make an object and access


3 the object’s variables and methods
class DogTestDrive {
public static void main (String[] args) {
Dog d = new Dog(); make a Dog
object
d.size = 40; use the dot operator (.)
dot r d.bark(); to set the size of the Do
operato } and to call its bark g If you already have some OO savvy,
you’ll know we’re not using encapsulation.
} () method We’ll get there in chapter 4.

36 chapter 2
classes and objects

Making and testing Movie objects


class Movie {
String title;
String genre;
int rating;
void playIt() {
System.out.println(“Playing the movie”);
}
}

public class MovieTestDrive {


public static void main(String[] args) {
Movie one = new Movie();
one.title = “Gone with the Stock”;
one.genre = “Tragic”;
one.rating = -2;
Movie two = new Movie();
two.title = “Lost in Cubicle Space”;
two.genre = “Comedy”;
two.rating = 5;
two.playIt();
Movie three = new Movie();
three.title = “Byte Club”;
three.genre = “Tragic but ultimately uplifting”;
three.rating = 127;
}
}
Sharpen your pencil

title
MOVIE
object 1 genre
title
genre rating
rating
playIt()
title

4HE-OVIE4EST$RIVECLASSCREATESOBJECTSINSTANCES OF object 2 genre


THE-OVIECLASSANDUSESTHEDOTOPERATOR TOSETTHE
rating
INSTANCEVARIABLESTOASPECIFICVALUE4HE-OVIE4EST$RIVE
CLASSALSOINVOKESCALLS AMETHODONONEOFTHEOBJECTS
&ILLINTHECHARTTOTHERIGHTWITHTHEVALUESTHETHREE title
OBJECTSHAVEATTHEENDOFMAIN 
object 3 genre

rating

you are here4 37


get the heck out of main

Quick! Get out of main!


!SLONGASYOUREINMAIN YOURENOTREALLYIN/BJECTVILLE)TSlNEFORATEST
PROGRAMTORUNWITHINTHEMAINMETHOD BUTINATRUE//APPLICATION YOU
NEEDOBJECTSTALKINGTOOTHEROBJECTS ASOPPOSEDTOASTATICMAIN METHOD
CREATINGANDTESTINGOBJECTS

The t wo uses of main:


Nto test your real class
Nto launch/start your Java application
!REAL*AVAAPPLICATIONISNOTHINGBUTOBJECTSTALKINGTOOTHEROBJECTS)NTHIS
CASE TALKINGMEANSOBJECTSCALLINGMETHODSONONEANOTHER/NTHEPREVIOUS
PAGE ANDINCHAPTER WELOOKATUSINGAMAIN METHODFROMASEPARATE
4EST$RIVECLASSTOCREATEANDTESTTHEMETHODSANDVARIABLESOFANOTHERCLASS)N
CHAPTERWELOOKATUSINGACLASSWITHAMAIN METHODTOSTARTTHEBALLROLLING
ONAREAL*AVAAPPLICATIONBYMAKINGOBJECTSANDTHENTURNINGTHOSEOBJECTS
GameLauncher
LOOSETOINTERACTWITHOTHEROBJECTS ETC
make
!SA@SNEAKPREVIEW THOUGH OFHOWAREAL*AVAAPPLICATIONMIGHTBEHAVE GuessGs a
HERESALITTLEEXAMPLE"ECAUSEWERESTILLATTHEEARLIESTSTAGESOFLEARNING*AVA object ame
WEREWORKINGWITHASMALLTOOLKIT SOYOULLlNDTHISPROGRAMALITTLECLUNKY main(String[] args) tells it and
ANDINEFlCIENT9OUMIGHTWANTTOTHINKABOUTWHATYOUCOULDDOTOIMPROVE startG to
IT ANDINLATERCHAPTERSTHATSEXACTLYWHATWELLDO$ONTWORRYIFSOMEOFTHE ame
CODEISCONFUSINGTHEKEYPOINTOFTHISEXAMPLEISTHATOBJECTSTALKTOOBJECTS

The Guessing Game GuessGame


instan
3UMMARY p1 variablecse
4HEGUESSINGGAMEINVOLVESA@GAMEOBJECTANDTHREE@PLAYEROBJECTS4HEGAMEGEN p2 forth
ERATESARANDOMNUMBERBETWEENAND ANDTHETHREEPLAYEROBJECTSTRYTOGUESS p3 playerse three
IT7EDIDNTSAYITWASAREALLYEXCITINGGAME
startGame()
#LASSES
GuessGame.class Player.class GameLauncher.class
the
4HE,OGIC Player this pnlumber
guessedayer
 4HE'AME,AUNCHERCLASSISWHERETHEAPPLICATIONSTARTSITHASTHEMAIN METHOD number
 )NTHEMAIN METHOD A'UESS'AMEOBJECTISCREATED ANDITSSTART'AME METHOD meth
guess()
ISCALLED makingod for
 4HE'UESS'AMEOBJECTSSTART'AME METHODISWHERETHEENTIREGAMEPLAYSOUT guess a
)TCREATESTHREEPLAYERS THENhTHINKSvOFARANDOMNUMBERTHETARGETFORTHEPLAYERS
TOGUESS )TTHENASKSEACHPLAYERTOGUESS CHECKSTHERESULT ANDEITHERPRINTSOUT
INFORMATIONABOUTTHEWINNINGPLAYERS ORASKSTHEMTOGUESSAGAIN

38 chapter 2
classes and objects

public class GuessGame { GuessGame has ree


Player p1; variables for thth
e th re
instance
Player p2; objects e Player
Player p3;
public void startGame() { create three Play
p1 = new Player();
assign them to theerthobrejec
e
ts and
p2 = new Player();
instance variables Pl ayer
p3 = new Player();
int guessp1 = 0; declare three variables to hold the
int guessp2 = 0; three guesses the Players mak
int guessp3 = 0; e
boolean p1isRight = false;
boolean p2isRight = false;
declare three variables to hold a true or
boolean p3isRight = false; false based on the player’s answer
int targetNumber = (int) (Math.random() * 10); make a ‘target’ number that the
System.out.println(“I’m thinking of a number between 0 and 9...”); players have to guess
while(true) {
System.out.println(“Number to guess is “ + targetNumber);
p1.guess();
p2.guess();
call each player’s guess() method
p3.guess();
guessp1 = p1.number;
System.out.println(“Player one guessed “ + guessp1);
guessp2 = p2.number; get each player’s guess (the result their
System.out.println(“Player two guessed “ + guessp2); guess() method running) by accessingofthe
guessp3 = p3.number; number variable of each player
System.out.println(“Player three guessed “ + guessp3);

if (guessp1 == targetNumber) {
p1isRight = true;
} check each player’s guess to see if it matches
if (guessp2 == targetNumber) { the target number. If a player is right ,
p2isRight = true; then set that player’s variable to be true
} (remember, we set it false by default)
if (guessp3 == targetNumber) {
p3isRight = true;
}
if player one OR player two OR player three is right
if (p1isRight || p2isRight || p3isRight) {
(the || operator means OR) ...
System.out.println(“We have a winner!”);
System.out.println(“Player one got it right? “ + p1isRight);
System.out.println(“Player two got it right? “ + p2isRight);
System.out.println(“Player three got it right? “ + p3isRight);
System.out.println(“Game is over.”);
break; // game over, so break out of the loop
otherwis
players feo,rsta ay in the loop and ask
} else {
// we must keep going because nobody got it right!
System.out.println(“Players will have to try again.”);
nother guess. the
} // end if/else
} // end loop
} // end method
} // end class

you are here4 39


Guessing Game

Running the Guessing Game


public class Player {
int number = 0; // where the guess goes

public void guess() { /UTPUTITWILLBEDIFFERENTEACHTIMEYOURUNIT


number = (int) (Math.random() * 10);
System.out.println(“I’m guessing “ File Edit Window Help Explode

+ number); %java GameLauncher


}
} I’m thinking of a number between 0 and 9...
Number to guess is 7
public class GameLauncher { I’m guessing 1
public static void main (String[] args) { I’m guessing 9
GuessGame game = new GuessGame();
game.startGame(); I’m guessing 9
} Player one guessed 1
}
Player two guessed 9
Player three guessed 9
Players will have to try again.
Java takes out the
Garbage Number to guess is 7
I’m guessing 3
%ACHTIMEANOBJECTISCREATED
IN*AVA ITGOESINTOANAREAOF I’m guessing 0
MEMORYKNOWNAS4HE(EAP I’m guessing 9
!LLOBJECTSˆNOMATTERWHEN WHERE
Player one guessed 3
ORHOWTHEYRECREATEDnLIVEONTHE
HEAP"UTITSNOTJUSTANYOLDMEMORY Player two guessed 0
HEAPTHE*AVAHEAPISACTUALLYCALLEDTHE Player three guessed 9
'ARBAGE #OLLECTIBLE(EAP7HENYOU
CREATEANOBJECT *AVAALLOCATESMEMORY
Players will have to try again.
SPACEONTHEHEAPACCORDINGTOHOW Number to guess is 7
MUCHTHATPARTICULAROBJECTNEEDS!N I’m guessing 7
OBJECTWITH SAY INSTANCEVARIABLES
WILLPROBABLYNEEDMORESPACETHANAN I’m guessing 5
OBJECTWITHONLYTWOINSTANCEVARIABLES I’m guessing 0
"UTWHATHAPPENSWHENYOUNEEDTO Player one guessed 7
RECLAIMTHATSPACE(OWDOYOUGETAN
OBJECTOUTOFTHEHEAPWHENYOUREDONE Player two guessed 5
WITHIT*AVAMANAGESTHATMEMORY Player three guessed 0
FORYOU7HENTHE*6-CAN@SEETHATAN
We have a winner!
OBJECTCANNEVERBEUSEDAGAIN THAT
OBJECTBECOMESELIGIBLEFORGARBAGE Player one got it right? true
COLLECTION!NDIFYOURERUNNINGLOWON Player two got it right? false
MEMORY THE'ARBAGE#OLLECTORWILLRUN
THROWOUTTHEUNREACHABLEOBJECTS AND Player three got it right? false
FREEUPTHESPACE SOTHATTHESPACECAN Game is over.
BEREUSED)NLATERCHAPTERSYOULLLEARN
MOREABOUTHOWTHISWORKS

40 chapter 2
classes and objects

there are no
Dumb Questions
Q: 7HATIF)NEEDGLOBAL Q: 7HATISA*AVAPROGRAM
VARIABLESANDMETHODS(OW 7HATDOYOUACTUALLYDELIVER
DO)DOTHATIFEVERYTHINGHASTO
GOINACLASS
A: !*AVAPROGRAMISAPILE
Make it Stic
A: 4HEREISNTACONCEPTOF
OFCLASSESORATLEASTONECLASS 
)NA*AVAAPPLICATION ONEOF
k
@GLOBALVARIABLESANDMETHODSIN THECLASSESMUSTHAVEAMAIN
!CLASSIS
A*AVA//PROGRAM)NPRACTICAL METHOD USEDTOSTART UPTHE LIKEARECI
P E
USE HOWEVER THEREARETIMES PROGRAM3OASAPROGRAMMER /BJEC TSA
RELIKE
WHENYOUWANTAMETHODOR YOUWRITEONEORMORECLASSES COOKIES
ACONSTANT TOBEAVAILABLE !NDTHOSECLASSESAREWHATYOU
TOANYCODERUNNINGINANY DELIVER)FTHEEND USERDOESNT
PARTOFYOURPROGRAM4HINK HAVEA*6- THENYOULLALSO
OFTHErandom()METHODIN NEEDTOINCLUDETHATWITH
THE0HRASE / -ATICAPPITSA YOURAPPLICATIONSCLASSES
METHODTHATSHOULDBEC ALLABLE SOTHATTHEYCANRUNYOUR
FROMANYWHERE/RWHATABOUT PROGRAM4HEREAREANUMBER
ACONSTANTLIKEPI9OULLLEARN OFINSTALLERPROGRAMSTHAT
INCHAPTERTHATMARKING LETYOUBUNDLEYOURCLASSES
AMETHODASpublic AND WITHAVARIETYOF*6-SSAY FOR
static MAKESITBEHAVEMUCH DIFFERENTPLATFORMS ANDPUTITALL
LIKEA@GLOBAL!NYCODE INANY ONA#$ 2/-4HENTHEEND USER BULLET POINTS
CANINSTALLTHECORRECTVERSIONOF
CLASSOFYOURAPPLICATION CAN
THE*6-ASSUMINGTHEYDONT
ß Object-oriented programming lets you extend
ACCESSAPUBLICSTATICMETHOD
ALREADYHAVEITONTHEIRMACHINE
a program without having to touch previously-
!NDIFYOUMARKAVARIABLEAS
public static ANDfinal tested, working code.
nYOUHAVEESSENTIALLYMADEA ß All Java code is defined in a class.
GLOBALLY AVAILABLECONSTANT
Q: 7HATIF)HAVEAHUNDRED ß A class describes how to make an object of
that class type. A class is like a blueprint.
CLASSES/RATHOUSAND)SNT
ß
Q: 4HENHOWISTHISOBJECT
THATABIGPAINTODELIVER
ALLTHOSEINDIVIDUALlLES
An object can take care of itself; you don’t
have to know or care how the object does it.
ORIENTEDIFYOUCANSTILLMAKE #AN)BUNDLETHEMINTOONE
ß An object knows things and does things.
GLOBALFUNCTIONSANDGLOBAL !PPLICATION4HING
DATA ß Things an object knows about itself are called
instance variables. They represent the state

A: A: 9ES ITWOULDBEABIG of an object.


&IRSTOFALL EVERYTHING PAINTODELIVERAHUGEBUNCHOF ß Things an object does are called methods.
IN*AVAGOESINACLASS3OTHE INDIVIDUALFILESTOYOUREND USERS They represent the behavior of an object.
CONSTANTFORPIANDTHEMETHOD BUTYOUWONTHAVETO9OUCAN
FORrandom() ALTHOUGHBOTH PUTALLOFYOURAPPLICATIONFILES ß When you create a class, you may also want
PUBLICANDSTATIC AREDEFINED INTOA*AVA!RCHIVEnAJARFILEn to create a separate test class which you’ll
WITHINTHEMathCLASS!NDYOU THATSBASEDONTHEPKZIPFORMAT use to create objects of your new class type.
MUSTKEEPINMINDTHATTHESE )NTHEJARFILE YOUCANINCLUDE ß A class can inherit instance variables and
STATICGLOBAL LIKE THINGSARETHE ASIMPLETEXTFILEFORMATTEDAS methods from a more abstract superclass.
EXCEPTIONRATHERTHANTHERULE SOMETHINGCALLEDAMANIFEST THAT
IN*AVA4HEYREPRESENTAVERY DEFINESWHICHCLASSINTHATJAR ß At runtime, a Java program is nothing more
SPECIALCASE WHEREYOUDONT HOLDSTHEMAIN METHODTHAT than objects ‘talking’ to other objects.
HAVEMULTIPLEINSTANCESOBJECTS SHOULDRUN

you are here4 41


exercise: Be the Compiler

1dQ^OU_Q "%THECOMPILER
Each of the Java files on this page
represents a complete source file.
Your job is to play compiler and
determine whether each of
these files will compile.
If they won’t compile,
how would you fix them,
and if they do compile,
what would be their output?

A
class TapeDeck {

boolean canRecord = false; B


class DVDPlayer {
void playTape() {
System.out.println(“tape playing”); boolean canRecord = false;
}
void recordDVD() {
void recordTape() { System.out.println(“DVD recording”);
System.out.println(“tape recording”); }
} }
}
class DVDPlayerTestDrive {
class TapeDeckTestDrive { public static void main(String [] args) {
public static void main(String [] args) {
DVDPlayer d = new DVDPlayer();
t.canRecord = true; d.canRecord = true;
t.playTape(); d.playDVD();

if (t.canRecord == true) { if (d.canRecord == true) {


t.recordTape(); d.recordDVD();
} }
} }
} }

42 chapter 2
classes and objects

Code Magnets
1dQ^OU_Q !*AVAPROGRAMISALLSCRAMBLEDUPON
THEFRIDGE#ANYOURECONSTRUCTTHE
CODESNIPPETSTOMAKEAWORKING*AVA
PROGRAMTHATPRODUCESTHEOUTPUTLISTED d.playSnare();
BELOW3OMEOFTHECURLYBRACESFELLON
THEFLOORANDTHEYWERETOOSMALLTOPICK DrumKit d = new DrumKit();
UP SOFEELFREETOADDASMANYOFTHOSE
ASYOUNEED
= true;
boolean topHat
= true;
boolean snare

void playSnare() {
ang”);
System.out.println(“bang bang ba-b
}

public static void main(String [] args) {

if (d.s
nare == tr
ue) {
d.playS
nare();
}

d.snare = false;

class DrumKitTestDrive {

();
TopHat
d.play
class DrumKit {

void playTopH
at () {
System.out.p
rintln(“ding
ding da-ding”
File Edit Window Help Dance
} );
% java DrumKitTestDrive
bang bang ba-bang
ding ding da-ding

you are here4 43


puzzle: Pool Puzzle

public class EchoTestDrive {


public static void main(String [] args) {
Echo e1 = new Echo();
_________________________
Pool Puzzle int x = 0;
9OURJOBISTOTAKECODESNIPPETSFROM while ( ___________ ) {
THEPOOLANDPLACETHEMINTOTHE
BLANKLINESINTHECODE9OUMAY e1.hello();
USETHESAMESNIPPETMORETHAN __________________________
ONCE ANDYOUWONTNEEDTOUSE
if ( ____________ ) {
ALLTHESNIPPETS9OURGOALISTO
MAKECLASSESTHATWILLCOMPILEAND e2.count = e2.count + 1;
RUNANDPRODUCETHEOUTPUTLISTED }
if ( ____________ ) {
/UTPUT e2.count = e2.count + e1.count;
File Edit Window Help Implode }
%java EchoTestDrive x = x + 1;
helloooo... }
helloooo... System.out.println(e2.count);
helloooo... }
helloooo... }

10
class ____________ {
int _________ = 0;
void ___________ {
"ONUS1UESTION
System.out.println(“helloooo... “);
)FTHELASTLINEOFOUTPUTWAS }
INSTEADOFHOWWOULD }
YOUCOMPLETETHEPUZZLE

.OTE%ACHSNIPPET
FROMTHEPOOLCANBE
USEDMORETHANONCE
X X
Y X %CHO
E X 4ESTER
COUNT X ECHO EE
EE  COUNT %CHOE
ECOUNT  HELLO %CHOEE
%CHOENEW%CHO  X
ECOUNTCOUNT 
X
ECOUNTECOUNT 

44 chapter 2
classes and objects

!BUNCHOF*AVACOMPONENTS INFULLCOSTUME AREPLAYINGAPARTY


GAME h7HOAM)v4HEYGIVEYOUACLUE ANDYOUTRYTOGUESSWHO
THEYARE BASEDONWHATTHEYSAY!SSUMETHEYALWAYSTELLTHETRUTH
ABOUTTHEMSELVES)FTHEYHAPPENTOSAYSOMETHINGTHATCOULDBETRUE
FORMORETHANONEOFTHEM CHOOSEALLFORWHOMTHATSENTENCECAN

m I ? APPLY&ILLINTHEBLANKSNEXTTOTHESENTENCEWITHTHENAMESOFONEOR
MOREATTENDEES4HEFIRSTONESONUS

ho a 4ONIGHTSATTENDEES
W #LASS-ETHOD/BJECT)NSTANCEVARIABLE

I am compiled from a .java file. class


My instance variable values can
be different from my buddy’s
values.

I behave like a template.

I like to do stuff.

I can have many methods.

I represent ‘state’.

I have behaviors.

I am located in objects.

I live on the heap.

I am used to create object instances.

My state can change.

I declare methods.

I can change at runtime.

you are here4 45


exercise solutions

Be the Compiler:
1dQ^OU_Q class TapeDeck {
boolean canRecord = false;
%XERCISE3OLUTIONS void playTape() {
System.out.println(“tape playing”);
A }
void recordTape() {
System.out.println(“tape recording”);
}
}

Code Magnets: class TapeDeckTestDrive {


public static void main(String [] args) {
class DrumKit {
TapeDeck t = new TapeDeck( );
boolean topHat = true; t.canRecord = true;
boolean snare = true; t.playTape();

void playTopHat() { if (t.canRecord == true) {


System.out.println(“ding ding da-ding”); t.recordTape();
} }
} We’ve got the template, now we have
void playSnare() { } to make an object !
System.out.println(“bang bang ba-bang”);
}
}
class DVDPlayer {
boolean canRecord = false;
class DrumKitTestDrive {
void recordDVD() {
public static void main(String [] args) {
System.out.println(“DVD recording”);
}
DrumKit d = new DrumKit();
void playDVD ( ) {
d.playSnare();
System.out.println(“DVD playing”);
d.snare = false;
}
d.playTopHat();
}
if (d.snare == true) {
class DVDPlayerTestDrive {
d.playSnare();
public static void main(String [] args) {
}
DVDPlayer d = new DVDPlayer();
}
B d.canRecord = true;
}
d.playDVD();
if (d.canRecord == true) {
File Edit Window Help Dance
d.recordDVD();
% java DrumKitTestDrive
}
bang bang ba-bang
ding ding da-ding
} The line: d.playDVD( ); wouldn’t
} compile without a method !

46 chapter 2
classes and objects

0UZZLE3OLUTIONS

Pool Puzzle
public class EchoTestDrive {
public static void main(String [] args) { 7HOAM)
Echo e1 = new Echo();
Echo e2 = new Echo( ); // the correct answer I am compiled from a .java file. class
- or - My instance variable values can be
Echo e2 = e1; // is the bonus answer! different from my buddy’s values. object
int x = 0;
while ( x < 4 ) {
I behave like a template. class
e1.hello(); I like to do stuff. object, method
e1.count = e1.count + 1;
if ( x == 3 ) {
I can have many methods. class, object
e2.count = e2.count + 1; I represent ‘state’. instance variable
}
if ( x > 0 ) {
I have behaviors. object, class
e2.count = e2.count + e1.count; I am located in objects. method, instance variable
}
x = x + 1; I live on the heap. object
} I am used to create object
System.out.println(e2.count); instances. class
}
} My state can change. object, instance variable
I declare methods. class
class Echo {
int count = 0; I can change at runtime. object, instance variable
void hello( ) {
System.out.println(“helloooo... “); Note: both classes and objects are said to have state and behavior.
} They’re defined in the class, but the object is also said to ‘have’
} them. Right now, we don’t care where they technically live.

File Edit Window Help Assimilate


%java EchoTestDrive
helloooo...
helloooo...
helloooo...
helloooo...
10

you are here4 47


3 primitives and references

Know Your Variables

Variables come in two flavors: primitive and reference. So far you've

used variables In two places-as object state (instance variables), and as local variables

(variables declared within a method) . Later, we'll use variables as arguments (values sent to a

method by the calling code), and as return types (values sent back to the caller of the method).

You've seen variables declared as simpie prj m IUve integer vaIues (type in c). You've seen

variables declared as something more complex like a String or an array. But there's gotta be
more to life than integers, Strings, and arrays.What If you have a PetOwner object with a Dog

instance variable? Or a Car with an Engine? In this chapter we'll unwrap the mysteries of Java

types and look at what you can declare as a variable, what you can pur In a variable, and what you

can do with a variable. And we'll finally see what life Is truly like on the garbage-collectible heap.

this Is a new chapter 49


declaring a variable

Peclarittg avariable
Java cares about type. It won't let you do
something bizarre and dangerous like stuff a
Giraffe reference into a Rabbit variable-what
happens when someone tries to ask the so-called
Rabbit to hop ()? And it won't let you put a
floating point number into an integer variable,
unless you lKknowledge to thecompiler that you
know you might lose precision (like, everything
after the decimal point).
The compiler can spot most problems:
Rabbit hopper = new Giraffe();
Don't expect that to compile. Thankfully .
For all this type-safety to work, you must declare
the type of your variable. Is it an integer? a Dog?
A single character? Variables come in two flavors:
primitive and object reference. Primitives hold
fundamental values (think: simple bit patterns)
including integers, booleans, and floating point
numbers. Object references hold. well, references
to objects (gee, didn't that clear it up.)
We'Ulook at primitives first and then move
on to what an object reference really means.
But regardless of the type, you must foUow two
declaration rules:

variables must have a type


Besides a type, a variable needs a name, so that
you can use that name in code.

variables must have a name

int count;
;?1 <,
type na.....e

Note: When you see a statement like: "an object


of type X", think of l)'Peand classes synonyms.
(We'll refine that a little more in later chapters.)

50 chapter 3
primitives and references

Primitive Types
n you think ofJava variables, think of cups. Coffee cups, tea cups, giant Type Bit Depth Value Range
that hold lots and lots of beer, those big cups the popcorn comes in at boolean and char
movies, cups with curvy, sexy handles, and cups with metallic trim that
learned can never, ever go in the microwave. boolean (JVM .. pedfic) true or false

wariable is just a cup. A container. It holds something. char 16 bits 0 to 65535

a size, and a type. In this chapter, we're going to look first at the numeric (all are signed)
- bles (cups) that hold primitives, then a little later we'll look at cups Integer
hold references to objects. Stay with us here on the whole cup analogy-as
byte 8 bits -128 to 127
pie as it is right now, it'll give us a common way to look at things when
discussion gets more complex. And that'll happen soon. short 16 bits -32768 to
32767
- itives are like the cups they have at the coffeehouse. If you've been to a
int 32 bits -2147483648
ucks, you know what we're talking about here. They come in different
and each has a name like 'short', 'tall', and, "I'd like a to 2147483647
de' mocha half-eaffwith extra whipped cream". long 64 bits -huge to huge
migh t see the cups displayed on the counter,
u can order appropriately: floating point
float 32 bits varies
double 64 bits varies

Primitive declarations
small short tall grande
with assignments:
Int ){i
--'!II" And inJava, primitives come in different sizes, and those sizes
have names. When you declare a variable in Java, x = 234;
E ::a-YoU must declare it with a specific type. The byte b = 89;
I four containers here are for the four boolean isfun = true;
integer primitives in Java.
double d = 3456,98j
char c ='f'j
fang int short byte lnt z e x:
cup holds a value, so for Java primitives, rather than saying, "I'd like a boolean IsPunkRock;
french roast", you say to the compiler, "I'd like an int variable with the
isPunkRock = false;
ber 90 please." Except for one tiny difference ... in Java you also have to
your cup a name. So it's actually, "I'd like an int please, with the value boolean powerOn;
:H86, and name the variable height." Each primitive variable has a fixed powerOn = IsFun;
ber of bits (cup size). The sizes for the six numeric primitives inJava long big = 3456789j
shown below:
float f = 32.5i

.( qatta "a~t -that


Nott tht ~ btU\,<St ja~a thi"~
..,i-th a ~\. ~\oab~ foi"t I~
byte short int long float double '"'ythi,,~ 'fI1-th a \,<St '~'.
8 16 32 64 32 64 a ci~\e, "",\65 'fO'#

you are here ~ 51


prlmltlve assignment

You really dot1~t wat1t to spill that...


Be sure the value can fit into the variable.
You can't put a large value into a
small cup. The compiler won't let you put
a value from a large cup into
WeU, OK, you can, but you'll a small one. But what about
lose some. You'll get, as we say, the other way-pouring a
spillage. The compiler tries to small cup into a big one7 No
help prevent this ifit can tell problem.
from your code that something's Basedon what you know
not going to fit in the container about the size and type of the
(variable/cup) you're using. pri mitive va rlables, see if you
can figure out which of these
For example, you can't pour an are legal and which aren't,
int-full of stuff into a byte-sized We haven't covered all the
container, as follows: rules yet, so on some of these
you'll have to use your best
int x = 24;
judgment. Tip: The compiler
byte b = x; always errs on the side of
safety.
//won't work!!

From the following list Circle


the statements that would be
Why doesn't this work, you ask? After all, the value of x is 24, and 24 is definitely
legal if these lines were in a
small enough to fit into a byte. You know that, and we know that, but all the single method:
compiler cares about is that you're trying to put a big thing into a small thing.
and there's the possibility of spilling. Don't expect the compiler to know what the 1. int x = 34.5;
value of xis. even if you happen to be able to see it literally in your code. 2 . boolean boo x;
You can assign a value to a variable in one of several ways including:
3 . int g = 17;
• type a litera/value after the equals sign (x=12. isGood = true, etc.)
4. int y '" 9;
• assign the value of one variable to another (x =y)
5 . Y = Y + 10;
• use an expression combining the two (x = y + 43)
In the examples below, the literal values are in bold italics: 6. short s;

int size = 32; declare an int named size, assIgn ilthe value 32 7. s = y;
char initial = 'j'; declare a char named initial, assign itlhe value T 8. byte b = 3;
double d = 456.709; declare a double named d, assign it the value 456.709
9 . byte v = b;
boolean isCrazy; declare a boolean named IsCrazy (no assignment)
10. short n '" 12;
isCrazy true; assign the value true to thepreviously-declared ;sCrazy
int y = x + 456; declare an int named y, assign Itlhe value that is the sum 11. v '" n ;
of whatever x is now plus 456
12. byte k 128;

52 chapter 3
prlmitJves and references

Jack away frotH that keyword!


lbu know you need a name and a type for your variables.
YOu already know the primitive types.
. , what can you we as names? The rules are simple. You
an name a class, method, or variable according to the
owing rules (the real rules are slightly more flexible,
t these will keep you safe) :
ftIfIeS ote:
. ' b\e
• It must start with a letter, underscore U, or , /'It primitIve '7" float do U .
dollar algn ($). You can't atart a name with a The elg e s\"lOft lot long . t/'lem:
number. eao char byt membermg
boO\ onic for re
, om nem
• After the first character, you can u. . numbers as And here S , gest urge
S u\dn't n
well. Just don't atart It with a number, CafefU\~ 8ea's \"10
• It can be anything you like, subject to those two
8e bertet.
furry Oogs 't'll stick even
rules, JU8t 80 long as It Isn't one of Java's reserved out own, I
words. It yoU make up Y D
S I LF- -
B_ c- B_ - -

public static void

And the primitive types are reserved as well:

boolean char byte short int long floa.t double


t there are a lot more we haven't discussed yet. Even if you don't
ed to know what they mean, you still need to know you can 't use
'em yourself. Do not-under any circumstances-try to memorize these
.w. To make room for these in your head, you'd probably have to
something else . Like where your car is parked. Don't worry, by
the end of the book you'll have most of them down cold.

fhls table reserved.


boolean byte mar double flom Inl long
protected abstract flnal native storic strictfp syndJronlzed transient If
else do while swllm case delauh for break continue assart
doss ex1and~ implements import rnstanceof interface new package super this
catch flnol~ try throw throws return void canst gala enum
Java's keywords and other reserved words (In no useful order). If you use these for names, the complier will be very, vel}' upset.

you are here I 53


object references

Controlling your ~og object


You know how to declare a primitive variable and assign it a
value . But now what about non-primitive variables? In other
words, what about objects? Dog d = new Dog();
d.bark();
• There Is actually no such thing as an object variable.
• There's only an object reference variable. \ thi.k ot this
• An object reference variable holds bits that represent a
way to access an object.
• It doesn't hold the object Itsetf, but It holds something
like a pointer. Or an address. Except., in Java we don't
really know what Is Inside a reference variable. We do
know that whatever It Is, It represents one and only one
object. And the JVM knows how to use the reference to
get to the object.

You can ' 1 stuff an object into a variable. We often think of


it that way... we say things like, "I passed the String to the
System.out.printlnf) method." Or, "The method returns a Dog",
or, "I put a new Foo object into the variable named rnyf'oo."
But that's not what happens. There aren't giant
expandable cups that can grow to the size of any Thillk o-f a D~
object. Objects live in one place and one place referente vdl'iable al
only-the garbage collectible heap! (You'll
learn more about that later in this chapter) a D~ l'en-ote to.\h-ol.
Although a primitive variable is full of You. IUC it to ~tt -t\l~
bits representing the actual value of the
objut to do ~tthill9
variable, an object reference variable is full
of bits representing a way to get to the (h'IVolcc ",et.h~) .
obJect.
You use the dot operator (.)
on a reference variable 10 say,
"use the thing before the dot to
get me the thing after the dot." For
example:
myDog.bark() ;
means, "use the object referenced by the variable myDog to
invoke the barkt) method." When you use the dot operator on
an object reference variable, think of it like pressing a button
on the remote control for that object.

54 chapter 3
primitives and references

The 3 steps of object


declaration, creation and
assignment

1 2
~3~
byte short int long reference
Dog myDog = new Dog();
8 16 32 64 Ibll depth not relevant)

At1 object referet1ce is just Declare a reference


a"other variable value. O variable
Something that goes In a cup. Doq myDoq = new Dog () ;
Only this time, the value 15 a remote control. Tells the JVM to allocate space for a
reference variable, and names that
Prhldtlve Variable ~\.\. variable myDog. The reference variable

J~itive
Is, forever. of type Dog.ln other words,
byte x = 7; a remote control that has buttons to
the bits representing 7 go
to the variable. (00000111),
Ubyte
vall.4t
control a Dog, but not a Cat or a Button
or a Socket.
Dog

e Create an object
Dog myDog '" new Dog () ;
Dog myDog = new Doq() ;
Tells the JVM to allocate space for a
new Dog object on the heap (we'll
learn a lot more about that process,
especially in chapter 9,)
Dog object

e Link the object


and the reference
Dog myDog = new Dog () ;
Assigns the new Dog to the reference
variable myDog.ln other words,
programs the remote control,

Dog object

~n care how meny t's and O's tho,o are In a (afare~08l1tlriabla lrs UP10 a&eh
: " a."ld Ihe phase of Ihe moon , Dog
you are he re . 55
object references

,
D:therel~o
.
"
ume ~uest19115 Java,£Nposecl
Q: How big 15 a reference This week's Interview:
variable?
Object Reference

A. :Vou don't know. Unless


you're cozy with someone on the
HeadFirst So, tell us, what's life likefor an object reference?
Reference: Pretty simple, really. I'm a remote control and I can be programmed to
JVM's development team, you control different objects.
don't know how a reference is
HeadArst Do you mean different objects even while you're running? Like, can you
represented. There are pointers
in there somewhere, but you refer to a Dog and then five minutes later refer to a Car?
can't access them .You won't Reference: or course not- Once I'm declared, that's it. If I'm a Dog remote control
need to. (OK, Ifyou Inslst, you then ru never be able to point (oops- my bad, we're not supposed to say poin~ I mean rifer
might as well Just imagine It to anything but a Dog.
to be a 54-bit value.) But when
you're talking about memory HeadFirst Does that mean you can refer to only one Dog?
allocation issues, your Big
Reference: No. I can be referring to one Dog, and then five minutes later I can refer to
Concern should be about how
many objects (as oppose-d to some other Dog. As long as it's a Dog, I can be redirected (like reprogranuning your remote
object references) you're creating, to a different TV) to it. Unless... no never mind.
and how big they (the objects) HeadFirst No, tell me. What were you gonna say?
really are.
Reference: I don't think you want to get into this now, but I'lljust giveyou the short
version - if I'm maned as final, then once I am assigned a Dog, I can never be repro-
grammed to anything else but I1ul1 one and only Dog: In other words, no other object can
Q:So, does that mean that be assigned to me.
all object references are the HeadFirst You're right, we don't want to talk about that now. OK, sounless you're
same size, regardless of the size final, then you can refer to one Dog and then refer to a differentDog later. Can you ever
of the actua I objects to which
refer to fIl)tJring at alP. Is it possible to not be programmed to anything?
they refer?
Reference: Yes, but it disturbs me to talk about it.

A.: Yep. All references for a


given NM will be the same
HeadArst Why is that?
Reference: Because it means I'm null, and that's upsetting to me.
size regardless of the objects
HeadFirst You mean. because then you have no value?
they reference, but each JVM
might have a different way of Reference: Oh, null isa value. I'm stilla remote control, but it's like you brought
representing references, so home a new universal remote control and you don't have a TV I'm not programmed to
references on one JVM may be control anything. They can press my buttons all day long, but nothing good happens. I
smaller or larger than references just feel so... useless. A waste of bits. Granted, not that many bits, but still. And that's not
on another JVM.
the worst part. If I am the only reference to a panicular object, and then I'm set to null
(deprogrammed), it means that now rwboqy can get to that object I had been referring to.
Q:can I do arithmetic on a HeadFirst And that's bad because...
reference variable, Increment It
you know - C stuff7 Reference: You have to ask? Here I've developed a relationship with thisobject, an
intimate connection, and then the tie issuddenly, cruelly, severed. And I will never see

A.: Nope. Say It with me again,


"Java Is not C."
that object again, because now it's eligible for [producer, cue.tragic music) garbage collection.
Sniff. But do you think programmers ever consider !haP. Snif. Why, wIrY can't I be a primi-
tive? I hate being a refcrcut. The responsibility, all the broken attachments...

56 chapter 3
primitives and references

ott the garbage..collectible heap

= new Book();
= new Book();
e two Book reference
- les.Create two new Book
. Assig n the Book objects to
reference variables.
Book
two Book objects are now living
e heap.

Obiects: 2
Book
Book d = c;
re a new Book reference variable.
r than creating a new, third Book
•assign the value of variable c to
. ble d. But what does th is mean?
li ke saying, "Take the bits In c, make a
of them, and stick that copy Into d."
..... c and d refer to the same
....ect.
The c and d variables hold
Book
two dlHerent copies of the
. .me value. Two remotes
.....grammed to one TV.
ferences: 3
Objects: 2
Book
c = h;
Assign the value of variable b to
variab le c. By now you know what
is means. The bits inside variable
at are copied, and that new copy Is
stuffed into variable c.
Both band c refer to the
same object.
References: 3
Objects : 2

you are here ~ 57


objects on the heap

Ufe a.,d death 0., the heap


Book b = new Book() ;
Book c = new Book() i
Declare two Book reference variables.
Create two new Book objects. Assign
the Book objects to the reference
variables.
The two book objects are now living
on the heap.
ActIve References: 2
Reachable Objects: 2
Book
b = Ci
Assign the value of variable c to variable b.
The bits Inside variable c are copied, and
that new copy is stuffed Into variable b.
Both variables hold identical values.
Both band c refer to the ••me
object. Object 1 I. abandoned
and eligible for Garbage Collec-
tion (GC).
Active References: 2
Reachable Objects: 1
Abandoned Objects: 1
The first object that b referenced, Object 1,
has no more references. It's unreachable.

C = null;
Assign the value nu 11 to variable c.
This makes c a null reference, meaning
It doesn't refer to anything. But It's still
a reference variable, and another Book
object can stili be assigned to It .
Object 2 .tlll h •• an active
reference (b), and •• long
as It does, the object I. not
eligible for GC.
ActIve References: 1
null References: 1
Reachable Objects: 1
Abandoned Objects: 1
Book
68 chapter 3
primitives and references

An array is like atray of cups


o Declare an int array verinble. An array variable is
a remote control to an array object.
int[] nums;

Create a new int array with a length


of 7 and assign it to the previously-
I

declared int r J variable nums

nums = new int[7] ;

Give each element in the array


an int value.
Remember, elements in on int
array are just int variables.

~
.:is
.3'
nums [0] = 6;
~
~ nums[l] = 19 ;
~
·s nums[2] = 44:
nums[3] = 42: int array object (int[])
nums [4] = 10:
nums[5] = 20;
nums [6] ='1; int[] Notit~ that. -tne a'rYa'f ihtlt is dl'l objtd:,
evel'l t.h~h ~e I tltMtl'lt.s art f\"i",j·I:.'Ives.

Arrays are objects too


Java standard library includes reference variable. Anything you Be sure to notice one key thing
of sophisticated data structures would put in a variable of that rype in the picture above - the arm)' is
uding maps, trees. and sets can be assigned to an array element an object, even though it's an array of
Appendix B). but arrays are of that type. So in an array of type primitives.
t when you just want a quick. int (int[]) . each element can hold
Arrays are always objects, whether
red, efficient list of things. an int, In a Dog array (Dog[]) each they're declared to bold primitives
,"'5 give you fast random element can hold... a Dog? No. or object references. But you can
ess by letting you use an index remember that a reference variable have an array object that's declared
ition to get to any element in just holds a reference (a remote to hold primitive values. In other
array. control), not the object itself. So words, the array object can have
in a Dog array, each element can elements which are primitives. but
ry element in an array isjust
hold a remote control to a Dog. Of the array itself is nevera primi tive,
nriable. In other words, one of
course, we still have to make the Regardless of what the array holds,
eight primitive variable types
. k: Large Furry Dog) or a Dog objects... and you'll see all that the array itself is always an objectl
on the next page.
you are here. 59
an array of objects

Make att array of Pogs

o Declare a Dog array variable


Dog[] pets;

A Create a new Dog array with


W a length of 7, and assign it to
the previously-declared Dog [J
variable pets

pets = new D09[7];

What~ .ttfsShtg1
Dogsl We have an array
of Dog rmrence$, but no
actual Dog obJects I
Dog array object (Dog[])

A Create new Dog objects, and


V assign them to the array
elements.
Remember, elements in a Dog
array are just Dog reference
variables. We still need Dogs!

pets[D] = new Dog();


pets[l] = new Dog();

_~~~~i:/_t
n,~~:':~:f
--~dmake
_
-ne ofthe
11 objects? Dog array object (Dog[])

58 (.. .r 3
primitives and references

, name
Dog Cot1trol your ~og
(with a referetlce variable)
barkO
Dog fide = new Dog();
eatO fido.name = ~FidoN;
chaseCalO
We created a Dog object and
used the dot operator on the
reference variable fido to access
the name variable."
We can use the fido reference
to get the dog to barkt) or
eat/) or chaseCatO .
fido.bark() i Dog
Java cares about type. fido .chaseCat();
Once you've declared an array. you
can't put anything an It except thing-
that are of the declared array type.
What happetts ifthe POQ is Itt
For example, you can't put Q COt into a Dog
a OOQ array?
array (it would be pretty awful if someone ~e know we can access the Dog's
thinks that only Dogs are inthe orrat, so Instance variables and methods using
the.y ask eoch one to ~ark, and th~n to their the dot operator, but em what1
horror discoverthere s a cat lurkmg.) And
you can't stick a double into on int orr'atl When the Dog is in an array, we don't
(spillage., remember?). You can, however. have an actual variable name (like
put Qbyte into on in t arraf, b~QuSe a fido). Instead we use array notation and
byte will always fit into on int-SIZed cup. push the remote control button (dot
This is known as an Implicit wid&ning. We''' ~perator) on an object at a particular
gat Into the details tater. for now just Index (position) in the array:
remember that the compiler won't 1st you
put the wrM'9 thing In on orraf, based on Dog[] myDogs = new Dog[3];
the Gtf'OY's d&elored type. myDogs[O] = new Dog() ;
myDogs[O].name = "Fido";
myDogs[O] .bark();

'Yes weknow we're notdemonslralin -


trying tokeep it simple. For now. We'1IgdencapsuiatiOn he_reo butwe're
0 encapsulation 10 chapter 4.

you are here ~ 61


using references

class Dog (
Str ing name ; A Pog exatMple
publ i c static void main (String() args) Dog
II make a Dog ob ject and a c cess it
name
Dog dogl = new Dog();
dogl.bark{) ; barkO
eatO
dogl.name = "Bart" ;
chaseCal()

I I now mak e a Dog ar ra y


Dog() myDogs = new Dog[3); Output
I I a nd put s ome dog s i n i~

myDogs[O ) ne w Dog () ;
myDogs[l ) new Dog () ;
myDogs [2 ) dog!;

/1 now Rece s s t he Dogs u s i ng t he ar r a y


I I r e f e r e nce s
myDogs(O).name " Fr e d " ;
myDogs(l).narne "Marge " ;

II Hmmnm . . . wha t i s myDogs (2 j name?


System.out .print( "!ast dog's name is ");
Sys t em. ou t . pr in t l n (myDogs (2) . narne ) ;
• Variables come intwo flavors: primitive and
II now 100 t hr ough t he a r r y reference.
I I a nd t e l l all dog s t o ba rk • Variables must always be declared with aname
and a type.
i nt x = 0;
mYDOgs .1ength)~
• Aprimitive variable value isthe bits representing
whi1e(x < J
the value (5, 'a', true, 3.1416, etc.).
myDogs [xl .ba r k () ; a \/aYiab\c l'~~ • Areference variable value isthe bits
x = X + 1; ay-yii'(S ha\/C t."c l'I~bCl" representing away to get to an object on the
t)lat. ~\\/ts 'lOlA a'J heap.
L' t,\lc jlY"Y I
e\e,.,.tf\'V 11'1
• Areference variable is like aremote control.
Using the dot operator (.) on a reference
variable islike pressing a button on the remole
pUblic void bark() (
control to access amethod orinstance variable.
System.out.prin tln(narne i- " says Ruff !");
• Areference variable has a value of n u 11 when
it is not referencing any object
pUblic vo i d ea t ( ) { • An array is always an object, even if the" array
p ub lic voi d c ha s e Ca t () isdeclared to hold primitives" There is no such
thing as a primitive array, only an array that
holds primitives.

62 chapter 3
prlmltlves and references

BE the cornriler
Each of the Java nles on this page
represents a cOtIlplete source file.
Your job is to play compiler and
detel"llline whether each of these files
will compile. If they won't
cmqpile, how would rOll
fIX them?

A B
class Books { class Hobbits {
String title;
String author; String name;
}
public static void main(String (J args) {
class BooksTestDrive
public static void main(String Ij args) Hobbits () h = new Hobbits[3]i
int z = 0;
Books () myBooks :: new Books(3);
int x :: 0; while (z < 4) {
myBooks{Oj.title :: "The Grapes of Java"; z = z + 1;
myBooks(lj.title = ~The Java Gatsby"i hlz] :: new Hobbits();
myBooks(2).title :: ~The Java Cookbook"; h{z] .name = "bilbo"i
myBooksIO).author = "bob"; if (z == I) {
myBooksllj.author:: "sue"; hlz].name:: "frodo";
myBooks(2).author = "ian"; }
if(z==2){
wbile (x < 3) { h[z).name = Usam";
System.ou t.print(myBookslxj.title)i
System.out.print(" by U)i System.out.print (h{z).name + " is a H);
System.out.println(rnyBooks[xj.author) ; System.out.println(Ugood Hobbit name");
x = x + 1;
} }

you are here. 63


exercise: Code Magnets

Code Magnets
Aworking Java program Is all scrambled up int Y ==
on the fridge. Can you reconstruct the code
snippets to make a working Java program index(y) ;
that produces the output listed below?
Some of the curly braces fell on the floor
and they were too small to pick up, so feel
free to add as many of those as you need!

int ref;
while (y < 4) {

System.out.print1n(islands{refj)i

index(Ol .,. 1;
index(ll '" 3;
index (21 == 0;
index[31 .,. 2; ~

String (] islands new String(4)i

System.out.print(Uisland ; U);

int [1 index ""


new int[4Ji
y y + 1;

class TestArrays {

public static void main(Strin N


":J rJ args) {

64 chapter 3
primitives and references

class Triangle
double arear
int height;
pool puzzle iot length;
public static void main(String [] args)
Your Job is to take code snippets from
the pool and place them into the
blank lines in the code. You may
use the same snippet more than while ( ) {
once, and you won't need to use
all the snippets .Your gOlll is to _______ .height (x + 1) * 2:
make a class that will compile and
run and produce the output listed. _______ .leogth x + 4:

System.out.print( "triangle "+x+" I area"};


Output
System.out.println(" =" + .area):

x = 27:
Triangle tS = ta[2]:
ta[2J.area = 343:
System.out.print(uy = U + y):
System.out.println(", tS area = "+ tS.area};
Bonus Questlonl }
For extra bonus points, use snippets void setArea() {
from the pool to fill in the missing
output (above). (height * length) / 2;
}
} Note: Each lnlppet
from the pool nn be
used more than oncel

yo u are here ~ 65
puzzle: Heap o' Trouble

class HeapQuiz {
int id == 0;
A Heap 0' Trouble public static void main(String [] argsl
int x = 0;
A short Java program is listed to the
HeapQuiz ( ] hq = new HeapQuiz(S]i
right. When '/1 do stuff' is reached, some
objects and some reference variables while ( x < 3 1 (
will have been created. Your task Is hq[x) = new HeapQuiz();
to determine which of the reference hq(x] . id == Xi
variables refer to which objects. Not all x = X + 1i
th e reference variables will be used, and
}
some objects might be referred to more
than once. Draw lines connecting the hq[3] == hq[l]i
reference variables with their matching hq[4] hq[l] ;
objects. hq[3] = null;
Tip: Unless you 're way smarter than us, hq (4) hq (0] ;
you probably need to draw diagrams hq(Ol == hq(31i
like the ones on page 55 and 56 of th is
hq(3] hq[2];
chapter. Use a pencil so you can draw
and then erase reference li nks (the hq[2] = hq [0] ;
arrows goIng from a reference remote II do stuff
control to an object).

Reference Variables: HeapQulz Objects:

hq[O]

hq[1]

hq[2]

10

~~
hq[3]

hq[4]
ftil
64 chapter 3
primitives and references

The case of the pilfered references

It was a clark and stormy night Tawny strolled into the programmers' bullpen like she
owned the place. She knew that all the programmerswould still be hard at work, and she
wanted help. She needed a new method added to the pivotal class that was to be loaded into the
client's new top-secretJava-enabledcell phone. Heap space in the cell phone's memory was
as tight as Tawny's top, and everyone knew it The normally raucous buzz in the bullpen fell to
silence as Tawny eased her way to the white board. She sketched a quick overview of the new
method's functionality and slowly scanned the room. 'Well boys, it's cnmch time", she purred.
'Whoever creates the most memory efficientversion ofthis method is coming with me to the
client's launch party on Maui tomorrow... to help me install the new software."
The next morning Tawny glided into the bullpen wearing her short Aloha dress.
"Gentlemen", she smiled, "the plane leaves in a few hours, show me what you've
got!". Bob went first; as he began to sketch his design on the white board Tawny
said, "Let's get to the point Bob, show me how you handled updating the list of con-
tact objects." Bob quickly drew a code fragmenton the board:

Contact I) ca = new Contact[10];


while ( x < 10 ) { II make 10 contact objects
calx) new Contact()i
x = x + 1;

II do complicated Contact list updating stuff with ca

"Tawny r know we're tight on memory,but your spec said that we had to be able to access
individualcontact informationfor all ten allowablecontacts, this was the best scheme I could
cookup", said Bob. Kent was next, already imagining coconut cocktails with Tawny, "Bob,"
he said, "your solution's a bit kludgy don't you think?" Kent smirked,"Take a look at this
baby":

Contact. refc;
while ( x < 10 ) { II make 10 contact. objects
refe = new Cont.act()i
x = x + 1;
I
II do complicated Contact list updating stuff with rete

"I saved a bunch of reference variables worth ofmemory,Bob-o-rino, so put away your
sunscreen", mocked Kent "Not so fast Kent!", said Tawny, "you've saved a little memory, but
Bob's coming with me.''.

Why did Tawny choose Bob's method over Kent's, when Kent's used Jess memory?

you are here t 67


exercise solutions

class Books {
Exercise Solutions String title;
String autbor;

class BooksTestDrive (
public static void main{String I) args)
Books II myBooks = new Books(3);
int x = 0:
A myBooks[O] :: ntw 9ooksO; IUrnanber: We hGvt to
Code Magnets: myBooks[1] :: ntw BooksO: actuclily InQJc.e the BooI<s
myBooks[2] :: new BooksO: objects I ~~----=- ----l

class TestArrays myBooksIO].title = uThe Grapes of Java';


myBooksll] .title = "The Java Gatsby·;
pUblic static void main(String () args) {
myBooks[2].title = NThe Java Cookbook';
int [) index = new int{4]:
myBooks[O].author = Nbob';
index[O) I: myBooks[l].author = Nsue";
Lndex] 1) 3: myBooks[2].author = "ian";
index[ 2) 0: while (x < 3) {
index(3) 2; System.out.print(myBoOks(x).title)i
String (] islands = new String[4]: System.out.print(" by ")j
system.out.println(myBooks[x).author);
islandslO] "Bermuda":
x e X + 1;
islandsjl] = "Fiji";
islands(2] "Azores H :

islands{3] "Cozumel";
int y = 0:
class Hobbits {
int ref;
String name:
while (y < 4) {
public static void main{String I) args) {
ref = index(yl;
Hobbits () h = ne_w=--H..:.ob::..:b7i:...:t..:.s~(3:....:)~: ~,....,....-,
system.out.print("island = H); Int :z :: -1; I
Remember: o.rrcys start with
System.out.println(islandslref]l; whfle (z ( 2) ( element 0 )
y = y + 1; z = z + 1i ------------

}
h[z] = new Hobbits{):
B h[z].name = "bilbo';
if (z == 1) {
} b[z].name = "frodo"j
)
if(z==2){
b[z].name = "sam";
}
System.out.print(hlz).name + " is a H);
system.out.println{"good 80bbit nameH)j

68 chapter 3
primitives and references

Puzzle Solutions

The case of the pilfered references

class Triangle Tawny could see that Kent's method had a serious
double area; flaw. It's true that he didn't use as many reference
int height; variables as Bob , but there was no way to access any
int length, but the last of the Contact objects that his method cre-
public static void main(String [1 argB) {
lnt x = 0:
ated. With each trip through the loop, he was assign -
Triangle [ ] tel = new Trlangle[4]; ing a new object to the one reference variable, so the
while ( x • 4 ) { previously referenced object was abandoned on the
tel[x] =new Tr/ClllglcQ; heap - unreachable. Without access to nine of the ten
~x].he19ht ~ (x + 1) * 2; objects created, Kent's method was useless.
talx]. length =x + 4; (The software was 8 huge success atKl the dlent gave Tawny and Bob anextra week
talx) . set.Arec(); In Hawa~. we'dlike to ~ you that byfinishing this book you too wil get stuff like IhaL)
System.out.print(~triangle ~+X+". area"),
System.ouLprintln(U - N + talx).area);
x=x+1; HeapQulz Objects:
Reference Variables:
}
Int 'I = x:
x - 27;
Triangle tS ~ ta[2J;
ts[2J.area = 343; hq[O]
Syatem.out.print(Ny = U + Y);
System .out.println(", tS area " U+ tS.area);
}
void setArea() {
~ = (height· length) J 2;

~
;, java Triangle
triangle 0, area 4.0
triangle 1. area 10 .0
criangle 2 , area 19 .0
triangle 3 , area 28.0
'i = 4, t5 arca = 343

you are here ~ 69


4 methods use Instance variables

How Objects Behave

State affects behavior, behavior affects state. We know that objects

have state and behavior, represented by Instance variables and methods. But until now, we

haven't looked at how state and behavior are related . We already know that each instance of a

class (each object of a particular type) can have its own unique values for its instance variables.

Dog A can have a name "Fido" and a weight of 70 pounds. Dog B Is"Killer" and weighs 9 pounds.

And If the Dog class has a method makeNoiseO,well , don't you think a 70-pound dog barks a

bit deeper than the little 9-pounder7 (Assuming that annoying ylppy sound can be considered

a bark.) Fortunately, that's the whole point of an object-It has behavior that acts on its state. In

other words, methods use /nstllnn vllt/llb/Ift values . Like,"if dog Is less than 14 pounds, make

ylppy sound, else..." or "Increase weight by 5~ Let's go chllnge some stat«,

this Is a new chap ter 71


objects have state and behavior

RetMetMber: a class describes what an


object knows and what at1 object does
A class is the blueprint for an object. When you Song

write a class, you're describing how theJVM lt1stat1ce title kt10ws


should make an object of that type. You already variables artist
know that every object of that type can have (state)
different instance variable values. But what about setTItleO
the methods? 'Methods setArtlstO does
(behavior) playO
Ca" every object of that type have dlfferettt
lMethod behavior?
Well... sort cif.*
Every instance of a particular class has the same
methods, but the methods can behave differently
based on the value of the instance variables.
The Song class has two instance variables, title
and artist. The playO method plays a song. but
the instance you call playO on will play the song
represented by the value of the title instance
variable for that instance. So, if you call the playO
method on one instance you'll hear the song
"Politik", while another instance plays "Darkstar",
The method code, however, is the same.
void pla.y ( ) {
soundPlayer.playSound(title);
}

Song
Song t2 = new Song(); 83 .play () ;
t2.setArtist("Travis");
t2.setTitle("Sing");
Song s3 = new Song();
I
C-illi~ playO 0l'I this iflSta~te
s3.sstArtist("Sex Pistols"); will t4lASe "My W;Y:: to play.
s3 . setTi tie ("My Way") ;
(blAt PI~ the ~r.ab-a ~d

·Yes. another stunningly clearanswerl

72 chapter 4
methods use instance variables

esize affects the bark


AtlD3cIJ Dog's bark is different from a big Dog 's bark.
og class has an instance variable size, that the
me th od uses to decide what kind of bark sound

Dog
Dog (
s i ze ; size
name
;;: =':' ng name;
bark()
_:'0 ba r k () {
:.f (size> 60)
System .out.println("Wooof! Wooof!"};
el s e i f (size> 14) {
System ,out.println("RUff! Ruff!");
else (
System.out.println("Yip! Yip!-);

~: = s s DogTestDrive {

pub li c static void main (String! J args) {


Dog one = new Dog();
one.size = 70;
Dog two = new Dog();
two ,size = 8;
Dog three = new Dog();
three.size = 35;
~
~ j ava DogTestDrive
one. ba rk () ;
Wooof! Wooof I
two.bark () ;
'lip! Yip!
three.bark/);
Ruff! Ruff!

you are here. 73


method parameters

You can send things to a tttethod


Just as you expect from any programming language, you aU1 pass values into
your methods. You might, for example, want to tell a Dog object how many
times to bark by calling:
d.bark(3) ;
Depending on your programming background and personal preferences,
you might use the term arguments or perhaps paramet.ers for the values passed
in to a method. Although there emformal computer science distinctions that
people who wear lab coats and who will almost certainly not read this book.
make. we have bigger fish to fry in this book. So yuu can call them whatever
you like (arguments, donuts, hairballs, etc.) but we're doing it like this:
A method ~ parameters. A caller passes arguments.
Arguments are the things you pass into the methods. An argument (a value
like 2, "Faa", or a reference to a Dog) lands face-down into a... wait for it..
parameter. And a parameter is nothing more than a local variable. A variable
with a type and a name, that can be used inside the body of the method
But here's the"important part: If a method takes a parameter, you mustpass
it something. And that something must be a value of the appropriate type.

Dog d = new Dog() ;


Call the bark method on the Dog refer-
O ence, and pass in the value 3 (as the d.bark(3) ;
argument to the method). ~ aY'~~",e~t.
A The bits representing the int
W value 3 are delivered into the
bark method.

P~,"d_~," l:>''\. A
V
The bits land in the numOfBarks
parameter (an int-stzec variable).
~ in
void bark (int numO arks) {
Use the numOfBarks
while (numOfBarks > 0) { O parameter as a variable in
the method code.
System.out.println("ruff");
numOfBarks = numOfBarks - 1;
}
}
74 chapter 4
methods use instance variables

You ca., get thi.,gs backfrottt a lMethod.


ods can return values. Every method is declared with a return
. but until now we've made all of our methods with a void
type, which means they don't give anything back.

re can declare a method to give a specific type of value


to the caller, such as:
~ giveSecret ()
return 42;

declare a method to return a value, you must


a value of the declared rypel (Or a value
. (()mpatiblewith the declared type. We'll get
at more when we talk about polymorphism
pter 7 and chapter 8.)

atever you say


'II give back, you
tter give back!

t - life. giveSecret () ;

giveSec et () {
return 42-
t,nis "'~ ~it.
} . tJ
ill aWl \WI\...

you are here ~ 75


.
multiple arguments

You can send ",ore than one thing


to a tMethod
Methods can have multiple parameters. Separate them
with commas when you declare them, and separate the
arguments with commas when you pass them. Most
importantly, if a method has parameters, you must pass
arguments of the right type and order.

Call1"Q a two-paralMeter IMethod, altd seltdh,g


It two arQuIMe"ts.
void qo () {
TestStuff t = new T8Ststuff()i
t.takeTwo(12, 34);

lnt z = x
\\
void takeTwo(int x, int y)

+ y;
(

Systam.out.prinUn ("Total. is " + z);


. )

You ca" pass variables h'to a IMethod, as lo"c.1 as


the variable type IMatches the paraIMefer type.
void qoO (
int faa = 7;

int bar = 3;
t. takeTwo (foo, bar);

\~
void takeTwo(int x, int y)
int z ... x + Yi
System. out . println ("Total is rr + z);

76 chapter 4
methods use instance variables

Java is pass...by...value.
=
That tMea"s pass"'by"'copy.
-----
Declare an in~nd assign it
int x = 7;
int
O the value '7. The bit pattern for 7
goes into the variable named x.

void go(int z){ }~ int


A
'iii'
Declare a method with an int
parameter named z.

f t Call the goO method, passing


W the variable x as the argument.
The bits in x are copied, and
the copy lands in z.
int int
foo.go(x) ; void qo(int z){ }

lit
e'Vb\
dots,,'f. thci
• f' ~ d~.113
,~ 4:'\1 .,
~. . . . a.,.d
~~t~g
L. j
'J.. d'f't":-\:' tf A
V
Change the value of z inside
the method. The value of x
doesn't change! The argument
><: ·.. · · · · ···0···.. · · · · ... passed to the z parameter was
int
void go(int z){
z = 0;
mt
---
only a copy of x.
The method can't change the
bits that were in the calling
variable x.
}

you are here. 77


arguments and return values

Q:What happens Ifthe argument you want to Reminder: Java


pass Is an object Instead of II primitive?
cares about type!
A: You'll learn more about this In later chapters,
but you already know the answer. Java passes
You can't return a Giraffe when
the return type Is declared
everything by value. EverythIng. But... value means as a Rabbit. Same thing with
bits Inside the vcrtable. And remem ber,you don't parameters. You can't pass a
stuff objects Into variables; the variable Is a remote Giraffe Into a method that
control-a reference to an object. So If you pass a takes a Rabbit.
reference to an object into a method, you're passing
a copy of the remote control. Stay tuned, though, we'll
have lots more to say about this.

Q..: Can a method declare multiple return values?


Or Is there some way to return more than one
value? • Classes define what an object knows and whal an
object does.

A: Sort of. A method can dec lare onIy one return


value. BUT... If you want to return, say, three int values,
• Things an object knows are its Instance variables
(state).
then the declared return type can be an Int orray.
• Things an object does are its methods (behavior).
Stuff those lnts into the array,and pass It on back. It's
a little more involved to return multiple values with • Methods can use instance variables so that objects
different types; we'll be talking about that in a later of the same type can behave differently.
chapter when ~e talk about ArrayLlst.
• Amethod can have parameters, which means you
can pass one ormore values in to the method.
'Q :Do I have to return the exact type , declared?
• The number and type ofvalues you pass inmust
A.: You can return anything that can be implicitly
promoted to that type. So, you can pass a byte where
match the order and type of the parameters
declared bythe method.
an Int Is expected .The caller won't care,because the • Values passed inand out ofmethods can be
byte fits Just fine Into the tnt the caller will use for implicitly promoted to a larger Iype orexplicitly cast
assigning the result. You must use an explicit cast to a smaller type.
when the declared type Is smaller than what you're
trying to return. • The value you pass as an argument toa method
can be a literal value (2, 'c', etc.) ora variable of
Q..: Do I have to do something with the return the declared parameter type (for example, x where
x is an intvariable) . (There are other things you
value of a method? can IJust Ignore it?
can pass as arguments, but we're not there yet.)

A :Java doesn't require you to acknowledge a


return value. You might want to call a method with
• Amethod must declare a retum type.Avoid retum
type means the method doesn't return anything.
a non-void return type, even though you don't care • Ifa method declares a non-void return type, it must
about the return value. In this case, you're calling
return a value compatible with the declared return
the meth od for the work it does inside the method,
rather than for what the method gives returns . In
type.
Java, you don't have to assign or use the return value.

78 chapter 4
methods use instance variables

"ttgs you catt do with parameters


returtt types
_ _.... .e've seen how parameters and return types work, it's ElectrlcGultar
them to good use: Getters and Setters. If you're into
rm al about it, you might prefer to call them ACC610TS brand
.Jw.;ifO;OOIrl. But that's a waste of perfectly good syllables. numOfPickups
Gc ters and Setters fits the java naming convention. so rockStarUsesl1
~,wl:l2 l we'Il call them.

nd Setters let you, well, get and sa things. Instance van-


1r:1_JeS. usually. A Getter's sole purpose in life is to send back, getBrandO
~az!lnl value, the value of whatever it is that particular Getter selBrandO
".-as.:d to be Getting. And by now, it's probably no surprise getNumOfPickuPSO
1&3, ~ner lives and breathes for the chance to take an argu-
.~1De and use it to set the value of an instance variable. setNumOfPickupsO
getRockStarUsesltO
setRockSlarUsesllO

- i.DcJ brand i
• numOfPiclcups;
.an rockStarUs8sIt;

Si:.:-'.-nCJ qetBrand ()
return brand;

id s8tBrand (String &Brand) (


brand = &Brand i

• getNumOfPickups() {
return numOfPickups;

:.d setNumOfPickups (int num)


numOfPickups = num;

.an g8tRockStarusealt()
=-~rn rockStarUseslt;

setRockStaruseslt(boolean y&sOrNo) {
~tarU8eslt m yesOrNoi

you a re he re. 79
real developers encapsulate

Et1capsulaffot1
00 It or risk hUlMlliatiot' at'd
ridicule.
Until this most important moment, we've
been committing one of the worst 00
faux pas (and we're not talking minor
violation like showing up without the IB'
in BYOB). No, we're talking Faux Pas with
a capital 'F' . And ·P'.
Our shameful transgression?
Exposing our datal
Here we are.just humming along without
a care in the world leaving our data out
there for anyoru to see and even touch.
You may have already experienced that
vaguely unsettling feeling that comes with
leaving your instance variables exposed.
Exposed means reachable with the dot
operator, as in:
theCat.height : 27;
.T hink about this idea of using our remote
control to make a direct change to the Cat
object's size instance variable. In the hands
of the wrong person, a reference variable
(remote control) is quite a dangerous
weapon. Because what's to prevent:

~\l.ts~ Wt.
't.
eA" 1
theCa t. height = 0; 1e-t ~i5. "ayYt".

This would be a Bad Thing. We need to public void setBeight (int ht) {
build setter methods for all the instance
variables, and find a way to force other
if (ht > 9) {
code to call the setters rather than access height: ht;
the data directly. }

80 chapter 4
methods use Instance variables

'"
thedata Java'~ed
it is that simple to go from This week's Interview:
implementation that's just An Object gets candid about encapsulation.
. g for bad data to one
HeadFirst What's the big deal about encapsulation?
protects your data and
ects your right to modify Object: OK.,you know that dream where you're givinga talk to 500 people when you
implementa tion later. suddenly realize- you're TUJkaP.
so how exactly do you HeadFirst: Yeah, we've had that one. It's right up there with the one about the Nates
the data? With the machine and... no, we won't go there. OK, so you feelnaked. But other than being a little
lie and private exposed, is there any danger?
ess modifiers. You're Object Is there any danger? Is there any danger? [St3.I'1S laughing] Hey, did all you other
. iar with public-we use instances hear that, "Is lhert aT[! danger?" he asks? [falls on the floor laughing]
rith every main method.
HeadFirst: What's funny about that? Seems like a reasonable question.
re's an encapsulation
Object: OK, I'll explain it. It's [bW'StS out laughing again, uncontrollably]
nile of thumb (all stan-
disclaimers about rules HeadFirst: Can I get you anything? Water?
~ thumb are in effect): mark Object: Whew! Oh boy. No I'm fine, really. I'll be serious. Deep breath. OK, go on.
instance variables privati!
provide public getters HeadFirst: So what does encapsulation protect you from?
setters for access control. Object Encapsulation puts a force-fieldaround my instance variables, so nobody can set
you have more design them to, let's say, something inappropriaJ.e.
codi ng savvyin Java, you HeadFirst Can you giveme an example?
bably do things a little
rently, but for now. this Object: Doesn't take a PhD here. Most instance variable values are coded with certain
I!!!IlP:oach will keep you safe. assumptions about the boundaries of the values. Like, think of all the things that would
break if negative numbers were allowed. Number of bathrooms in an office. Velocity of
an airplane. Birthdays.Barbell weight Cellphone numbers. Microwaveoven powet
HeadArst: I see what you mean . So how does encapsulation let you set boundaries?
Object By forcing other code to go through setter methods. That way, the setter method
can validate the parameter and decide if it's do-able. Maybe the method will reject it and
do nothing, or maybe it'll throw an Exception (like if it's a null social security number
ark getters and for a credit card application), or maybe the method will round the panlITleter sent in to
etters pUblic. the nearest acceptable value. The point is,you can do whatever you want in the setter
method, whereas you can't do aT[!thing if your instance variables are public.
HeadFirst: But sometimes I see setter methods that simplyset the value without check-
ing anything: If you have an instance variable that doesn't have a boundary, doesn't that
sener method create unnecessary overhead? A performance hit?
·Sodly. Bill forgot to
CftCopsulQt~ his Cat class and Object: The point to setters (and getters, too) is that you can c1umge your mind later,
ended up wltk Q flat cat . H without breaking any1Jo4y else's code! Imagine if half the people in your com-
(overheard at the water cooler). pany used your classwith public instance variables, and one day you suddenly realized,
"Oops- there's something I didn't plan for with that value, I'm going to have to switchto a
setter method." You break everyone'scode. The cool thing about encapsulation is that you
get to cJumgt)'CUT mind. And nobody gets hurt The performance gain from using variables
directly is so rniniscule and would rareIy--if DJn- be worth it
you are here ~ 81
how objects behave

class GoodDog (
Ettcapsulatittg the GoodDog
t}oodPog class /I
.~.,.t,L
private int size;
size
tJ\o¥-t. .\.)\t. \. #. ,/ -
~o~
'\ ,,\ l\ t.
0
~ public int getSize ()
gelSize( }
~ ) r,turn ,i,e,
selSize( )
bark( )

t). ~~ al\G ~ public void setSi"le (int s) (


Ma'¥.t. t..1.\..~~ ~.
~tt.~ ",CV' size = s r

void bark () (
i f (size > 60)
System .out.println("wooof! Wooof!");
else i f (size> 14) (
Syscem.out.princln("Ruff! Ruff!");
else (
System .out.println( "Yip! Yip!");

I.Any place where a


particular value can class GoodDogTestDrive I
be used, a method
call that returns that public static void main (String!) args) (
type can be used. GoodDog one = new GoodDog();
one .setSize(70);
GoodDog two = new GoodDog();
Instead of:
two.setSize(8);
int x =3 + 24;
System .out.printlnI WDog one: + one.getSize(»;
you can say: System.out.printlnl"Dog two: " + tWQ.getSize(»;
int x =3 + one.gdSize(); one. bark ();
two. bark () ;

82 chapter 4
methods use instance variables

How do objects I" a" array


have?
like any other object. The only difference is
. you get to them. In other words, how you get
remote control. Let's try calling methods on
objects in an array.

Declare and create a Dog array,


to hold 7 Dog references.
Doq[] pets;
pets = new Doq[7];

Dog array object (Dog[])


Dog[]

Create two new Dog objects.


and assign them to the first
two array elements.
pets [0] = new Dog () ;
pets[l] = new Dog();

Call methods on the two Dog


objects.
pet8[O].setSize(30) ;
int x =
pets[O] .qetsize();
peta[l) .setSize(8);

Dog array object (Dog[])


Dog[]
you are here ~ 83
Initializing instance variables

Peclarfttg and initializing


ittstatlce variables
Instance variables
You already know that a variable declaration needs at least a name
and a type : always get a
int size; default value. If
String name;
you don't explicitly
And you know that you can initialize (assign a value) to the assign a value
variable at the same time:
to an instance
int size =420;
String name =
"Donny"; variable, or you
don't call a setter
But when you don't initialize an instance variable, what happens
when you call a getter method? In other words, what is the value of
method, the
an instance variable bejoreyou initialize it? instance variab'e
t,al'll.t IIayia\,\es, still has a value!
class PoorDog ( dtt\a'Ct t..,o i~ ~ IIalw.
. . / } \:l",t. d()t\' t. a~I~1\ integers 0
private 1nt size; k'~
private String name; floating points 0.0
What will -tnue: 'Cd!.',",?? booleans false
P)ubliC int getsize () (~
return size; If references null
public String getName () (
return name;

, Y.-? y.l\\\
public class PoorDogTestDrive { ~\:, ~o ~O'" t.~j ,
public static void main (String [] args) ( / . "'1\ t,O"'~
PoorDog one =
new PoorDog () ; '.!. ~\~ e )
System.out.println("Dog size is " + one.getSize(»);
System.out.println("Dog name is " + one.getName(»);

% java PoorDogTestDrive
Dog size is 0
Dog name is null

84 chapter 4
methods use instance variables

fhe differet1ce betwee" it1sfat1ce


at1d local variables

o Instance variables are declared


inside a class but not within a method. Local variables do
class Horse ( NOT get a default
private double height 15.2; value! The compiler
private String breed;
II more code . . . complains if you
try to use a local
variable before

e Local variables are declared within a method.


the variable is
initialized.
class AddThing {
iot a;
int b = 12;

public iot add() {


int total = a + b;
return total;
Q: What about method parameters?
How do the rules about local variables
apply to them?

A:
e Local variables ~UST be initialized before usel
Method parameters are virtually the
same as local variables-they're declared
Inside the method (well, technically they're
declared in the argumenr ltst of the method
class Foo { "I\e" Yov. u~ rather than within the body of the method,
public void go () W()\'l t to"''' ' t~ ~ a 'Ja\~,
(
Ln t x; deda ye Yo WI 0 b-1
nl.&t. as $CO¥\ as 'f~ .
but they're still local variables as opposed to
Instance variables). But method parameters
Lrrt z = x + 3; to ~ it, ~e l.oft<~\ tr will never be uninitialized, so you'll never get
"------- ~~ea~ ol.&-t. a complier error telling you that a parameter
variable might not have been initialized.
But that's because the compiler will give
you an error if you try to invoke a method
File Edit Window He! 'r'lke6
without sending arguments that the method
% javac Foo.java needs. So parameters are ALWAYS initialized,
because the compiler guarantees that
Foo.java:4: variable x might methods are always called with arguments
not have been initialized that match the parameters declared for the
method, and the arguments are assigned
int z = x + 3; (automatically) to the parameters.
1 error

you ar e he re . 85
object equality

Colttpari"Q variables (primitives or refere.,ces)


Sometimes you want to know if two primitives are the same. That's easy
enough, just use the = operator. Sometimes you want to know if two
Use ==to compare
reference variables refer to a siogle object ~>n the heap. Easy as well, jusl use two primitives,
the == operator. But sometimes you want to know if two objects are equal. or to see if two
And for that, you need the .equals 0 method. The idea of equality for references refer to
objects depends on the type of object. For example, if two different String the same object.
objects have the same characters (say. "expeditious"), they are meaningfully
equivalent, regardless of whether they are two distinct objects on the heap. Use the equalsO
But what about a Dog? Do you want to treat two Dogs as being equal if they method to see
happen to have the same size and weight? Probably not. So whether two
different objects should be treated as equal depends on what makes sense for
if two diHerenf
that particular object type . We'll explore the notion of object equality again objects are equal.
in later chapters (and appendix B), but for now, we need to understand that (Such as two different
the == operator is used emly to compare the bits in two variables. What those String objects that both
bits represent doesn't matter. The bits are either the same, or they're not. represent the characters
In "Freel")
To compare two primitives, use the == operator
The = operator can be used to compare two variables of any kind, and it
simply compares the bits.
if (a = b) {...j looks at the bits in a and b and returns true if the bit pattern
is the same (although it doesn't care about the size of the variable, 50 all the
extra zeroes on the left end don't matter). ~~ 0" )(~\
oV'e u'( t
in t Ii = 3;

byte b
i f (a
= 3;
== b) { II tl:Ue }
(t.t.t'«( aye.'" J t"e iYl ,
rt ~\de
.lc.he \tJ(
\,~t. 'Ole o.~
t.'hat n('(e) ,
L~t
't. (.4'(e 61l
.
a--
int
--
byte

To see If two references are the same (which means they


refer to the same object on the heap) use the operator ==
Remember, the == operator cares only about the pattern of bits in the
variable. The rules are the same whether the variable is a reference or
primitive . So the == operator returns true if two reference variables refer to
the same objectl In that case, we don't know what the bit pattern is (because
it 's dependent on theJVM, and hidden from us) but we M know that whatever
it looks like, it wiU be the samefor two refmrues to a singleobject.
Foo a = new Foo();
Foo b = new Foo();
Foo c = a;
if (a == b) { II false } Foo
a=t.ish"\oI.e
if (a -- c) ( II true )
a = b is .falst
i f (b --
c) ( II false ) Foo
Foa

86 chapter 4
methods use Instance variables

Make ,t st,tk
Roses are red,
this poem ischopPY,
. byvalue
passing
;s passing by copy,
1 it.Replace our
can do better? r'J 8e~ryet.
Oh,like yoU d llne with your ow'" wn wOld~
dumb secon I thing with YOUl 0
theY/ho e
replace forget it.
a"d you'll never

int a '" calcArea(7, 12);


What's legal?
Given the method below, which
KEEP short c '" 7;

of the method calls listed on the


right ore legalt
Put a checkmcrk next to the
+-
RIGHT
calcArea (c,15) ;

int d '" calcArea(S7);

calcArea (2,3) ;
ones that are legal. (Some
statements are there to assign long t '" 42;
values used in the method colis).
int f = calcArea(t,17);

int 9 '" calcArea();


int calcArea(int height, int width) calcArea () ;
return height • width; byte h = calcArea(4,20);

int j = calcArea(2,3,5);

you are here ~ 87


exercise: Be the Compiler

BE the oomriler
Each ofthe Java files on this page
represents a complete source file.
Your joh is to play collll'iler and
determine whether each ofthese files
will compile. If they won't
compile. how would you
rIX them, and if they do
c011lpile. what would he
their output'i'

A B

class XCopy { class Clock {


String time;
public static void main(Strinq [) arqs) {
void setTime(String t)
int orig = 42;
time = t j
Xcopy x = new xCopy();

int y : x.go(orig)j void getTime()


return time;
System.out.println(orig + U U + y); }

int go(int arg)


class ClockTestDrive {
arg = arg * 2; public static void main(String (] args) {

return arg; Clock c = new Clock();


}
}
c.setTime(U124S n ) j
String tad = c.getTime()i
System.out.println(Utime: u + tod)j

88 chapter 4
methods use instance variables

A bunch of Java components, in full costume, are playing a party


game,· Wha am W They gille you a clue, and you try to guess who
they are, based on what they say.Assume they always tell the truth
about themselves. If they happen to say something that could be true
for more tha n on e guy, then write down all fa r whom that sentence
applies. Fill In the blanks next to the sentence with the names of one
or more attendees.
Tonight's attendees:
Insta nee variable, argument, return, getter, setter,
encapsulation, public, private, pass by value, method

A class can have any number of these.

A method can have only one of these.

This can be Implicitly promoted.

I prefer my Instance variables private.

It really means 'make a copy'.

Only setters should update these.

A method can have many of these.

I return something by definition.

I shouldn't be used with instance variables.

I can have many arguments.

By definition, I take one argument.

These help create encapsulation.

I always fly solo.

you are here. 89


puzzle: Mi)(ed Messages

Mixed
Messages
A short Java program Is listed to your right. public class Mix4 (
Two blocks of the program are missing.
Your challenge Is to match the candIdate int counter = OJ
blocks of code (below) , with the output public static void main (String [) args) (
that you'd see if the blocks were Inserted. int count = 0;
Not all the lines of output will be used, and Mix4 [) m4a =new Mix4[20lj
some of the lines of output might be used
int x = 0;
more than once. Draw lines connecting
the candidate blocks of code with their
matching command-line output.
while (I I)
m4a [x] = new Mix4 ();
m4a(x] . counter = m4a(xl .counter + 1;
count count + 1;
count count + m4a[x) .maybeNew(x);
x = x + 1;

System. out.println(count + ~ "


+ m4a[1) .counter);
CandIdates: Possible output:

x ·< 9 public iot maybeNew(int index)


index < 5 ,!
if (I I') (
Mix4 m4 = new Mix4();
x < 20 m4.counter = m4.counter + 1;
return 1;
index < 5 .~

return 0;

x <7

index < '1

x < 19
index < 1 •.

90 chapter 4
methods use Instance variables

public class Puzzle4 {


public static void main(Strinq [] arqs) {

int y = I:
int x = 0:
int result = 0;
Your Job is to take code snippets from the
pool and place them Into the blank lines while (x < 6) {
in the code. You may not use the same
snippet more than once, and you won't
need to use all the snippets. Your goal
is to make a class that will compile and y y * 10;
run and produce the output listed.
}
x = 6;
while (x > 0) {

result = result + __
Output }
system.out.println("result " + result);
}
}

class {
int ivar;
_____ doStuff(int ) {
if (ivar > 100) {
return _
} else {
- return
}
---------------------
}
}
Note: Eachsnippet
"om the pool can be
used only oncel

you are here) 91


puzzle: Five Minute Mystery

Fast TImes in Stim-Clty

When Buchanan jammed his twitch-gun into Jai's side , Jai froze. Jai knew that Buchanan
was as stupid lis he was ugly and he didn't want to spook the big guy. Buchanan ordered Jai
into his boss's office, but Jai'd done nothing wrong, (lately), so he figured a little chat with
Buchanan's boss Leveler couldn't be too bad. He'd been moving lots of neural-stimmers in
the west side lately and he figured Leveler would be pleased. Black market stimmers weren't
the best money pump around, but they were pretty harmless. Most of the slim-junkies he'd
seen tapped out after a while and got back to life, maybe just a little less focused than before.

Leveler's ' office ' was a skungy looking skimmer, but once Buchanan shoved him in, Jai
could see that it'd been modified to provide aIL the extra speed and armor that a local boss like
Leveler could hope for. "Jai my boy", hissed Leveler, "pleasure to see you again". "Likewise
I'm sure...", said Jai, sensing the malice behind Leveler's greeting, "We should be square
Leveler, have r missed something?" "Ha! You're making it look pretty good Jai, your volume
is up, but I've been experiencing, shall we say, a little 'breach'lately..." said Leveler.

Jai winced involuntarily, he'd been a top drawer jack-hacker in his day. Anytime someone
.figured out how to break: a street-jack's security, unwanted attention turned toward Jai, "No
way it's me man", said Jai, "not worth the downside. I'm retired from hacking, [just move
my stuffand mind my own business", "Yeah, yeah", laughed Leveler, "I'm sure you're
clean on this one, but I'll be losing big margins until this new jack-hacker is shut
out!" "Well, best of luck Leveler, maybe you could just drop me here and I'll go
move a few more 'units' for you before I wrap up today", said Jai.

"I'm afraid it's not that easy Jai, Buchanan here tells me that word is you're
current on 137NE", insinuated Leveler. "Neural Edition? sure I play around a bit, so
what?". Jai responded feeling a little queasy. "Neural edition's bow I let the stim-junkies
know where the next drop will be", explained Leveler. "Trouble is, some srim-junkie's stayed
straight long enough to figure out how to hack into my WareHousing database." "I need a
quick thinker like yourself Jai, to take a look at my StimDrop 137NE class; methods, instance
variables, the whole enchilada, and figure out how they're getting in. It should..", "HEY!",
exclaimed Buchanan, "I don't want no scum backer like Jai DOSin' around my code!" "Easy
big guy", Jai saw his chance, "I'm sure you did a top rate job with your access modi .. "Don't
tell me - bit twiddler!", shouted Buchanan, "1 left all of those junkie level methods public,
so they could access the drop site data, but 1 marked all the critical WareHousing methods
private. Nobody on the outside can access those methods buddy, nobody!"

"I think I can spot your leak Leveler, what say we drop Buchanan here off at the comer
and take a cruise around the block", suggested Jai. Buchanan reached for his twitch-gun but
Leveler's stunner was already on Buchanan's neck, "Let it go Buchanan", sneered Leveler,
"Drop the twitcher and step outside, I think Jai and I have some plans to make",

What did Jai suspect?


Will be get out of Leveler's skimmer with all his bones intact?
92 chapter 4
methods use Instance variables

class Clock
String time;
void setTime(~tring t) {
time:: t;
B }
String getTime ( )
return time;
}

class ClockTestDrive {
public static void main(String rl args) {
Clock c = new Clock();
c.setTime(R124S R ) j
String tod = c.getTime();
System.out.println(Utime: • + tod);

} Note: 'Getter' methods have a return


XCopy' compiles and runs as it stands I The type by definition.
84'. Remember Java is pass by value, (which
copy), the variable 'orig' is nol changed by the

dass can have any number of these. Instance varl~bles, getter, utter,method
method can have only one of these. return
I' can be implicitly promoted. return. argument
prefer my instance variables private. encapsulation
really means 'make a copy'. pass by value
setters should update these. Instance variables
method can have many of these. o.rgt.llnent
return something by definition. getter
shouldn't be used with instance variables public
can have many arguments. method
definition, , take one argument. setter
se help create encapsulation. getter. s£'tter, public. private
always fly solo . return

you are here. 93


puzzle answers

Puzzle Solutions

Answer to the 5-minute mystery...

pUblic class Puzzle4 (


Jai knew that Buchanan wasn't the sharpest
public static void main(String [] args) { pencil in the box. When J ai heard Buchanan
Puzzle4b [ ] ebs =new Puzzle4b[6J; talk about his code, Buchanan never mentioned
int y - 1; his instance variables. Jai suspected that
int K .. 0, while Buchanan did in fact handle his methods
int result = 0:
correctly, he failed to mark his instance variables
while (x < 6) (
private. That slip up could have easily cost
obs[x) =new PU2zle4b( ):
Leveler thousands.
obs[x) . ivar =y;
y - y .. 10;
x=><+1;

x = 6,
while (x > 0) {
x =x-I;
result = result + obs[x].doStuff(x): Candidates: Possible output:

System.out.println("result u + result); x < 9


}

index < 5
class Punle4b {
1nt ivar,
public int doStuff (int factor) x < 20
if (ivar > 100) {
return ivar * factor; index < 5
else {
return ivor" (5 - factor);
Output
x < 7
q\ java Puzzle4
index < 7
result 543345

x < 19

index < 1

94 chapter 4
5 writing a program

Extra-Strength Methods

Let's put some muscle In our methods. We dabbled with variables, played
with a few objects, and wrote a little code. But we were weak.We need more tools. Like
operators. We need more operators so we can do something a little more interesting than, say,
bark. And loops. We need loops, but what's with the wimpy while loops? We need 10, loops

jfwe're really serious. Might be useful to generate random numbers. And turn a String
Into an Int, yeah, that would be cool. Better learn that too. And why don't we learn It all by
building something real, to see what it's like to write (and test) a program from scratch. Maybe
a game, like Battleships. That's a heavy-lifting task,so It'll take two chapters to finish .We'll build
a simple version in this chapter, and then build a more powerful deluxe version in chapter 6.

this is a new chapter 95


building a real game

Letls build a Jattleship.. style


gattte: "Sitdc a Pot COttt
N

It's you against the computer, but unlike the real


Battleship game, in this one you don't place any ships You're going to build the
of your own. Instead, your job is to sink the computer's Sink a Dot Com game, with
ships \0 the fewest number of guesses.
a 7 x 7 grid and three
Oh, and we aren't sinking ships. We're killing Dot Dot Coms. Each Dot Com
Corns. (Thus establishing business relevancy so you can
takes up three cells.
expense the cost of this book).
Goal: Sink all of the computer's Dot Corns in the fewest
number of guesses. You're given a rating or level, based
on how well you perform.
part of a galMe it1feraetlott
Setup: When the game program is launched, the
computer places three Dot Corns on a virtual 7 x 7 ..
grid. When that's complete, the game asks for your first %j ava OotComBust
guess. Ent e r a guess A3
How you play: We haven't learned to build a CUI yet, so mi s s
this version works at the command-line. The computer
will prompt you to enter a guess (a cell), that you 'U type Ent e r a guess 82
at the command-line as ~A.3", "C5", etc.). In response mi s s
to your guess, you'll see a result at the command-
Ent e r a guess C4
line, either "Hit", "Miss", or "You sunk Pets.corn" (or
whatever the lucky Dot Com of the day is). When mi s s
you've sent all three Dot Cams to that big 404 in the Ent e r a guess 02
sky,the game ends by printing out your rating.
h it
tat.\-. 'oo~~
"7 )< "7 ~r-id ',s a "t.t\\ Ent e r a guess 03
hit
A k
Enter a guess 04
B Ouch! You sunk Pets. com
E
C 5• kill
~
e Enter a guess B4
D P4 ts.cc m
miss
E Enter a guess G3
F hit
Enter a guess G4
G
I Asi Me.c pm hit
o 1 2 3 4 5 6 Enter a guess GS
Ouch! 'lou sunk AskMe.com
'- shr-h at. ut"o, like Java d'n'ays
96 chapte r 5
writing a program

First a high.. level desigtt


'e know we'll need classes and methods. but what
uld they be? To answer that, we need more
form ation about what the game should do.
First, we need to figure out the general flow of the
zame. Here's the basic idea:

o
User starts the game

o
Game set-up

Game creates three Dot Coms

o Game places the three Dot


ColTlS onto a virtual grid

Game play begins


hit
Repeat the following until there are
no more Dot Coms:

A Prompt user for a guess 1'\


W ("'2', 'CO', etc.) . ) remove

(0 Check 'he user guess oga;nst


all Dot Coms to look for a hit,
Dot Com

miss, or kill. Take appropri-


ate action : if a hit, delete cell Adial'l\Of\d
(A2, D4, etc.). If a kill, delete yt:f""~l\b a
Dot Com. dt:t.isiOl\ ~O'l\t

Game finishes
Give the user a rating based on display user
the number of guesses. score/rating

~ ow we have an idea of the kinds of things the


rogram needs to do. The next step is figuring
ut what kind of objects we'll need to do the
loo·ork. Remember, think like Brad rather than
Larry; focus first on the things in the program
ra the r than the jrroredures.
Whoa. A real flow chait.

you are here. 97


a simpler version of the game

N
fhe "SitMple Pot CO"' .allte
a get1tler it1troductiot1
It looks like we're gonna need at least two classes, a
Game class and a DotCom class. But before we build
o 6arM starts, and creates ONE DotCom
and gives it a location on three. cells in
the single row of seven cells.
Instead of • A2", ·C4", and 50 on, the
the fuJI monty Sinh a Dot Com game, we'll start with
locations are just integers (for example :
a stripped-down. simplified version, Simple Dot Com 1,2,3 are the cell locations in this
Game. We'll build the simple version in this chapter, picture:
followed by the deluxe version that we build in the
next chapter.
Everything is simpler in this game , Instead ofa 2-D
grid, we hide the Dot Com injust a single TOW. And o 1 2 3 4 5 6
instead of three Dot Corns, we use one.
6a1U play begins. Prompt user for
The goal is the same, though, so the game still needs a guess, then check to see jf it hit
to make a DotCom instance, assign it a location any of the DotCom's three cells .
somewhere in the row, get user input, and when all If a hit , increment the numOfHits
of the DotCom's cells have been hit, the game is over, variable.
This simplified version of the
game gives us a big head start SlmpleDotCom Game 6ame 'finishes when all three cells have
on building the full game. been hit (the numOfHits variable vel-
~ ue is 3), and tells the user how many
If we can get this small one
SlmpleDofCom guesses it took to sink the DotCom.
working, we can scale it up to
the more complex one later. Inl 0localionCells
voId mail\ Intnum01Hl1s
In this simple version, the
game class has no instance
variables, and all the game String checkYou~If(Stril\g guess)
code is in the main () method,
void SetlocallonCellsQntO loe)
In other words, when the
program is launched and
main () begins to run, it will
make the one and only DotCom
instance, pick a location for it ( three
consecutive cells on the single virtual
seven-cell row), ask the user for a guess, check the
guess, and repeat until all three cells have been hit.
Keep in mind that the virtual row is... virtual: In other
words, it doesn't exist anywhere in the program . As
long as both the game and the user know that the
DotCom is hidden in three consecutive cells out ofa
possib\e seven (starting at zero) , the tOW i.tself doesn't
have to be represented in code. You might be tempted
to build an array of seven ints and then assign the
DotCom to three of the seven elements in the array,
but you don't need to. All we need is an array that
holds just the three cells the DotCom occupies.
98 chapter 5
writing a program

Pevelopit1Q aClass fhe three thlt19S we~1I wrIte for


_ a programmer, you probably have a methodology/
each class:
ess/approach to writing code. Well. so do we. Our
sequence is designed to help you see (and learn) what
're thinking as we work through coding a class. It
' t necessarily the way we (or you) write code in the
World. In the Real World, of course, you'll follow This bar Is displayed on the next set of pages to tell
approach your personal preferences, project, or you which part you're working on. For example, if you
ployer dictate. We, however, can do pretty much see this picture at the top of a page. it means you're
working on prepcode for the SimpleDotCom class.
tever we want And when we create aJava class as a
rning experience", we usually do it like this:
SlmpleDolCom class
~
D Figure out what the class is supposed to do.

D List the Instance variables and methods.


prep code
D Write prepcode for the methods. (You'll see A form of pseudocode. to help you focus on
this in Just a moment.) the logic without stressing about syntax.
D Write test code for the methods.
test code
D Implement the class. A class or methods that will test the real code
and validate that it's doing the right thing.
o Test the methods.
o Debug and relmplement as needed. rea I code
The actual implementation of the class . This is
o Express gratitude that we don't have to test _ _- - - -..... al Java code.
our so-called learning experience app on To DO.:
actuallJve users.
s'mp'eDotCOm claSS
o write prep code

o write test code


o write final Java code

s,mp'eDotCOmoame
Flex those dendrftes. cia••
How would you decide whIch class or classes
o write prep code

to build first, when you're writIng a program? write test code {nol
Assuming that all but the tiniest programs
need more than one class (If you're following
o write final Java code

good 00 principles and not having one class


do many different Jobs), where do you start?

you are here. 99


SimpleDotCom class

You'11 get the idea of how prepcode (our version of pseudocode) works as you
read through this example. It's sort of half-way between real Java code and a plain
SlmpleOolCom
English description of the class. Most prepcode includes three parts: instance
illl 0IocaIiooCelIs
inlnumOft-lils
variable declarations, method declarations, method logic. The most important
part of prepcode is the method logic, because it defines what has to happen,
String checkYourself(string guess)
which we later translate into hotu; when we actually write the method code.
void selLoca~onCells{inlj) lot)
DECLARE an int array to hold the location cells. Call it loeatJonCells.
DECLARE an int to hold the number of hits.Call it numOfHits and SET it to O.

DECLARE a checkYourset(() method that takes a String for the user's guess (" I", "3", etc),
checks it. and retums a result representing a "hit", "miss",or "kill",
DECLARE a setLocationCeJ/sO setter method that takes an int array (which has the three cell
locations as ints (1.3/1, etc.).

METHOD: String checkYourself(String userGuess)


GET the user guess as a String parameter
CONVERT the user guess to an int
REPEAT with each of the location cells in the int array
II COMPARf the user guess to the location cell
IF the user guess matches
INCREMENT the number of hits
II FIND OUT if it was the last location cell:
I F number of hits is 3, RETt,JRN "kill" as the result
ELSE it was not a kill. so RETURN"hit"
[
END IF
ELSE the user guess did not match, so RETURN "miss"
END IF
END REPEAT
END METHOD

METHOD: void setLocotJonCe//$(lnt[] eel/Locations)


GET the cell locations as an in! array parameter
ASSIGN the cell locations parameter to the cell locations instance variable
END METHOD

100 chapter 5
writing a program

Writing the tttethod


hMpletM8ntations
let's write the real
...ethod code ttOW, ittd get
this puppy worklttg.
Before we start coding the
methods, though, let's back
up and write some code to
test the methods. That's right,
we're writing the test code
1M/ore there's anything to testl
The concept of writing
the test code first is one of
the practices of Extreme
Programming (XP), and
it can make it easier (and
faster) for you to write your
code. We're not necessarily
saying you should use XP,
but we do like the part about
....Tiling tests first. And XP just
sounds cool.

Extreme Programming (XP)


Extreme Programming(XP) Is a newcomer to the software Don't put in anything that's not in the spec (no matter
evelopment methodology world.Consld ered by many how tempted you are to put In functionality "for the
t be "the way programmers really want to work ~ XP future) .
e erged In the late 90's and has been adopted by
Write the test cod e first .
•ompanies ranging from the two-person garage shop
the Ford Motor Company. The thrust of XP is that the No killer schedules;work regular hours.
sterner gets what he wants, when he wants It, even Refactor (improve the code) whenever and wherever you
en the spec changes late In the game. notice the opportunity.
is based on a set of proven practices that are all Don't release anything until it passes all the tests.
esigned to work together, although many folks do pick
and choose, and adopt only a portion of XP's rules. These Set realistic schedules, based around small releases.
ctices include things like: Keep it simple.
ke small, but frequent, releases. Program in pairs, and move people around so that
velop in Iteration cycles. everybody knows pretty much everything about the code .

you are here ~ 101


SlmpleDotCom class
prepcode

Writh1Q test code for the Shttp[eUoi'ColM class


We need to write test code that can make a SimpleDotCom object
and run its methods. For the SimpleDotCom class. we really
care about only the cMckYourselj() method, although we will have
to implement the sdLocatiun~l1s()method in order to get the
cMckYourself() method to run correctly.
Take a good look at the prepcode below for the checkYourselj()
method (the setLocaticmCells() method is a no-brainer setter method,
so we're not worried about it. but in a 'real' application we might
wan I a more robust 'setter' method. which we wouldwant to test).
Then ask yourself, "If the checkYourselfO method were
implemented. what test code could I write that would prove to me
the method is working correctly?"

'ased Ott this prepcode: Here1s what we should test:


METHOD String checkYourselffString userCuess) 1. Instantiate a SlmpleDotCom object.
GET the user guess as a String parameter 2, Assign It a location (an array of 3 ints, like
CONVERT the user guess to an Int {2,3.4}).
3. Create a SlJing to represent a user guess
REPEAT with each of the location cells in the Int array
('2", '0', etc.).
/I COMPARf the user guess to the location cell
4. Invoke the checkYourselfO method pass-
IF the user guess matches ing il the fake user guess.
INCREMENT the number of hits 5. Print out the result to see If It's correct
/ / FIND OUT if it was the last location cell: ("passed" or "failed").

IF number of hits is 3. RETURN "Kill" as the result


ELSE it was not a kill, so RETURN"Hif'
END IF
ELSE the user guess did not match, so RETURN "Miss"
END IF
END REPEAT
END METHOD

102 chapter 5

writing a program

~relare,..{l? "
fest code for the SIIMpiePotCoIM class
DiiJjjo ~uestl9ns
Q..:Maybe I'm missing some- public class SimpleDotComTestDrive ( ....sta"ba-tl. a
here, but how exactly do \~....y\e'Da\:.e,o...
run a test on something public static void main (S trinq [ ] arqs) ( do~et,t.
. . doesn't yet existI1
SimpleDotcom dot = new SimpleDotCom (); t::"
: You don't. We never said
start by running the test;
.".a't.-e 0" "'~t. il:l0'1 ~oY
-\:.be Got.
&e \ot.WOl' vb~e ,,,b
J ~'1o\t
O'>t. C,
start by writing the test. At
------ t.o"'" 1)·
. e you write the test code, int [] locations = {2 I 3 I 4}; V a Y°sJ.\
won't have anything to run
,against. so you probably won't dot.setLocationCells(locations); .
Ie to compile It until you
~ ''' ...oIc e tJ.. •.....L
e 'st ub' code that can com- .--.. ,.,tih e ~tn-
bu t that will always cause od 0,. the dot. to ....
est to fail (like, return null.)
"",Itt 0 ~ ake
String userGuess = "2 H ; ~
~tv"~~
:Then I stili don't see the
••..,rt. Why not walt until the String result = dot.checkYourself(userGuess);
Is written, and then whip
the test code? Strinq testResult = "failed" j
~i""'oke 1:~e thetJcYoursel.fO
_...1.,
m.ev\od on ille dot to...
objttt, a"d Pdss if. ill
if (result. equals ("hi t") ) ( .f<ilr:e ~LAe.11. e
: The act of th Inkl n9 th roug h
writing) the test code helps
. ...bri"tv your thoughts about what

method Itself needs to do.


)
soon as your implementation
e is done, you already have
code Just waiting to validate System.out.println(teStResult);~
Besides,you know If you don't f"'in1: 0Ii01: the wf. reslOl
't now, YOU'll never do It. } (p-aued at" .f<iiledJl) t
e's always something more
esting to do.
}

~r.~~,!::~~"
ally, write a little test code,
write only the Implementa-
code you need in order to
that test. Then write a little
of p••es w' Implemem the S1mpleDoteom class,
and then later we return to the test class. Looking at our test code
e test code and write only above, what else shou Id be added 7 What are we not testi ng in this
new implementation code code, that we should be testing for? Write your ideas (or lines of
ed to pass that new test. At code) below:
test lteratlo n, you TUn all
preViously-written tests, so
you always prove that your
t code additions don't break
iously-tested code.

you are here ~ 103


SimpleDotCom class

The checkYourselfO tttethod


There isn't a perfect mapping from prepcode to javacode; you'll see a few
adjustments. The prepcode gave us a much better idea of what the code needs to
do, and now we have to find the Java code that can do the how.
In the back of your mind, be thinking about parts of this code you might want
(or need) to improve. The numbers (18 are for things (syntax and language
features) you haven't seen yet. They're explained on the opposite page.

GET the user


public String checkYourself(String stringGuess) {
guess
I) to"veri th &t '
CONVERT
int guess = Integer.parselnt(stringGuess); L-
,--- w
L
al'l I•I'I~1- e r'''9
the user guess t o
an int String result = "miss"; ( a:
- .... e a variable
re~lAr" Plat II . "
to hold the reslAlt we'll
. . ""ss i" as the detalAlt
('.e. we clsslA....e a ......iss")
REPEAT with
each ceil in the int
array
IF the user guess

for (int cell : locationCells) {

mat ches

INCREMENT
the nUI1"lb er of
hits

~ 9d; QlAt o.f th I


to te t e <><>p, no "eed
! I e nd i f s the other tells

} II end f or
/ / FIND OUT if
it. was t he last ee l!
if (numOfHits == locationcells.length) (
IF number of hits
is 3.
result = "kill";
RETURN "kili"
as the result
/ ! end i f
ELSE it was
not a kill. so
RETURN "hit " System.out .println(result); ~ display the reslAlt.for the lASer
ELSE return result; ("Miss", lAl'lless it was tha"ged to "I-hi;" or "Kill")
RETURN
t"-. retlAr" the reslAlt bade to
} II end me thod the talli"9 ....ethod

104 chapter 5
writing a program

e things we haven't seen before


on this page. Stop worryingl The
of the details are at the end of
chapter. This isjust enough to let
keep going.

Converting a
String to an Int

n ~ ++ ... taY\1 add I to


The post-increment
operator
( 'WhaWtr'S th&e (il'l ~
'Wc*d.s, int __ e",ent by ,).
numOfHits++
roIArllOtl·hh++ i.s the sa...t (il'l
this ~) as sayi,,~ "...... O.f»its ::.
""",o.f~hh +" e~rt sli9hUt
...~~ tHitient

break statement
break;
~et.s y~ out o-f alOOf· l......ediduly. Ri~ht htl'"t.
No ihl'"atiol'l, no boolul'I ust, iwt o.d out "ow!

you are here ~ 105


SlmpleDotCom class
prep code

:therelare~~ "
DUmb ~uesti9115
public class S~leDotComTestDrive {
Q..: What happens In
Integer.pa rselnt(l If the thing you publiC s t a t i c void main (S~ringl] args) {
pau Isn't a number? And does It SimpleDotCom dot ~ new SimpleDotCom{};
recognize spelled-out numbers,
intI] locations ~ (2,3,4);
/Ike Jl t hree"?
dot , setLocationCells (locations) ;

A: Intege r.parselntO wo rks only


on Strings that represent the ascii
String userGuess
String result ~
~ "2-;
dot .checkYourself(userGuess);
values for digits (0,1,2,3,4,5,6,7,8,9).
If you try to parse something like
"two" or "blurp'; the code wi II blow
up at runtime. (By blow up, we
actually mean throw an exception,
but we don't talk about exceptions
until the Exceptions chapter. So for public class SimpleDotCom
now, blow up is close enough .)
intI) locationCells ;
int numOfHits ~ 0 ;

Q..:ln the beginning ofthe pUblic void setLocationCells(intl] locs) (


book, there was an exam pie of a locationCells = locs;
for loop that was really different
from this one-are there two
different styles of for loops? pUblic String checkYourself(String stringGuess)
int guess ~ Integer.parselnt{stringGuess);
String result - "miss ";
A:YeSl From the first version of for (int cell : IocationCells)
Java there has been a sIngle kind i f (guess ~ ~ cell) (
of (or loop (explained later In this result = " h i t - ;
chapter) that looks like this : numOfHits++;
break;
for (Int i = 0:/ < 10;1++) { ) What should we see
// do someth ing 10 times I I out o f t h e l o op when we run this code?
The test code makes a
if (numOfHits == SimpleDotCom object
You can use this format for any locationCells.length) and gives it a locat ion at
kind of loop you need. But... result ~ "kill-; 2,3,4 . Then it sends a fake
beginnIng with Java 5.0 (Tiger), ) user guess of "2" Into the
you can also use the enhancedfor System.out.println{result}; checkYouselfO method.
loop (that's the official description) return result; If the code is working
when your loop needs to iterate ) II clo se meth o ' correctly, we should see the
over the elements In an array (or I I c l o 'e c Ia s result print out:
another kind of collection, as you'll
see In the next chapter). You can
Java SlmpleDotComTestD r l ve
always use the plain old for loop
There's a little bug lurking here. It complies end lat
to iterate over an array, but the runs. but sometimes ... don't WOffY aboulll for now,
enhanced for loop makes it easier. but we will have to face it II little later,

106 chapter 5
writing a program

We built the test class, and the SimpleDotCom class.But we still haven't
made the actua I game. Given the code on the oppos Ite page, and the spec for
the actual game, write In your Ideas for prepcode for the game class. We've given
The SlmpleDotComGame
you a few lines here and there to get you started. The actual game code is on the
needs to do this:
next page, so don't tum the page until you do this exerdsel
1. Make the single
You should have somewhere between 12 and 18 lines (including the ones we wrote,
SimpleDotCom Object.
but not including lines that have only a curly brace).
2. Make a location for it (three
METHOD publicstatic void main (String 0 OI'J:S) consecutive cells on a single
DECLARE an int variable to hold the number of user guesses. named numOfGuesses row of seven virtual cells).
3. Ask the user for a guess.
4. Check the guess.
5. Repeat until the dot com is
dead .
6. Tell the user how many
guesses it took..

COMPUTE a random numberbetween0 and "I that will be the starting location cell position

WHILE the dot com IS ~i ll ahve :


GET user input (rom the command line

yo u are here. 107


SlmpleOotCom class

Prepcode for the ShMpleUo'fCottttatMe class


Everythfng happetts Itt Ittal..n
There are some things you'll have to take on faith. For example. we have one
line of prepcode that says, wCET user input from command-line". Let me tell
you, that's a little more than we want to implement from scratch right now, But
happily, we're using 00. And that means you get to ask some otherc1ass/object
to do something for you, without worrying about how it does it. When you write
prepcode, you should assume that somehoto you'll be able to do whatever you
need to do, so you can put all your brainpower into working out the logic.

public stadc voJd main (String D args)


DECLARE an int variable to hold the number of user guesses. named numO(t;uesses. set it to O.
MAKE a new SimpleDotCom instance
COMPUTE a random number between 0 and '\ that will be the starting location cell position
MAKE an int array with 3 ints using the randomly-generated number, that number incremented by I.
and that number incre mented by 2 (example: 3.4,5)

INVOKE the retLocOlionCeI!sO method on the SimpleDotCom instance


DECLARE a boolean variable representing the state of the game. named isAhve. SET it to true

WHILE the dot com is still alive (isAlive == true) :


GET user input {rom the command line
// CHECK the user guess
INVOKE the checkYourse/fO method on the SlmpleDotCom instance
INCREMENT numO(t;uesses variable
II CHECK (or dot com death
IF result is "kill"
SET isAlwe to false (which means we WOT'l'! enter the loop again)
PRINT the T'lumberof user guesses
END IF
END WHILE
END METHOD
nl~ogn.itive ttl
Don't work one part of the brain for 100 long a stretch at one time.
Working Just the left side of the brain formore than 30minules
is like working lust your left arm for 30 minutes, Give each side
of your brain a break by swilchlng sides at regular intervals. .
When you shift to one side. the other side gels 10 rest and
recover. Left-brain actJvlties Include things like step-by-step
sequences, logical prob\em-solving, and analysis. while the
right-brain kicks in formetaphors, creative problem-solving,
pattern-matching, and Visualizing.

108 chapter 5
writing a program
-
• Your Java program should start with a high· • Choose forloops over while loops when you
level design. know how many times you want torepeat the
loop code.
• Typically you'll write three things when you
create a new class: • Use the pre/post increment operator toadd 1
prepcode
to a variable (x++;)
testcode • Use the pre/post decrement tosubtract 1 from
a variable (x-;)
real (Java) code
• Use Integer .parseInt() to get the int
• Prepcode should describe what to do, not how value ofa String.
todoit. Implementation comes later.
• In teger . parseIn t () works only if the
• Use the prepcode tohelp design the test String represents a digit ("0":1',"2", etc.)
code.
• Use break 10 leave a loop early (i.e. even if
• Write test code before you implement the the boolean test condition is still true).
methods.

How many
hits did you get
last month?

you are here) 109


SimpleDotComGame class

Just as you did with the SimpleDotCom class, be thinking about parts of this code
you might want (or need) to improve. The numbered things • are for stuffwe
want to point out. They're explained on the opposite pag e. Oh, if you 're wonder-
ing why we skipp ed the test code phase for this class, we don 't need a test class for
the game. It has only one method, so what would you do in your test code? Make
a separate class that would call maini] on t~is class? We didn't bother.

public static void main(String[] arqs) (

DECLARE 3 var i-
able to hold user
guess count . set it GameBelper helper '" new GameBelper (); e-r: this is a 1ft/.'Ial t1ass \role wv~ thdt has
to 0
t.he ...dhod +OY ~d±i,,~ ~ il'lf l< t.. +OY
l""Wl'IG it's part. ~ Java
l\O'<II,

MAKE a Simplefzot -
SimpleDotCom t:.heDotCom '" new SimpleDotcomO ; ~ .....lce the dot tOO>l objet+'
Com objec t

COMPUTE ,\
rando m num be r
be tween 0 and .\
int randomNum = (int) •
(Mat:.h.random() ... 5) ;b--lft<1lce a ril,wf"", l'I"",beY.toy the
tell, and lUe it to ~ke the leU
~ lotdtiOt\.! array
.first

MAKE an int ar ray


WIth the 3 cell loca- let(] locations • (randamNum, randOlllNum+l, rand0lllNUm+2);
lions, and
thaDotCom. IIstLocationCells (locations) ; .
~ ~,ve
L1..
v>e
dot tQtI\ ih lotdtiOtlS (th, C1Yril'1)
INVOKE seu.oca -
[lonCells on the do t
corn ob ject boolean isAli va '" true;

DECLARE a boo l-
eat" sAlive

WHILE the dot


co m 1\ still alive

GET user' input


II CHE.CK It
INVOKE checkro-
ursell() on dot co m
IN C R EM E N T
nurnO fGuesses
IF re ult is " kill"
SET gameA live to
false

PRINT the number


of user gue sses II c l o s e if

II c lose while

- II close main

chap ter 5
writing a program

jf...ro things that need a bit more


,:xplain ing. are on this page, This is
. t a quick look to keep you going;
re details on the GameHelper
are at the end of this chapter.

Make a random
number

(Math.random() '" 5)
t
Atlau that tOfllts
t
A... rthoci ok the
wit.h Java. Mat.h daS$.

An 'l"rl,arU wt "'<id.t tdrlieY,


ok a t1ass that we bl/.ilt to
Getting user input hell' wit}, tnt ~...e. It' s ~lItd
using the GameHelper qaft't~tlfeY a"d 'feN haVbl t
class set" it yd ('fov wilD.
~
String guess = helper.getUserInput("enter a number");

i l'
A...ethod o..f the ~a...t!'+e'ft"r tlau
~t asks the w.ser ~ot' toow.",a"d-
li"e i"f\lt, \'"ealb it in .»u.-
-the
1ISe'r hits R~Tl).RN, ahli ~'Ives batk
the ytsl/.I-c clS a Sh-i,,~.

you are here) 111


GameHelper class (Ready-bake)

One last class: G-attteHelper


We made the dot CQtn class. Just copy* the code below and compile it into
a class named GameHelper. Drop all three
We made the game class.
classes (SimpleDotCom, SimpleDotComGame,
All that's left is the helper class- the one with the GameHelper) into the same directory. and make it
getUserInputO method . The code to get command- your working directory.
line input is more than we want to explain right now.
It opens up way too many topics best left for later. "Ready-IMke
(Later, as in chapter 14.) Whenever you see the Bell de logo, you're see-
ing code that you have to type as-is and take on faith .
Trust it, You'Illeam how that code works later.

import java.io.* ;
public class GameBelper
public String getOserlnput(String prompt)
String inputLine = null;
System.out.print(prompt +" ");
try {
Bu£feredReader is = new BufferedReader (
new InputStre~ader(SY8tem.in);

inputLine = is.readLine();
if (inputLine. length () == 0) return null;
} catch (IOException e) (
System.out.println("IOException: " + e);

return inputLine;

"We know how much you enjoy typing . bul for thoee rare
moments When you'd mlher do some\hlng else , we'vil mad II
11111 Ready-bake Code avallable on wlckedlyamart.com.

112 chapter 5
writing a program

lefs play What's this? Abug?


Gaspl
Here's what happens when we Here's what happens when we
run it and enter the numbers enter 1.1,1.
1,2,3,4,5,6. Leckin' good.

Acoltlplete gatMll lltteractlolt Adlfferettf gaIMe h,teractlotl


(your mileage may vary) (ylkes)

%j a v a SimpleDotComGame %j ava SimpleDotComGame


enter a number 1 enter a number 1
miss hit
enter a number 2 enter a number 1
miss hit
enter a number 3 enter a number 1
miss kill
enter a number 4 'lou took 3 guesses
hit
enter a number 5
hit
enter a number 6
kill
You took 6 guesses
It's a cliff-hangerl
Will we find the bug?
Will we flxthe bug?

Staytuned r the next chapter,where we answer


these quest! ns and more...
And In the meantime,see If you can come up with
Ideasfor what went wrong and howto fix It.

you are here. 113


for loops

More about for loops


We've covered all the game code for this chapter (but we'll pick it up again
to finish the deluxe version of the game in the next chapter). We didn't
want to interrupt your work with some of the details and background info,
so we put it back here. We'U start with the details of for loops, and if you're
a Ct+ programmer, you can just skim these last few pages ...

legular bto"-e.,ha"ced] for loops

repeat for 100 reps:

What It means In plain English: ~Repeat 100 times ."


How the complier sees It:
• create a variable I and set It to O.

-;. repeat while II siess tha n 100.

• at the end of each loop IteratIon, add 1 to I

Part One: Initialization


Use this part to declare and Initialize a variable to use within the loop body.
You'll most often use this variable as a counter.You can actually initialize more
than one variable here, but we'll get to that later In the book.
Part Two: boolean test
This Is where the conditional test goes. Whatever 's In there, It must resolve to a
boolean value (you know, tru« or flllu) . You can have a test" like (x >= 4), or you
can even Invoke a method that returns a boolean.
Part Three: IteratIon expression
In this part, put one or more things you want to happen with each trip through
the loop. Keep In mind that this stoff happens at the end of each loop.

114 chapter 5
writing a program

output:
sthrough a loop ~
int i = 0; i < 8; i++)
tem.out.println(i);

enter loop
body
++
Pre and Post Increment/Decrement Operator
print the value
of; The shortcut for adding or subtracting 1 from a variable.
X++;
Increment Is the same as:
(the iteration
expression) X = X + 1;
They both mean the same thing in this context:
"add 1 to the current value of x" or ·'ncrement x by 1·
And:

p has only the boolean test; It doesn't have X--;


I_!I!!I~-in in it ializat ion or Iteration expression. A while Is the same as:
good when you don't know how many times to
just want to keep going while some condl-
X = X I-I
ue. But If you know how many tl mes to loop Of course that's never the whole story.The placement of the
• e length of an array, 7 times, etc.), a for loop Is operator (either before or after the variable) can affect the re-
t , Here's the loop above rewritten using while: sult. Putting the operator before the variable (for example, ++x),
means:'!irst, increment x by 1, and then use this new value of x."
This only matters when the ++x Is part of some larger expres-
. .
11:lt 1. = 0; ~
"lII,<---~, jllitia/i~ ih
'lJe helv.. 1 d I
et. ire dl'ld
sion rather than just in a single statement.
int x = 0; int z = ++x;
while (i < 8) e lOlAl'\k
produces: )( Is I, z Is 1
System.out.println(i);
But putting the ++ after the x give you a different resuIt:
i++; ~ , J..;t have to illl
Ule lOlA;,k I'"e"'e,.,f int x '" 0; int z c x++;
produces: )( Is I, but z Is 01 z gets the value of x and then x is
Incremented.

you are he re ' 115


..
enhanced for

The etthattced for loop


Beginning with Java 5.0 (Tiger), the Java language has a second kind of Jor loop
called the enhanced jM, that makes it easier to iterate over all the elements in an
array or other kinds of collections (you'll learn about othercollections in the next
chapter). That's really all that the enhanced for gives you-a simpler way to walk
through all the elements in the collection, but since it's the most common use of a
for loop, it was worth adding it to the language. We'll revisit the enhancedfor lMp in
the next chapter, when we talk about collections that aren't arrays.

What It means In plain English: "For each element in nameArray, assign the
element to the 'narne'varlable, and run the body of the loop."

How the complier sees It:


... Create a String varIable called name and set It to null.

... Assign the first value In nameArray to name.

... Run the body of the loop (the code block bounded by curly braces).

... Assign the next value In nameArray to name.

... Repeat while there are stili elements In the array.

Part One: Iteration variable declaration


Use this part to declare and Initialize a variable to use within the loop body, With each
Iteration of the loop. this variable will hold a different element from the collection. The
type of this variable must be compatible with the elements in the arrayl For example,
you can't declare an lnt Iteration variable to use with a StrlngU array.

Part Two: the actual collection


This must be a reference to an array or other collection. Again, don't worry about the
other non-array kinds of collections yet-you'll see them in the next chapter.

116 chapter 5
writJng a program

converting a String to an int Casthtg


iDe quess = Int8qer .parseInt(strinqGuess); prhttftives
The user types his guess at the command-
line, when the game prompts hi m.That
guess comes In as a String (M2;"0~ etc.) ,
and the game passes that String into the
checkYourselfO method.
But the cell locations are simply lnts In an
array,and you can't compare an Int to a
String.
For example, this won't work:
long ~ short
can be cast to
. tx" 2;
. (x = num) II horrible explosionl
rying to compile that makes the complier
but you might
lau gh and mock you: lose something
o per a t o r ==
cannot be applied to
int,java .lang .String In chapter 3 we talked about the sizes of the various primitives. and how you
if (x == nurn) { } can'tshove a bIg thIng dlrecUy Intoa small thing:
,., 10n9 Y = 42;
int x = y; II won't compile
So to get around the whole apples and A long Is bigger than an int andthe complier can't besure where that long has
oranges thing, we have to make the String been. It might have been outdrinking with the other longs, andtaking on really
'2"into the int 2. Built Into the Java class big values. To force the complier toJam the value of a bigger primitive variable
brary is a class called Integer (that's right intoa smaller one, you can usethe casl operator. II looks likethis:
a Integer class, not the int primitive), long y == 42; II so far so good
and one of its Jobs is to take Strings that
represen: numbers and convert them Into int x = (int) y; II x = 42 oool!
actual numbers. Puttlng In the ~ tells the complier to take the value of y,chop It down to iot
size, and sat )( equal towhatever Is left. If thevalue of y was bigger then the
maximum value of x, then what's left will be a weird (butcalculable') number:
long y == 40002;
takes d ~b-i,,~ II 40002 exceeds the 16-bit limdt of a short

t short x c (short) y; II x now equ~s -25534!

teger.parseInt ("3") Stili,Ihe point is that the complier letsyou do It. And let's sayyou have a noal-
Ing point number, andyou just want to get at the whole number (in/) partof it

d ...etJ,od
I in the I"u~et"
float f .. 3.14£;
int x == (int) f; II x will equal 3
das.s that knows how io And don't even think about casting anything \0 a boolean or vice versa-just
"pa~J) a Sb-in~ i"io the walk away.
il'.t: it l"epl"C!seni.s.
'It involves sign blls, bInary, 'two's complement' and other geekery, all of which
arediscussed ai/he beginning of appendix B.
you are here _ 117
exercise: Be the JVM

BEtheJVM
The Java file on this page
represents a complete source
rue. Your job is to play JVM
and detel"llline what would be
the outpltt when the
program runs?

class Output {

pUblic static void main(String [J args) {


Output 0 = new Output();
o.go() ; -or-
}

void go() {
int y = 7;
for(int x = I: x < 8: x++) {
y++;
if (x > 4) {
System.out.print(++y + • -): -or-

i f (y > 14) {

Systern.out.println( U x = u + x);

break;
}

118 chapter 5
writing a program

Code Magnets
A working Java program Is all scrambled up on the fridge . Can you
reconstruct the code snippets to make a working Java program that
produces the output listed below? Some of the curly braces fell on the
floor and they were too small to pick up, so feel free to add as many of
those as you need!

1) {

System.out.println(x + ~ M + y):

4; Y > 2; y--) {
for(int Y

for(int :l( 0; x < 4; x++) (

you are here ~ 119


puzzle: JavaCross

JavaOr~ss
How doesa crossword puzzle
help you leam Java? Well,all
of the words are Java related.
In addition,the cluesprovide
metaphors, puns. and the like.
These mental twists and turns
bum alternateroutes to Java
knowledge,right into your
bralnl

Across Down
1. Fancy computer word 20. Automatic toolkit 2. Incrementtype 21. As if
for build 3. Classs workhorse 23. Addafter
22. Looks likea primltfve.
4. Multi-part loop buL 5. Pre Is a type of _ _ 24. PI house
6. Test first 25. Un-castable 6. For's Iteration _ _ 26. Compile it and__
7.32 bits 26. Math method
7. Establish first value 27. ++ quantity
10. Method'sanswer 28. Convertermethod
8. Whileor For
, 1. Prepcode-esque 29. Leave early
9. Updatean Instance variable
13. Change 12 Towards blastoff
15.The bigtoolkit 14. A cycle
17. An arrayunit 16.Talkative package
, 8. Instance or 10C41 19. Method messenger
(abb rev)
writing a program

A short Java program is listed below . One block of the program


is missing. Your challenge Is to match the candidate block of
code (on the left), with the output that you'd see If the block
were inserted. Not all the lines of output will be used,and some
of the lines of output might be used more than once. Draw lines
connecting the candidate blocks of code with their matching
command-line output.

class MixForS (
public static void main (String [) args)
int x = 0;
int y = 30;
for (int outer = 0; outer < 3i outer++) (
for(int inner = 4; inner> li inner--) {

y = y - 2;
if (x == 6)
break;

x = x + 3;
}
y = y - 2;
}
System.out.println(x + " " + y};

Candidates: Possible output:

X + 3~ 45 6 ~-\:t.'"' tat"
t.a~i6at.t 'fI~
x + 6~ 6 Qt\t~t.ht
yo"\b\t ~~h
x + 2~ 6

10

+ O~

you are here ~ 121



exercise solutions

Be the JVM: Code Magnets:


class Output { class HultiFor {

public static void main(String [ ) args) { public static void main(String [] args) {
Output 0 = new Output();
for(int x 0; x < 4; X++) {
o.go() ;
}
for(int y = 4; Y > 2; y--) {
void go{ ) { system.out.println(x + U U .;. y);
int y = 7; }

for(int x =: i I. x < B'I x++) {


y++;
i f (x =:= 1) { What would happen
x++ ; If this code block came
i f (x > 4) {
before the 'y' for loop?
System.out.print(++y + • h); }
} }

i f (y > 14) {

system.out.println(U x = h + x);

break;

} Did you remember to factor In the


break statement? How did that
affect the output?

122 chapter 5
writing a program

Candidates: Possible output

x • x + 3;

x • x + 6;

x • x + 2;
x++;

x--;

x - x + 0,

you are here • 123


6 get to know the Java API

Using the Java Library

Java ships with hundreds of pre-built classes. You don't have to

reinvent t he wheel If you know how to f1 nd what you need In the Java IIbra ry, known as

t he Java API. You've got better things to do . If yo u're go ing to write code, you mig ht aswell
write only the parts that are truly custom for your application. You know those programmers

who walk out the door each night at 5 PM? The ones who don't even show up until lOAM?

They use the Java API. And about eight pages from now, so will you. The core Java library
Is a giant pile of classesJust waiting for you to use like building blocks, to assemble your own

program out of largely pre-bullt code .The Ready-bake Java we use in this book Is code you

don't have to create from scratch, but you stili have to type It. The Java API is full of code you

don't even have to type. All you need to do is learn to use it .

this Is a new chapter 125



we stili have a bug

Itt our last chapter, we left you


with the cliff.. ha.,ger. Abug.

How ifs supposed to look How the bug looks


Here's what happens when we Here's what happens when we
run it and enter the numbers enter 2,2,2 .
1,2,3.4,5,6 . Lookin' good.

Aco~plete galMe I.,teractlon Adifferent galtle Interact/o.,


(your mileage may vary) (yikes)

Fllo Ed~ Window He Felnl

~ j a va SimpleDotComGame
enter a number 2
hit
enter a number 2
hit
enter a number 2
kill
You took 3 guesses

hi the CUffltlt verslotl. otlce


you geta hit, you catl shttplv
repeat that hittwo tMore
tlllles for the kill!

126 cha pter 6


get to know the Java API

So what happetted?

public String checkYourself (String stringGuess) (

int guess'" Int:8ger.pa.rselnt{stringGue8S); (-- fon\l~ the Sh-ill~


1;Q all lilt.
Strinq reBUlt '" ''miss''; ( - A1ake cl va~jable t.D hold the reswi: 'II
rttwhl p.,.e II " we
(' . ...iss i\'\ as the detault
I. e. lIIe as.s""'e 8 u... iss''),

for (int cell loeationCells)

Here's where It
goes wrong. We
counted a hit every ~
time the user
guessed a cell
location. even If
that location had
already been hit!

We need a wayto
II end foz:
know that when
a user makes
if (numOfHits = locationCells . length)
a hit, he hasn't
previously hit that result::: "kill";
cell. If he has, then
we don't want to II end if
count It as a hit.
System . out.println (result) j ~ Di1fla'f the res"l! k()lr the lI.1Cr
return result;
(..... i~", ",,1e1S it waJ i.hcl,,~ed to "hit" CW' "1cill U ) .
r-, R~ the "mit baLk to
II e n d me t h od the talli~ "'«hod.

you are here. 127


fixing the bug

How do we fix it?


We need a way to know whether Q cell has already been hit. Let's run
through some possibilities, but first, we'll look at what we know so for...

We have a virtual row of 7 celts, and a DotCom will occupy three


consecutive cells somewhere in that row. This virtual row shows a
DotCom placed at eel/locations 4,5 and 6.

The DotCom has an instance variable-an int array-that holds that


DotCom object's cell locations .

locatlonCells
(instance variable of
the DotCom)

• OptlO" o"e
We could make a second array, and each time the user makes a hit, we
store that hit in the second array. and then check that array each time
we get a hit. to see if that cel/ has been hit before.

kltCells arra~
(this would be 0
new boolean array
instance variable of
the DotCom)

128 chapter 6
get to know the Java API

Option one is too clunky


Option one seems like more work than you'd expect. It means that each
time the user makes a hit, you have to change the state of the second
array (the 'hitCells' array), oh -~ but first you have to CHECK the 'hitCeJls'
array to see jf that cell has already been hit anyway. It would work, but
there's got to be something better...

• OpfloHtwo
We could just keep the one original array, but change the value of any hit
cells to -1. That way, we only have ONE array to check and manipulate

locQtlonCells
(instance var iable of
the DotCom)

Option two is a little better, but


still pretty clu"ky
Option two is a little less clunky than option one, but it's not very efficient. You'd
still have to loop through all three slots (index positions) in the array, even jf
one or more are already invalid because they've been 'hit' (and have a -1 value).
There has to be something better...

you are here I 129


prep code
prep code

Optlo., three
We delete each cell location as it gets hit, and then modify the array to
be smaller. Except arrays can't change their size, so we have to make a
new array and copy the remaining cells from the old array into the new
smaller array.

locatlonCells array
BEFORE any cells
have be.en hit

locatlonCells array
AFTER cell '5', which
was at inde.x 1 in the.
array, has been hit

Optlo., three would be 'Much better Ifthearray could shrlttlc, so that we would.,'t have
to ",ake a .,ew ''Maller array, copy there",altt'"(1 values ht, attd reasslQ" thereferettce.

fhe orlal"81 prepcode for partof the Life would be good 'f otdy we could
checkYourselfU 'Method: chattae Itto:
REPEAT with each of the location cells in the int array . ~. -REP EAT with each of the remaining locat ion cells
1/COMPARE the user guess to the location cell /1 COMPARE the user guess to the location cell
I F the user guess matches IF the user guess matches
INCREMENT the number of hits ~ REMOVE this cell from the array
/1 FIND OUTif it was the last location cell: 1/ FIND OUTif it was the last location cell:
IF number of hits is 3. RETURN "kill" ~ 'IF the array is now empty, RETURN "ki ll"

ELSE it was not a kill, so RETURN"hit" ELSE it was not a kill. so RETURN"hit"
END IF END IF
ELSE user guess did not match, 50 RETURN "miss" ELSE user guess did not match, so RETURN "miss"
END IF END IF
END REPEAT END REPEAT

130 chapter 6
get to know the Java API
when arrays aren't enough

Wake up at1d stMell the library

As if by magic, there really Is such a thing.

But it's not an array, it's an ArrayLisf.

A class in the core Java library (the API).

The java Standard Edition (which is what you have unless you're work-
ing on the Micro Edition for small devices and believe me, you'd know)
ships with hundreds of pre-built classes. Just like our Ready-Bake code
except that these built-in classes are already compiled.

That means no typing.

Just use 'em.


ArrayUS t

dd{Ob}ed e\en") aram eter to the \\st .


a Adds the object P
et er.
Ont. of a 5az..illiol\ t1asst.$ in eUnt Index) h \nde)( paralTl
t.ht. Ja~a libvavy. ren"o" he object at t e
Removes t
Yo... tan lASt. it itl 'fOlJ.V cede {Ob}ed elel1\) t' 'I' the AnayLlst).
as i+ yOlJ. IIIrOU if 'f0.. ~I.f. rel1\o"e thIs object (If I s
RelTl oves
) arameter
. {Object e\en" h for the object P
,o"ta,n s , 'If there'S a mate
Returns trUe
II . \em entS
\sEI1\PtV . If the list has no e
RetUrns true ,
, ) eter, or '
\"dellOf{Obiec~ ~:~de)( of the object paralTl
RetUrns elthe
currently In the list
s\zell h number of elements
RetUrns t e
(NoU; tht add(ObjttA:. ele...) ...tthod aram et er
att..ally look.s a li-i:.Be sh-a"1& ~a .. -tht ge tt\nt Indell)
the obleet eur r ently at the.l.n.de.'Il.p .
Returns
OY\e ..,e'~t shOWtl h,~e ... ..,,'11 ~tt to -the
..tal Qrle lai& i .. tht book. FOfr ""'''', jlA1t
think of it as a.. aodO ...tihod that
take.! the objett yo<. ",ant to addJ

132 chapter 6
get to know the Java API

Some thhtgs you ca., do with ~rrayLisr


~
a~\e-h--6t.ket ~"jI,
D '~wt:IrT'f a~ this ",ew': -.T. , l o.f c, ol:!' eth"·
'"' .~. t I\S U....akt IS a \In. "j~ ~
• Make one ? . . i~~t "ow; I jW Mea _ .

ArrayList<Egg> myList = new ArrayList<Egg> () ; ~-a'1l,ist objet~ \ 'We


/'I ~ (\P tnt \leaf' \~ 5 ,
tvea~ci ,~ ...w,

• Put something in it
Egg s = new Egg() i
\)eLi~ no' CW'Y "I

myList.add(s)i

• Put another thing in it


Egg b = new Egg();

myList.add(b);

• Find out how many things are in it


int theSize = myList.size();

Find out if it contains something The A'rt"a'1L.i.st. Dol:S tC/tItail'l the ~~


I / " .... ,.__ I.e! ku '5', so tC/tItail\SO retWY\S ~
, tltd
boolean is10 = myList.contains(s)i ~ ~~.~~ ~1

" D 0 (... eal\S ~irtt. ;Yllie~ is 0)


Find out where something is (l.e. its index) ~ Atta'1Ust 15 ~ Last ,. _ . 0 D'f '0' ..,os the
int idx = myList .indexOf(bl i
d '."te the Objet.. vt-tc;·~t
01'1 51 l"
I
' l.\. \.--1. i\'lO~'W .... eboVl\S_
sUO\'IO ..hl"~ lY\ 'We In"

Find out if it's empty it's deo.fil'li+.tly NOT bftpty, so isE"'rtyO


boolean empty = myList. isEmpty (); C- r~PIS £ili.e
• Remove something from it
myList.remove(s);

you are here. 133


when arrays aren't enough

~ your penCil Fill In the rest of the table below by looking at the ArrayList code
on the left and putting in what you think the code might be if it
were using a regular array Instead. We don't expect you to get all
of them exactly right, so Just make your best guess.

ArrayList regular array


hrrayList<String> myList = new
~h-i"9 0 "'yList ::.. "ew Sh-il'l~ClJj
hrrayList<String>();

String a = new String("whoohoo H ) ;


Sb-il'l'l a =- ~ Sb-i~("whoohool)j
myList.add(a);

String b = new String("Frog H )


~iri,,~ \> ::. """ ~ir;I'I~C'n-~»)j
;

myList. add (b) ;

int theSize = myList.s izeO:

Object 0 = myList.get( l);

myList.remove(l);

boolean isIn = myList.contains(b);

134 chapter 6
get to know the Java API
;\.

Java'&pos~
R..,: So Arl1lyListIs cool, but This week's Interview:
ArrayList. on arrays
how would I know It exists?
HeadFirst So, ArrayLists are like arrays, right?
!A.: The question is really, ArrayLlst In their dreams! I am an objec: thank you very much.
-How do I know what's In the
HeadFirst If I'm not mistaken, arrays are objects too. They live on the heap right
API?" and that's the key to your
success as a Java programmer. there with all the other objects.
Not to mention your key to ArrayList Sure arrays go on the heap, duh, but an array is still a wanna-be
being as lazy as possible while ArrayList. A poser. Objects have state and behavior, right? We're clear on that. But
still managing to build software. have you actually tried calling a method on an array?
You might be amazed at how
much time you can save when HeadFirst Now that you mention it, can't say I have. But what method would I
somebody else has already done call, anyway? I only care about calling methods on the stuff I put in the array, not
most of the heavy lifting, and the array itself. And I can use array syntax when I want to put things in and take
all you have to do is step in and things out of the array.
create the fun part.
ArrayUst Is that so? You mean to tell me you actually remooed something from an
But we digress... the short
array? (Sheesh, where do they train. you guys? Mljava's?)
answer Is that you spend some
time learning what's In the core HeadFirst Of &OlITSe I take something out of the array. I say Dog d = dogArray[l)
API. The long answer is at the and J get the Dog object at index lout of the array.
end of this chapter, where you'll
learn how to do that. ArrayList Allright, I'll tty to speak slowly so you can follow along. You were 1UJ1,
I repeat TUI~ removing that Dog from the array. All you did was make a copy of the
rifmnce to tht Dog and assign it to another Dog variable.
R: But that's a pretty big
Issue. Not only do I need to
HeadFirst Oh, I see what you're saying. No I didn't actually remove the Dog
know that the Java library object from the array. It's still there. But I can just set its reference to null, I guess.
comes with ArrayLlst, but more ArrayLlst: But I'm a first-class object, so I have methods and I can actually, you
Importantly I have to know know, M things like remove the Dog's reference from myself, not just set it to null.
that ArrayList Is the thing that And I can change my size, dynami£al£y (look it up). Just tty to get an ami)' to do that!
can do what Iwantl So how
110 I go from a need-to-do- HeadArst Gee, hate to bring this up, but the rumor is that you're nothing more
something to a-way-to-do-It than a glorified but less-efficient array. That in fact you're just a wrapper for an
using the API? array, adding extra methods for things like resizing that I would have had to write
myself. And while we're at it,J'OU can't even haM primiJiDes! Isn't that a big limitation?

!A..:Now you're really at the ArrayList I can't believe you buy into that urban legend. No, I am not just a less-
efficient array. I will admit that there are a few extmne{y rare situations where an
heart of It . By the time you've
finished this book, you'll have array might be just a tad, I repeat, tad bit faster for certain things. But is it worth the
agood grasp of the language, miniscule performance gain to give up all this poWa'. Still, look at all tlllsflexihiliry. And
and the rest of your learning as for the primitives, of 'dum you can put a prirntive in an ArrayList, as long as it's
curve really Is about knowlnq wrapped in a primitive wrapper class (you'll see a lot more on that in chapter 10).
now to get from a problem to And as ofJava 5.0, that wrapping (and unwrapping when you take the primitive out
a solution, with you writing the again) happens automatically. And allright, I'll Q£krwwledge that yes, if you're using an
least amount of code. If you can
ArrayList of primitives, it probably is faster with an array, because of all the wrapping
be patient for a few more pages,
and unwrapping, but still... who really uses primitives Uu.se days?
we start talking about it at the
!nd of this chapter. Oh, look at the rime! I'm llJujor Pilaus: We'll have to do this again sometime.

you are here ~ 135


difference between ArrayList and array

CotMparhtg ArrayList to a regular array

ArrayList regular array


ArrayList<String> myList = new String [] myList = new String[2J;
ArrayList<String>();

String a = new String("whoohoo"); String a = new String("whoohoo");


myList.add(a) ; myList[O) = a;

String b = new String ("Frog") ; String b = new String("Frog");


myList.add(b); myList{l) = b;

int theSize = myList.size(); int theSize = myList.length; ~ ,


\ \\eY~ s ..,'ncYt
= myList.get(l); rl;s tp \oo\t.
\ ~a\\'t d'~~eYO\t...: t
Object 0 String 0 = myList(l];

myList.remove(lj; myList(l] = null; ..,..

boolean isIn = myList.contains(b); boolean isIn = false;

for (String item : myList) (

if (b. equals (item)) {

isIn = true;

break;

Notice how with ArrayList, you're working With an arra)', you use special array syntax (like
with an object of type ArrayList, so you're just myList[O] = foo) that you won't use anywhere
invoking regular old methods on a regular old else except with arrays. Even though an
object, using the regular old dot operator. array is an object, it lives in its own special
world and you can't invoke any methods on
it, although you can access its one and only
instance variable, length.

136 chapter 6
get to know the Java API

CotMparit1g ArrayList to a regular array

• A plain old array has to know its


size at the time it's created.
But for Arrayl.ist, you just make an object of
type Arrayl.ist, Every time. It never needs to
Arrays use array syntax that's not
used anywhere else in Java.
But ArrayLists are plain old Java objects, so
they have no special syntax.
know how big it should be , because it grows
myList[l]
and shrinks as objects are added or removed.
~ ~ .\
n ew Str ing[2] Needs 0 siu· The ott0'l Lo\"otkets [ J o\"e sfet,o
s'll'lta~ l,ISed 01'1\'1 kO't' attd'ls.
new ArrayList<String>( )

No siu \"e,"'i\"eo (olthOl,\~h YOl,\ tan


~ive it 0 siu i~ yo", wont to).

• To put an object in a regular array,


you must assign it to a specific
location.
• ArrayLists in Java 5.0 are
parameterized.
We just said that unlike arrays, Arrayl.ists
have no special syntax. But they do use
(An index from 0 to one less than the length of
something special that was added to Java 5.0
the array.)
Tiger-paramet:erized types.
myList[l] = b;
Ar rayList <String>
~
Needs oYl il'lde~.

If that index is outside the boundaries of the


'"
The <St\"il'l~> in ol'l~le b\"otlcets is 0 "-t'ife
fo\"offtete\"". A\"\"oyList<St\"il'lg> ffteal'lS Sifftf1y "0
array (like, the array was declared with a size of list ~ Stril'lgs", oS offosed to AttoyList<Dog>
2, and now you're trying to assign something whith ""eons, "0 list ~ Dogs".
to index 3), it blows up at runtime. Prior to Java 5.0, there was no way to declare
With ArrayIist, you can specify an index us- the type of things that would go in the
ing the add(anlnt, anObject) method, or you ArrayList, so to the compiler, all ArrayIists
can just keep saying add(anObject) and the were simply heterogenous collections of
ArrayList will keep growing to make room for objects. But now, using the <typeGoesHere>
the new thing. syntax, we can declare and create an
myList.add(b) ; ArrayIist that knows (and restricts) the
-, types of objects it can hold. We'll look at the
details of parameterized types in ArrayLists
No il'ldex. in the Collections chapter, so for now, don't
think too much about the angle bracket <>
syntax you see when we use Arrayl.ists, Just
know that it's a way to force the compiler to
allow only a specific type of object (the type in
angle brackets) in the ArrayList.

" _" ........_ L.. ...


the buggy DotCom code

Letl fix the t'otCOItt code.

int(] locationCells;
int nurnOfHits = OJ

publ ic void setLocationCells(int[] locs) (


locationCells = locs;

public String checkYourself(String stringGuess)


int guess = Integer.parselnt(stringGuess);
String result "miss ";

fo r (i nt ce ll locat i onCe l l s )

break;
}
I I ou t o f: t he l oop

if (numOfHits == l oc a t i o nCe l l s . l e ng t h )
result. = " ki l l " ;

System.out .println(resul t);


return result;
/ / c l os e me t h od
I I c l ose cl a s s

138 chapter S
get to know the Java API

prep code ID~~

New and hMproved PotCOtM class

import

publ ic class DocCom I

p r Lva t e ArrayList<Strinq> locationCells ;


/ / pri v at e i n c nurnOf<Ji t ~ ~-a L.irt. that. ho\ds Shin~S -
// don ' t n e ed t.ha c now C Lhe Shinl1 a"r.,.a~ to an f\n ~
ha"ljl", .(;)

publi c vo id se t Locat ionCe lls (ArrayList<String> Loc) ! l'll "al'l'l-


locat ionCe lls = loc; _ .,.-o'ItO a'(~l>J"t
~t'tI a"d ""r-

public String checkYours e lf (String user Inputl


/'"
(
"t \I.SC'f"~!>S
f ind out, tne - ~orr ib inde~
is i" t.he

~
An-a~L.-'st... b ~l~skll~1) t.hen i,..oe-d)tO
I~r ",l.'s
l '" 1St.
String result = " mi s s" ; '"
_A
.-'"
",I'll

y~'n\S a -l-
int index = locationCells.indexOf(userlnput):
if (index >= 0) {

if (locationCells.isEmpty(»
result "kill";
else I
result c: "h it";
I I c l os e if

II c l os e ou e r if

return r esult;
) II c lose method
I I cl os e c l a s s

you are here. -1 3 9


making the OotComBust

Let's build the REAL galtte:


HSi"k a Pot COItt M

We've been working on the 'simple' version, but now


let's build the real one. Instead of a single row, we'll You're going to build the
use a grid. And instead of one DotCOID,we'll use Sink a Dot Com game, with
three . a 7 x 7 grid and three
Goal: Sink all of the computer's Dot Corns in the Dot Cams. Each Dot Com
fewest number of guesses. You're given a rating level takes up three cells.
based on how well you perform.
Setup: When the game program is launched, the
computer places three Dot Corns, randomly. on the
virtual. 7:x. 7 grid . When that's complete, the game
asks for your first guess .
partof a gattte I.,teractlo.,
How you play: We haven't learned to build a GUI
yet, so this version works at the command-line. The 't j ava DotComBust
computer will prompt you to enter a guess (a cell), Enter a guess A3
which you'll type at the command-line (as "A3n, WCS\
etc.) , In response to your guess, you'll see a result at miss
the command-line, either "hit", "miss", or "You sunk Enter a guess 82
Pets.com" (or whatever the lucky Dot Com of the day miss
is) . When you've sent all three Dot Corns to that big
404 in the sky, the game ends by printing out your Enter a guess C4
rating. miss
Enter a guess 02
7 )<. 7 ~__id
hit

A k V Enter a guess D3
hit
B
E Enter a guess 04
( q Ouch! You sunk Pets.com
N

o i ....p L;~ kill


I· .~ .,.~~,~c f~~~~
Enter a guess B4
E
miss
F Enter a guess G3
hit
G
RS.IrMe~c ~m
I. '. Enter a guess G4
o 1 2 345 6
hit
\ start.s at ZbO, like Java ar'ra'f~ Enter a guess G5
Ouch! You sunk AskMe .com

140 chapter 6
get to know the Java API

What tteeds to chattge? DotComBust class continued.••


We have three classes that need to change: the o Put the DotComs on a grid rather than
DotCom class (which is now called DotCom instead of just a single row, and do it for all three
SimpleDotCom), the game class (DotComBust) and the DotComs.
game helper class (which we won't worry about now). This step is now way more complex than
o DotCom class
before, ifwe're going to place the DotComs
randomly. Since we're not here to mess
o Add a name variable with the math, we put the algorithm for
to hold the name of the DotCom giving the DotComs a location into the
("Pets.com", uGo2.com~, etc.) so each Dot- GameHelper (Ready-bake) class.
Com can print its name when it's killed (see
the output screen on the opposite page). @ Check each user guess with all three

o DotComBust class (the game)


DotComs, instead of just one.
@ Keep playing the game (i.e accepting
o Create three DotComs instead of one. user guesses and checking them with the
remaining DotComs) until there are no nwre
o Give each of the three DotComs a name. live DotComs.
Call a setter method on each DotCom
instance, so that the DotCom can assign the o Get out of main. We kept the simple one in
name to its name instance variable. main just to... keep it simple. But that's not
what we want for the real game.

3 Classes:
DotcomBlItt DotCom Gam.Helper

The game class. The actual The helper class


Makes DolComs, DotCom objects. (Ready-Bake).
gels user Input, DolComs know their It knows how to
plays until all001· name. location, and accept user com-
Corns are dead how 10 check a user mand-llne input,
gu6SS for a match. and malle DOICom
locations.

Plus 4
ArrayLists: 1 for
the DotComBust
5 Objects: and 1 for each
of the 3 DotCom
objects.

DotComBust GameHelper

you are here ~ 141


detailed structure of the game

Who does what it' the PofColMJust gatMe


(at'd whetd

DotCom8u" The mainO method

o The game
class.
instantiates in the DotComBust
class instantiates the
DotComBust object that
does all the game stuff.
DotComBust
object

The DotComBust (game)


object instantiates an
instance of GameHelper.
the object that will help
DotComBust the game do its work
object

The DotComBust object


instantiates an ArrayList
that will hold the 3 DotCom
objects.

ArrayList object (to


hold DotCom objects)

142 chapter 6
get to know the Java API

e The DotComBust object


creates three DotCom
objects (and puts them in
the ArrayList)

ArrayList object to
DotCom
hold DotCom objects
objects

The DotComBust object asks the The DotComBust object gives each of the Dot-
he/per object for a location for a Com objects a location (which the DotComBust
DotCom (does this 3 times, one for got from the helper object) like - A2 u • -B2-.
each DotCom) etc . Each DotCom object puts his own three
location cells in an ArrayList

ArrayList object
(to hold DotCom
cell locations)

Ar ray List
object

ArrayList
object

The DotComBust object asks the helper The DotComBust object loops through the list
object for a user guess (the helper of DotComs. and asks each one to check the user
prompts the user and gets input from guess for a match . The DotCom checks its locations
the command-line) ArrayList and returns a result ("hW. "miss", erc .)

ArrayList object
(to hold DotCom
cell lccctioas)

ArrayList
1If:Jl~91o bj ec t

And so the game continues ... get- ArrayList


ting user input. asking each DotCom object
to check for a match, and continuing
until 011 DotComs are dead
you are here ~ 143
the OotComBust class (the game)

prep code

DalComBUJt

GameHelper helper
ArrayUsl dolComsLlsl
Inlnurn OfGUB.'lS6S
-
Prep code for the real PotCOIM'ust class
The DotComBust class has three main jobs: set up the game, play the game
until the DotComs are dead, and end the game. Although we could map
those three jobs directly into three methods, we split the middle job (play the
selUpGameO
game) into two methods, to keep the granularity smaller. Smaller methods
slarIPlayingO (meaning smaller chunks of functionality) help us test, debug. and modify
checkUserGuessO the code more easily.
fin~GameO

DECLARE and instantiate the GomeHelper instance variable, named helper.


DECLARE and instantiate an ArrayUst to hold the list of DotComs (initially three) Call it
Variable dotComsLJst
DECLARE an int variable to hold the number of user guesses (so that we can give the user a
Declarations score at the end of the game). Name it numOfGuesses and set it to O.

DECLARE a setUpGameO method to create and initialize the DotCom objects with names
and locations. Display brief instructions to the user.
DECLARE a 5tortPlayingO method that asks the player for guesses and calls the
Method
checkUserGuessO method until all the DotCom objects are removed from play.
Declarations DECLARE a ched<UserGuessO method that loops through all remaining DotCom objects and
calls each DotCom object's checkYourselfO method.
DECLARE a ~nlshGomeO method that prints a message about the user's performance, based
on how many guesses it took to sink all of the DotCom objects.

METHOD: voId JetUpGGmeO


II make three DotCom objects andnome them
CREATE three DotCom objects.
Method
SET a name for each DotCom,
Implementations ADD the DotComs to the dotComsLJst ( the ArrayList).
REPEAT with each of the DotCom objects in the dotComsUst array
CALL the placeDotComO method on the helper object, to get a randomly-selected
location for this DotCom (three cells, vertically or horizontally aligned, on a 7 X 7 grid).
SET the location for each DotCom based on the result of the placeDotComO call,
END REPEAT
END METHOD

142
get to know the Java API

Method httpleltt8MtatioMS COMttMUad:


METHOD: void startPlaylng()
REPEAT while any DotComs exist
GET user input by calling the helper getUserinputQ method
EVALUATE the user's guess by checkUreI'GuessO method
END REPEAT
END METHOD

METHOD: void checkUserGuess(SCrlng userGuess)


/I find out if there's a hit (and kill) on any DotCom
INCREMENT the number of user guesses in the numOfGuesses variable
SET the local resul! variable (a String) to "miss", assuming that the user's guess will be a miss.
REPEAT with each of the DotObjeC1S in the dotComsUst array
EVALUATE the user's guess by calling the DotCom object's checkYourseJf() method
SET the result variable to "hit" or "kill" if appropriate
IF the result is "kill", REMOVE the DotCom from the dotComsUst
END REPEAT
DISPLAY the resul! value to the user
END METHOD

METHOD: void fJnlshGameO


DISPLAY a generic "game over" message,then:
IF number of user guesses is small,
DISPLAY a congratulations message
ELSE
DISPLAY an insulting one
END IF
END METHOD

rpen yoor p e n C i l - - - - - - - - - - - - - - - - - - ,
How should we go from prep code to the methods, And which method do you test
final code? First we start with test code. and and write first? See If you can work out some
then test and build up our methods bit by prep code for a set of tests. Prep code or
bit. We won't keep showing you test code even bullet points are good enough for this
In thIs book, so now It's up to you to think exercise,but If you want to try to write the
about what you'd need to know to test these rea/test code (In Java), knock yourself out,

you are here. 145


the DotComBust code (the game)

import java.util . *;
public c lass DotComBust
Annotat. the code
yourself.
Pr i va t e GameHelper helper new GameHelper() ;
Match the
~ private ArrayList<DotCom> dotComsList
f private int numOfGuesses
private void setUpGame () (
= 0;
= new AIrayList<DotCom>();
annotations 8t the
bottom of each
with the numbe...
...

II first make some dot corns and give them locations In the code. Writ.
the number In the
DotCom one = new DotCom();
slot In front of the
one .setName(-Pets.com"); eorr..pondlns


DotCom two = new DotCom(); annoldon.
two.setName("eToys.com H ) ;
DotCom three = new DotCom(); You'll u_ each
three .setName{ "Go2.com"); annotation Just once,
and you'll n.....11 of
dotComsList ,add {one);
the .nnotatlon•.
dotComsList,add(two);
dotComsList .add(three);
System.out.println("Your goal i s to sink three dot corns.");
System.out,println("Pets .com, eToys.com, Go2.com");
System.out,pr intln("Try to sink them all in the fewest number of guesses "):

for (DotCom dotComToSet : dotComsList) ( •


ArrayList<Str ing> newLocation = helper .placeDotCom(3); ~
dotComToSet .setLocationcellS(neWLocatiOn); ...
I I I c lose for loop
I I c los e s ec UpGame method

pr i va te void startPlayinq () (
while(!dotComsList,isEmpty() ( •
String userGuess = helper.getUserInput("Enter a guess"); ~
checkUserGuess(userGuess); •
I I I c l ose wh il e
linishGame () ; •
I I c lose sta rcPlay ing met hod

146 chapter 6
get to know the Java API

Whatever you do,


DON'T turn the
pagel
private void checkUserGuess (String u serGuess) {

numOfGuesses++; 4ID Not until you've


finished this
String r esult = " miss" ; ~ exercise.
for (DotCom d otComToTest : dotComsList) { ~ Our version is on
result = dotComToTest.checkYourself(u serGuess); ~
the next page.
if (result.equals("hit"» {
~
break; •
)


if (result.equals("kill"»
dotComsList.remove(dotComToTest);
b reak;

) I I c l os e fo r
System. out.println(result); •
II c lose method

private v oid finishGame ()


System.out.pri ntln("All Dot Corns are dead! Your stock i s now worth less.");
if (numOfGuesses <= 18) {
System.out.println(" It only took y ou" + numOfGues ses + " guesses.") ;
System.out.println(" You got out before you r op ti o n s sank.");
el se {
System.out.println("Took you long enough. " + numOfGuesses + " guesse s .");
System.out.println("Fish are dancing with your o p tio n s . " ) ;
}
I I close method

public s t a t i c void DUlin (S tring[] args) {


DotComBust game = new DotCOmBust();.
game . setUpGame () ; •
game. startPlaying () ; •
II close method

_ Pt'il'l't the
~es~lt to\'"
the ~et'
_ull the ~a",e objett
to set ~f the ~a...e

you are here ~ 147


the DotComBust code (the game)

import java.util.*;
pub Li,c class DotComBust

private GameHelper he l pe r "' new GameHelper () ; ~, ~


private ArrayLis t<DotCom> dotComsList = new ArrayLlst<DotCom> (); Ma\(( a" An-att atn
private int nurnOfGuesses = 0; DotCo'" ~jC:L .L'" 'II h~d
lis a l,st. Vla~ "'"
ONL.~ Dot:COf'I ~jctb,
private void setUpGame () ( ' w{: as pot£.or..() ...,oJd
/1 fust make some dot corns and give them locations J",tdll ..~II a"/ ok DotcOfl"
DotCom one = new DotCom(): o\>jtt.W.
one .setName("Pe ts.com") ;
DotCom two = new DotCom();
two .setName("eToys.com");
DotCom three ~ new DotCom();
three.setName("Go2.com");
dotComsList.add(one);
dotComsLis t.add(two) ;
dotComsList.add(three); Pyi\'lt b\-ie~

~
ir.st,n..l tions .foor \O.KY.
System,out.println("¥our goal is to sink three dot coms .");
System.out.println("Pets .com, eToys.com, Go2.com") ;
System .out.println("Try to sink them all in the fewest number of guesses");

f o r (DotCom dotComToSet : dotComsList) { ~Reytdt 'WoIith tdth DO'l:.COftI i" t~t list.
Ask t},c helt'e\' t.... a
ArrayList<String> newLocation = helper.placeDotCom(3); ~ D~ loUBOY\ ~a:.~
~a'1Lisi .J Sh,,,,..·..
dotComToSet. setLocationCells (newLocation) : ( - C<111 ih
DotCA...e ~~t" "'~
to . 't
.1, .
0" UlIJ
I / / c l.ose f o r loop j~ ~ot .(t"o1'V~j the 10t4i:ioh y04J.
I I close se t Upq ame, method ~ helpa-.

private void startPlayinq ()

while( !dotComsLi9t.is~mpty())

String userGuess = helper .getUserlnput ("E:nter a guess"); k""' ~et \O.KY i\'lflo+"
checkUserGuess(userGuess);~
C<111 ~ OWJI lhtl~1A L.
II cl o s e whi le
set'qlotU "'et.hod.
finis hGame(); ~ C<111 010"" 0""" +i"ish~a"'e ...tihod.
I J c l ose s C3rt Pl ay il1g method

148 chapter 6
get to know the Java API

private void checkUserGuess (String userGuess) {

numOfGuesses++;

String result \\miss"; t--asslA",e it's a '",iss', IAl'liess told oth«wise


for (DotCom dotComToTest dotComsList) { ~ \"eyeat with all DotCO\'I'IS il'l the list

result = dotComT oTest .checkYourself (userGuess); ~ ask the DotCO\'I'I to thet.k the Wie\"
~IAeSS, lookil'l~ ~O\" a hit (0\" kill)
if (result .equals(\\hit"» (

break; ~ ,ei ~~ o.f the loop ea\"ly, 1'10 poil'lt


<; 11'1 USt;II'I~ the others
)
if (result.equals("kill"» (

dotComsList.remove(dotComToTest);
break;

I I c l o s e for

System. out.println (result); ~ PY'il'lt the reslAlt +0\" the Wi«


II c l o s e met hod PY'il'lt a l'IIessa~e tellil'l~ the
lASe.. . how he did il'l the ~l'IIe

private void finishGame ()


System.out.println(\\All Dot Corns are dead! Your stock is now worthless .");
f
if (numOfGuess es <= 1 8) (
System.out.println(\\It only took you \\ + numOfGues s e s + \\ guesses.") ;
System.out.println(\\ You got out before your options sank.");
else (
System . out.println(\\Took you long enough. \\+ numOfGuesses + \\ guesses.");
System .out.println( \\Fish are dancing with your options");
)
I I close met hod

public static void main


DotComBust game = new
game.setUpGame();
game.startPlaying();
II clo s e me t hod

yo u are here • 149


the DotCom code

The final version of the


PotCOtlt class
import java .util.*;

DotCOM'5 iWlStaWlte "iav-ia'oles:


public class DotCom
_ ah Arra'fl-ist cJ tell loeatiOWlS
private ArrayList<String> locationcells;'S
_ the DotCOM'5 ~Me
private String name; )

public void setLocationCells(ArrayList<String> loc) {


locationCells = loc;

public vo id setName (String n) ~ 'lOll-V- basit seHe\" Method


name = n;

pUblic String checkYourself(String userlnput) {


Str ing result = ~miss";

int index = locationCells .indexOf(userlnput);


if (index >= 0) (
l ocationCells.remove(index);~
1___ (,(Sih~
L._
(lrrayl-ist'
5 \"eMo"ie
() il
Me~od 1R
L_.J
aeIe1;C:
L_ L
an en,,\,,'!,

if (locationCells. isEmpty ()) { (-----~'-.. (,(sin~ the iS~Mft'l( ) Method to see i~ all
re sult = ~kill";
cJ the loeatoWlS ha"ie been ~~sed
System.out.println(~Ouch! You sunk ~ + name + ~ ( ~);

else {
result = ~hit ";
<,
Tell the lASe\" wnen h Lr»
' a Vo"U., has bten 51Ahk.
} II close i f OM
II cl ose i f
return result;
O_i....... ( . ,
1\1:1;- n, -...5S ..... 'h'i' ,
..... '" or kill'.
} I I close method
I I close class

150 chapter 6
get to know the Java API

Super Powerful 'oolea" [xpressio"s


So far, when we've used boolean expressions for our loopsor Not equals (!= and ! )
i f tests, they'vebeen pretty simple. We will be using more
powerful boolean expressions in some of the Ready-Bake code Let's say that you have a logiclike,"ofthe ten available
you're aboutto see, andeven though we knowyou wouldn't camera models, a certain thing is true forall butone,"
peek, wethought this would bea good time to discuss howto if (model 1= 2000) {
energize yourexpressions. II do non-model 2000 stuff
}
'And' and 'Or' Operators (&&, II )
or for comparing objects likestrings...
Let's say you'rewriting a chooseCamera( ) method, with lotsof rules
aboutwhich camera to select. Maybe you can choose cameras if (lbrand.equals("X"» {
ranging from $50 to $1000, but in some cases youwantto limit the II do non-brand X stuff
price range more precisely. You wantto say something like: }

'If the price range isbetween $300 and $400 then choose x: Short Circuit Operators (&&, II )
The operators we've looked at sofar, && and II, are
if (price >= 300 && price < 400) { known as shortcircuit operators. Inthe case of &&,
the expression will betrue onlyif both sides ofthe &&
camera =
"X"i
are true. So jf theJVM sees that the left side of a &&
} expression isfalse, it stops right there! Doesn't even
botherto lookat the right side.
Let's say that of the ten camera brands available,you have some Similarly, with II, the expression will betrue if either side is
logicthat applies to onlya few of the list: true, soif the JVM sees that the left side istrue,it declares
the entire statement to betrue and doesn't botherto
check the right side.
if (brand.equals("A") II brand.equals("B") ) {
Why isthis great? Let's say that youhave a reference
II do stuff for only brand A or brand B variable and you're not sure whether it's been assigned
} to anobject. If youtry to call a method using this null
reference variable (l.e, no objecthas been assigned), you'll
get a NullPointerException. So, try this:
Boolean expressions can get really big and complicated:

if «zoomType.equals("optical") && if (refVar 1= null &&


(zoomDegree >= 3 && zoomDegree <= 8» II refVar.isvalidType() ) {
(zoomType.equals("digital") && II do 'got a valid type' stuff
}
(zoomDegree >= 5 && zoomDegree <= 12») {
II do appropriate zoom stuff Non Short Circuit Operators (&, I)
} When used in boolean expressions, the & and Ioperators
If youwantto get really technical, you might wonder aboutthe act liketheir && and II counterparts, except that
precedence of these operators. Instead of becoming anexpert they force theJVM to always check both sides of the
in the arcane world of precedence, we recommend that you use expression. Typically, & and Iare used in another context,
for manipulating bits.
parentheses to make yourcode clear.

you are here ~ 151


Ready-bake: GameHelper

Th is is the helper class for the game. Besides the. user input method
(that prompts the user and reads input from the commend -line), the
helper's Big Service is to create the cell locat ions for the DotComs.
If we were you, we'd just back away slowly from this code, except
to type it in and compile it. We tried to keep it fairly small to you
wouldn't hove to type so much, but that means it isn't the most
import java.io.*i readable code. And remember, you won', be able to compile the
import java.util.·: DotComBust game class until you have this class.

pUblic class GamaBelper

private static final Str ing alphabet "abcdefg";


NoU: F~ elttta ,,,e,M, '101# ",\~h-l:
private int gridLength = 7: b-)' '1<rI-'o...... c:"ti,,~' tht
private int gridSize = 49; S)'lu....Ollt.fri..HI,,)'s i.. t.he
pr ivate int () grid = new int[gridSize); fl.lteDoiCo...( ) ... dhod, j\l.1t.
private int comCount = 0; to w<iUh it work! These ?,"i"t
u
1~te-e"u will Id Y0l# "',heai
public String ge tUserlnput(String prompt)
String inpu tLine = null; by ~ivi,,~ 'f..... tile lold·tioll o-f the
System.out.print(prompt +" ")i Dot.ColN, bl#t it. will hell' 'fOIl ust it..
try (
BufferedReader is = new BufferedReader(
new InputStreamReader(System.in»);
inputLine = is.readLine();
if (inpu tLine.length() == 0) return null;
catch (IOExcept ion e) (
System.out.println("IOException : " + eli
I
return inputLine .toLowerCase();

public ArrayList<Stxing> placeDotCom(int comSi ze) (


ArrayList<String> alphaCells = new ArrayList<String>();
String [1 a1phacoords = new String (comSizel: II holds 'f6' type coords
String temp = null; II temporary String for concat
int II coords = new intlcomSize); II current candidate coords
int attempts = 0; II current attempts counter
boolean success = false; II flag = found a good location?
int location = 0; II current starting location
comCount++; II nth dot com to place
int incr = 1; II set horizontal increment
i f «cornCount % 2) == 1) ( II if odd dot com (place vertically)
i nc x = gridLength; II set vertical increment

while ( ! s uc c e s s & attempts++ < 200 ) ( II main search loop (32)


location = (int) (Math.random() .. gridSize); II get random starting point
I/S y s t em. o uc . p ri n t ( " t ry" + locat ion);
i n t x == Oi II nth position in dotcom to place
success = true; II assume success
while (success && x < comSizel II look for adjacent unused spots
i f (grid(locacion) =-= 0) { II if not already used

152 chapter 6
get to know the J ava API

tallteHelper class code cot1tlt1ued...

c o ords[x++] = location; II s a v e l ocati on


l o cation += incr; II tr y 'nex t' adjacent
if (location >= gridSize){ II out of b ounds - 'bottom'
success = false; II fa ilu re
}
if (x> O && (location % g ridLength 0» { II o u t o f b ounds - ri g ht edg e
success = false; II failure
}
else ( II f ound already used l o c a t i on
I I System . o ut .pr i nt ( " used" + l oc ati on);
succes s = f al se; II failure

I I e nd while

int x = 0; II turn l ocation into alpha coo r d s


int r ow = 0;
int c olumn = 0;
II Sy s tem . o u t . p ri n tl n ( "\ n " ) ;
whil e (x < c omSiz e) {
grid[coords[x]] = 1; II mark master g r id p t s . a s 'u s ed'
r ow = (int) (c o o rds[x] I gridLength); II get row value
c olumn = coords[x] % gridLength; I I g et numeric co l umn va lue
t emp = String.va lueOf(alphabet.charAt(column); I I c o nv e r t to alpha

alphaCell s.add(temp.concat(Integer.toString(row»); ttnat


x++; n' is tnC stateVOlC" t nC
II System .ou t . p r i n t ( n co or d " +x +" = n + a l p h aCe ll s . get(x - l) ); <;-,, 1 ~s olJ.c"14t.H'i'f/nCVOC
te s'f . \-'atCO.
1)otCOVOI IS ""
I I Sys t em . o u t .pr i ntln r " \ n " ) ;

r e t u r n alphaCells;

you are here ~ 153


API packages

Usittg the Library (the Java API)


You made it all the way through the DotComBust game,
thanks to the help of ArrayList. And now, as promised,
it's time to learn how to fool around in theJava library.

In the .Java API. classes


are grouped into packages.

To use a class in the API. you


have to know which package
the class Is in.
Every class in theJava library belongs to a package .
The package has a name, like javax.swlng (a
package that holds some of the Swing CUI classes
you'll learn about soon). ArrayList is in the package
called java.utll, which surprise surprise, holds a
pile of utility classes. You'll learn a lot more about
packages in chapter 16, including how to put your
own classes into your own packages. For now though,
we're just looking to usesome of the classes that come
with Java.
Using a class from the API, in your own code, is
simple. You just treat the class as though you wrote
it yourself... as though you compiled it, and there it
sits. waiting for you to use it. With one big difference:
somewhere in your code you have to indicate the full
name of the library class you want to use, and that
means package name + class name.
Even if you didn't know it, you've already been using
cJassesfrom a ptu:kage. System (System.out.println),
String, and Math (Math.random 0), all belong to the
java.lang package.

154 chapter 6
get to know the Java API

You have to know the full name*


of the class you want to use in
- :tberet&rH?
Dumo ~uest19ns

your code. Q.: Why does there have to


be a full name? Is that the only
purpose of a package?
ArrayList is not the full name of ArrayList, just as 'Kathy'
isn't a full name (unless it's like Madonna or Cher, but we
won't go there). The full name of ArrayList is actually: A: Packagesare import ant
for three main reasons. First, they
java.util.ArrayList help the overall organization of a
~ ~ project or library. Rather than just
/ '\ having one horrendously large
patka~e l'lc11l1e e.\ass ~"'c pile of classes, they're all grouped
into packages for specific kinds
of functionality (like GUI,or data
structures, or database stuff, etc.)
You have to tell Java which ArrayList you Second, packages give you a name-
want to use. You have two options: scoping, to help prevent collisions
if you and 12 other programmers
in your company all decide to
make a class with the same name.
IMPORT If you have a class named Set and
Put an import statement at the top of your source code file: someone else (including the Java
import java.util.ArrayList; API) has a class named Set,you
need some way to tell the JVM
public class MyClass { ... } which Set class you're trying to use.

OR Third, packages provide a level of


security, because you can restrict
the code you write so that only

o
other classesin the same package
can accessit. You'll learn all about
TYPE that in chapter 16.
Type the full name everywhere in your code. Each time
you use it. Anywhere you use it. n .
~: OK, back to the name
. .. collision thing. How does a full
When you declare and/or instantlate It: name really help? What's to
java.util.ArrayList<Doq> list = new java .util.ArrayList<Dog>0 ; prevent two people from giving a
class the same package name?

When you use it as an argument type:


A:Java has a naming convention
public void go(java.util .Arraytist<Dog> list) { } that usually prevents this from
happening, as long as developers
adhere to it. We'll get into that in
When you use it as a return type: more detail in chapter 16.

public java.util.Arraytist<Doq> fooO { .. . }

"Unless the class is in the java.lang package.

you are here. 155


when arrays aren't enough

.-----_ BUUD POINIS-


• ArrayList isa class inthe Java API.
Where'd that 'x' come from?
• To put something into an ArrayUst. use addD,
(or, what does it mean when
a package starts with Javax?) • To remove something from an ArrayUst use
r&moveD·
In the first and second versions of Java (1.02
and 1.1), all classes that shIpped with Java (In • To find outwhere something is (and If it is) in an
other words, the standard library)were In packages ArrayUst, use indexOfO.
that began wlthJava.There was alwaysjllva.lang, of course
- the one you don't have to import. And th ere was jlllla.netl • To find outif an ArrayUst is empty, use
jOl/a,/o,java.util (although there was no such thing as ArrayList IsEmpfyQ.
way back then), and a few others, Including the ja va.aWl
package that held GUI-related classes. • To get the size (number ofelements) in an
ArrayUst. use the sizeD method.
Looming on the horizon, though, were other packages not
Included in the standard library.These classes were known as • To get !he length (number of elements) ina
extensions, and came in two maInflavors: standard, and not regular old array. remember, you use the length
standard. Standard extensions were those that Sun considered variable.
official,as opposed to experimental, early access, or beta
packages that might or mIght not ever see the light of day. • An Arraylist res1z&s dynamically to what-
Standard extensIons, by convention, all began with an 'x' ever size is needed. It grows when objects
appended to the regular java package starter. The mother of all are added, and it shrinks when objects are
standard extensions was the Swing library. It Included several removed.
packages, all of which began with jallax.swlng.
• You declare the type of the array using a type
But standard extensions can get promoted to first-class,shlps-
parameter, which is a type name in angle
wIth-Java,standard-out-of-the-box library packages. And that's
what happened to Swing,beginning with version 1.2 (which brackets. Example: ArrayList<8utton> means
eventually became the first version dubbed 'Java 2') . the ArrayUst will be able to hold only objects of
type Button (or subclasses ofButton asyou'll
MCool: everyone thought (Including us).~Now everyone who has
Java will have the SwIng classes, and we won't have to figure learn in !he next couple ofchapters).
out how to get those classes Installed with our end-users: • Although an ArrayUst holds objects and not
Trouble was lurking beneath the surface, however, because primitives, the compiler will automatically "wrap.
when packages get promoted, well of COURSE they have to (and ·unwrap· when you take It out) a primI-
start wlthjalla, notjavax. Everyone KNOWS that packages In tive into an Object, and place that object Inthe
the standard library don't have that "lC: and that only extensions ArrayUst Instead of the primitive. (More on this
have the "x~ So,Just (and we mean Just) befo re version 1.2
feature later in the book..)
went final, Sun changed the package names and deleted the
"x· (among other changes). Bookswere printed and In stores • Classes are grouped into packages.
featurIng SWing code with the new names. Naming conventIons
were intact. All was right with the Java world. • Aclass has a full name, which isa combina-
Except the 20,000 or so screaming developers who realized tion of the package name and the class name.
that with that simple name change came dlsasterl All of their Class ArrayList is really java.utiIArrayUst.
Swing-using code had to be changedl The horrorl ThInk of all
• To use a class in a package other than java.
those Import statements that started wlthjavCDf...
lang, you must tell Java the full name of the
And In the flnal hour, desperate, as their hopes grew thin, the class.
developers convInced Sun to "screw the convention, save our
code" The rest Is history. So when you see a package In the • You use either an Import statement atthe top of
library that beglns with Javax, you know It started life as an your source code, oryou can type the full name
extension, and then got a promotion. every place you use the class in your code.

156 chapter 6
get to know the Java API

Q.: D06S import make my


class bigger? Does It actually
compile the imported class or
package Into my code7
N/ale~ if. oStit.1e
A: Perhaps you're a C pro-
grammer? An import is not the
Roses arered
apples areri;e.
same as an include. So the ifyou don't im;on
answer is no and no. Repeat after You 'lljust have t
c otYpe
rne.ran import statement saves
you from typing:That's really It. Youmust tell Java
you use, unle the full name of ev
You don 't have to worry about packag A s.s that class is in til ' ery class
your code becom ing bloated, or e. n lmport Sf e Java.lang
slower, from too many Imports. or packageat the to f atement for the class
An i mport is simply the way you easyway. OtherWise~~ ~our sourceCode is the
give Java the full name of a class. name of the class, e:e~h ave to type the fUll
. ere you use it!

Q: OK, how come I never had


to import the String class? Or
One more time, in the unlikely
System?
event that you don't already
have this down:
A: Remember, you get the
java.lang package sort of·pre-
Imported" for free. Because
the classes In [ava.lanq are so
fundamental, you don't have to
use the full name.There Is only
one java.lang.Strlng class,and one
[ava.tanq.System class,and Java
darn well knows where to find
them.

Q: Do I have to put my own


classes Into packages? How do I
do that? Can I do that?

A..: In the real world (which


you should try to avoid), yes, you
wl/l want to put your classes Into
packages. We'll get into that in
detail In chapter 16. For now, we
won 't put our code examples In a
package.

you a re he re . 157
getting to know the API

"Good to know there's an ArrayList in


the java.util package. But by myself, how
would 1 havefigured that out?"
- Julia, 31, hand model

How to play with the API


Two things you want to know:

o What classes are In the library?

e Once you find a class, how do


you know what It can do?

o Browse a Book

e Use the HTML API docs

. . . .1_..
I " ... 0 .

_USJl
&G!.~
e..
... . . ..
o..n-wo....zPIal. ... 51: l.O1
+ ~ ~t/Jlot&-Il.A (OMIIl 'ftl .',O/ _IJ ~1

~, ..-. .........
E'IlIiIIlIPocuoo C., UU JJlN ~ nIn tlAlD

Jav,,'" 2 P1IItlormStaodard Edlllon 51)


O ~·~Q.· '-

J"""'~
~U Hi
-
...... -¥~,., ;,,: i

-- . . - API SpedtblloD

- 1- IoAClM_ 'Nt - . . . Is'" API _ _ (00 "" b ... , Pbtl..... S<a\.ooIrod•.., 1,0

Ila<dIIJIoIl

JAVA --
Nnlr!cI".!ffIU
J8va 2 P18t1orm hcbgcs
N"1!rW1">"9'T"1 P'Jl.wtdca IIlc d ...~ 1lC'CD""' ~l nc. . . ~ .....
ANeJIChQ"""", C9ntr.i IIu.I.oPI<l c~u.~tan .,COl['IIamCC "lib b ~
","""l.

INANUTSHELL
6CID:!lraCr=
/IW..nJ
_ .et. . .
CmWM aDat Iht daun lar ClQlilt DID~ arid b
...-. JnliIIct1lOI 1m>;n.

... .
f«coInf ___•
......u.ab:
iIIlIIICUI
f'roo'Iotic" ~ ~ d:lUl:f for ttll:).ran.' .im t:w:r-tcII ~
~.
~ lnll>I",
Ii CX:sJdop Quick RI!jlf'l:llce

O'REillY'

158 ch ap ter 6
get to know the Java API

IJAVA
''?''!!!@I'
}twa ,utU,ClUnmcy

R,/JUJUId Bj~ IN.ltU1lleeImalFaT1lat#lCun8lctO.IM,te:l1-~malf~o.mncyO.


J-.l8ItN~eum:lley(I . O:JtnlllCY'~

Date

This d:I5:l represents dates and limes 2nd leu you ...·o rk with them in ~ ~em-ind~pen­
den! way , You C:1n create a D8l& by specityina the number of m1Diseconds (rom the
epoch (audf\is/11 GMT. J:>nw<y 181. 1970) or We year. month, date, and, oplional1)', th e
hour. m1nUle, llrld second. Yo,.. are 5p<'cilied as the number of fC"'lS since 1900, If you
call the Dale construClor wilh no "'BWDCfIlS. the OIIe ts ini riJn:z...d 10 the current time
J11d dJ'e. Tht Insunce runhods of the class .110"" you 10 get :lOd se t the \':l(iOll~ UJI"
and lim e fields, (0 compare mid "nd umes, and '0 convert da tes to 2nd from SIring
n:prcscnulio"" 11:> of J'V> 1.1, = ) ' or the dale metho<b bave been deprecated in
fa\ 'Or of th e me thods of the calendar cl.....

PiUc dass Oila iIIpltments ctonUblt. Coml*;tblt; Sedllriille I


II Mil; ~strucl:lrs
IUbllc Dm():
~leD~r. ct.lle):
, iiiIl1t o.tt(SlJireI);
, lIUbIlcD m..lIllye.v, lnlmonlft, IIIlct.l f!):
, PliIIlclllWCiI1ltw,lnlllll:'l ,liIl dlle. lnlhn,inl t*l;
, pUllIlc DItIl(lr>I ye¥, lnl /llMlII, lnlttaDl. lnllirs. Int mil, tnt sec):
II Piijiiifj~S{l(1rIer1t4df (tj ~ -J
~It Itr( e-t1llMl):
IdiIlt will MtTIIM(Ion&1tIIe):
7/ JljibJ; IiiSfiiiij MilIiOili
public boomn aftal\lmJJ1lLIl8:t . , ):
. II\iIllcbooIelI\hhlr-aM.UliLDiIl'-);
1.1publicInt c-..N1To11m.uDI.DJI'~Irllat,}:
ll lIiI1JDiif~~~
1.1putIIlc In! _PANTo(ObjtCl 0):
II JIlIbIi: j,jeth6ill ~0l;Id
1.1 pulIIlc 0lijtcI doN( I:
puliIic b09Iear! .q.II(OijIlc:l «II:
IdiI lcIIIl••1Ie.c1e():
PliIII~Sllitl(toStrlDiO; .
II ~ WPubic lIe~
, llWIlC irt 1I!tI!at1():
, ~ic Int,.0.,0:
, puliIic IIIptHoan/):
, puliIlc IntptMlllCIttI():
, ~~lnt ~d();
, pWlc Int,.S aMI(J:
, pUblic rt 1itI'IMIo..otfiit(1:
'~ltlnt"""l():
• liibIlclll~clq,.lM(S1(IrcJ);
, pJlllc'/Old utDat-r1fll dlIIlI):
, lIulill~ iOId iittIilIrI('llllllOurl);
, lQlillcvoIdMtMl~nlllllilwl8s):
, ~lc'lOliI ~ntllDllII);

you are here) 159


using the Java API documentation

e Use the HTML API docs


Java comes with a fabulous set of online docs The reference book, for example, tells you
called , strangely, the Java API. They're part of what the methods take, as arguments, and what
a larger set called the Java 5 Standard Edition they return. Look at ArrayList, for example.
Documentation (which, depending on what In the reference book. you'll find the method
day of the week you look, Sun may be refer- index Of'(}, that we used in the DotCom class,
ring to as "Java 2 Standard Edition 5.0"), and But if all you knew is that there is a method
you have to download the docs separately; called indexOf() that takes an object and re-
they don't come shrink-wrapped with the Java turns the index (an int) of that object, you still
5 download. If you have a high-speed internet need to know one crucial thing: what happens
connection, or tons of patience, you can also if the object is not in the ArrayList? Looking
browse them at java.sun.com, Trust us. you at the method signature alone won't tell you
probably want these on your hard drive. how that works, But the API docs will (most of
the time, anyway). The API docs tell you that
The API docs are the best reference for get- the indexOff) method returns a -1 if the object
ting more details about a class and its methods. parameter is not in the ArrayList. That's how
Let's say you were browsing through the refer- we knew we could use it both as a way to check
ence book and found a class called Calendar, if an object is even in the ArrayList, and to get
in java.util , The book tells you a little about it, its index at the same time , if the object was
enough to know that this is indeed what you there. But without the API docs, we might have
want to use, but you still need to know more thought that the indexOf() method would
about the methods . blow up if the object wasn't in the ArrayList.

boolNA .tdlM1.1(rp))eCt(PDcr .n...o.d.. c:' e)


Appilrod' >IJ of lbo C~1S In the <pcci1kd Col lccrlon 10 do: <lid 0( 1IIlJ!lSI. In
lIlc Olderdill. dley lite teI1lmCd by lIlc spcd{1ed CollccOOt>', ItcralQT.
tloOoQl. u .I44I.llf hot. .1..1:I4 •• 1 Co)) lOt iQa<) Qt._tlds P (III
1Jumj all r>ilIlc d<ma!1J in !be <pcd/ltd Collcctloo!n1O Ihi> hst, stuIing 4I1llC
<nccif1n1 nndrinn

160 chapter 6
get to know the Java API

Code Magnets a.remove(2); pri.ntAL (a) ;


Can you reconstruct the code snippets to make a
working Java program that produces the output
listed below7 NOTE: To do this exercise, you need a .add(O I " zero").
a _.....-oz-I one NEW piece of info-If you look in the API for
a.. add (1 " ,
ArrayList,you'll find a secondadd method that takes , one"),.
two arguments:
.';;;~.jiI:
"- lIdd(lnt Index. Object 0) public static void printAL (ArrayList<String> al) (
It lets you specify to the
Arrayl.lst where to put the object you're adding . if (a
. Contains ("brO"
&.add ( " 2 . 2 " ) ; » (
)

public static void main (String[]

System.out.print(eleme.nt +" ") ;


)
Syst.em.out.println(" ");

(a. contains ("three"»


a.add("fourn)i

public class ArrayListMagnet

if (a .indaxOf("four") !=
a.add(4, "4.2");

import java. ut i l.*;

printAL (a) ;

ArrayList<String> a = new ArrayL

for (String e1............-


~t:

3 "three") i
a.a dd( J

printAL(a) ;

you are here . 161


puzzle: crossword

JavaOr~ss t. O
How does this crossword puzzle help you learn
Java 7 Well,all of the words are Java related
(exceptone red herring).
HInt: When In doubt, remember ArrayUst.

Aaoss
1. I can't behave
6. Or, In the courtroom
7. Where It's at baby
9. A fork'sorigin Down
12. Grow an ArrayUst 2. Wherethe Java action Is.
13. Wholly massive 3. Addressable unit
14. Value copy 4. 2nd smallest
16. Not an object 5. Fractional default
17. An arrayon steroids 8. Ubrary'sgrandest
19, Extent 10. Must be low density
21. 19'scounterpart 11. He's In there somewhere
22, Spanish geek snacks (Note: This has 15. As if
nothing to do with Java)
16. dearth method
23. For lazyfingers
18. Whatshopping and arrays haveIn common
24. Wherepackages roam
20, Ubrary acronym
21. What goesaround

More Hints:
--1l6UI~IlWS.ill-l ·81 sJ~ladde 4SIUIldS' 1!hIl( l/1oqe ION 'U
lSn,(IlJJv l(U!ll..L '9 1 IUillXds•.(IlJJV' IZ
ilhll!W!!d '01 ~ 'to' ~w!Jd UOWWO) '91
lSn.<eJJy l(U!ll..L 'E ISn'<WY'lUI'lJ. 'L
lillqllP!JJahO S,lllllM ' Z 5a!liljJRh 8 ' I
uMO(J stoJ:lV

162 chapter 6
get to know the Java API

import java. uti!. * i I


public class ArrayListMagnet
( II
I public static void main (Strinq[] arqs) (I
I ArrayList<Strinq> a = new ArrayList<String>()i l
a.add(O,HzerOn)i
a.add(l,"one")i

a.add(2,"twO")i

a.add(3,"three")i
printAL (a) i

if (a.contains ("three"» (
a.add("four")j
)

a. remove (2) i Ie
printAL (a) i . .
..
if (a. indexO£ ("four") != 4) (
a .add(4, "'4.2")i
}

printAL (a) ; ..

if (a.contains("two"» {
a.add("2.2")i
}
printAL (a) ; ..

[r II'

I public static void printAL(ArrayList<String> a1) {r


for (Strinq element : al) (

System. out. print (element + " ") ;


)

ofll- System.out.println(" \\} ;

you are here ~ 163


puzzJe answers

JavaOrctSS
answers

~ your re::,~e you. OWN set of cluesl Lookat each word , and "y to
write your own clues. Try making them easier,or harder, or
Aaoss more technical than the ones we have.

I.
6. Down
7. 2
9. 3.
12. 4.
13. 5.
14. 8.
16. 10.
17. II.
19. 15.
21. 16.
22 18.
23. 20.
24. 21.

164 chapter 6
7 inheritance and polymorphism

We were underpaid,

Better Living in overworked coders 'fill we


tried the Polymorphism Plan. But

Objectville thanks to the Plan, our future is


bright. Yours can be tool

Plan your programs with the future in mind. If there were a way to write
Java code such that you could take more vacations, how much would It be worth to you? What
if you could write code that someone else could extend, easily? And if you could write code
that was flexible, for those pesky last-minute spec changes, would that be something you're
interested In?Then this is your lucky day. For Just three easy payments of 60 minutes time , you
can have all this. When you get on the Polymorphism Plan, you'll learn the 5 steps to better class
design, the 3 tricks to polymorphism, the 8 ways to make flexible code, and if you act now-a
bonus lesson on the 4 tips for exploiting inheritance. Don't delay, an offer this good will give
you the design freedom and programming flexlbll lty you deserve. It's quick. it's easy, and it's

available now. Start today, and we'll throw in an extra level of abstractionl

this is a new ch ap ter 16i


the power of inheritance

Chair Wars (evisited...


Remember way back in chapter 2, when Larry (procedural guy)
and Brad (00 guy) were vyingfor the Aeron chair? Let's look at
(J few pieces of that story to review the basics of~.

LARRY: You've got duplicated codel The rotate procedure


is in all four Shape things. It's a stupid design. You have [0
maintain four different rotate "methods". How can that
ever be good?
BRAD: Oh, I guess you didn't see the final design. Let me
show you how 00 inheritance works, Larry.

Square Amoeba
o
Ilooked at what all four
rotateQ
playSoundO
rotateO
playSoundQ