Thin kin g in J ava,
2
n d
Edition,
Release 11
To be published by Prentice-H all m id-J une, 20 0 0
Bruce Eckel, Presiden t,
Min dView, In c.
Plan et PDF brin gs you the Portable Docum en t
Form at (PDF) version of Thin kin g in J ava (2n d
Edition ). Plan et PDF is the prem ier PDF-related
site on the web. There is n ews, software, white
papers, in terviews, product reviews, Web links,
code sam ples, a forum , an d regular articles by
m any of the m ost prom in ent and respected PDF
experts in the world. Visit our sites for m ore detail:
Thinking
in
J ava
Secon d Edition
Bruce Eckel
Com m ent s fr om r eader s:
M uch better than any other J ava book I’ve seen. Make that “by an order of
m agnitude”... very com plete, with excellent right-to-the-point exam ples an d in telligen t, n ot dum bed-down , explan ation s ... In con trast to m an y other J ava books I foun d it to be un usually m ature, con sisten t,
intellectually honest, well-written and precise. IMH O, an ideal book for studying J ava. An a to ly Vo ro be y, Te ch n io n U n ive rs ity, H a ifa ,
Is ra e l
One of the absolutely best program m ing tutorials I’ve seen for any language. J o a kim Zie gle r, FIX s ys o p
Than k you for your won derful, won derful book on J ava. D r. Ga vin
P illa y, Re gis tra r, Kin g Ed w a rd VIII H o s p ita l, S o u th Africa
Thank you again for your awesom e book. I was really floundering (being a n on -C program m er), but your book has brought m e up to speed as fast as I could read it. It’s really cool to be able to understand the underlying principles and concepts from the start, rather than having to try to build that conceptual m odel through trial and error. H opefully I will be able to attend your sem inar in the not-too-distant future. Ra n d a ll R. H a w le y,
Au to m a tio n Te c h n ic ia n , Eli Lilly & Co .
The best com puter book writing I have seen. To m H o lla n d
This is one of the best books I’ve read about a program m ing language… The best book ever written on J ava. Ra vin d ra P a i, Ora cle
Co rp o ra tio n , S U N OS p ro d u ct lin e
book is great! S te ve W ilkin s o n , S e n io r S ta ff S p e cia lis t, MCI
Te le co m m u n ica tio n s
Great book. Best book on J ava I have seen so far. J e ff S in cla ir,
S o ftw a re En gin e e r, Ke s tra l Co m p u tin g
Than k you for Thinking in Jav a. It’s tim e som eon e wen t beyon d m ere language description to a thoughtful, penetrating analytic tutorial that doesn’t kowtow to The Manufacturers. I’ve read alm ost all the others— only yours and Patrick Winston’s have found a place in m y heart. I’m already recom m ending it to custom ers. Thanks again. Rich a rd B ro o ks ,
J a va Co n s u lta n t, S u n P ro fe s s io n a l S e rvice s , D a lla s
Other books cover the WH AT of J ava (describing the syntax and the libraries) or the H OW of J ava (practical program m ing exam ples).
Thinking in Jav a is the only book I know that explains the WH Y of J ava;
why it was designed the way it was, why it works the way it does, why it som etim es doesn’t work, why it’s better than C++, why it’s not. Although it also does a good job of teaching the what and how of the language,
Thinking in Jav a is defin itely the thin kin g person’s choice in a J ava book.
Ro be rt S . S te p h e n s o n
Thanks for writing a great book. The m ore I read it the better I like it. My students like it, too. Ch u ck Ive rs o n
I just wan t to com m en d you for your work on Thinking in Jav a. It is people like you that dignify the future of the Internet and I just want to than k you for your effort. It is very m uch appreciated. P a trick B a rre ll,
N e tw o rk Office r Ma m co , QAF Mfg. In c.
Most of the J ava books out there are fine for a start, and m ost just have begin n in g stuff an d a lot of the sam e exam ples. Yours is by far the best advanced thinking book I’ve seen. Please publish it soon! ... I also bought
Thinking in C++ just because I was so im pressed with Thinking in Jav a.
Ge o rge La fra m bo is e , Ligh tW o rx Te ch n o lo gy Co n s u ltin g, In c.
I wrote to you earlier about m y favorable im pressions regarding your
Thinking in C++ (a book that stands prom inently on m y shelf here at
work). And today I’ve been able to delve into J ava with your e-book in m y virtual hand, and I m ust say (in m y best Chevy Chase from M odern
like a dry textbook. You cover the m ost im portant yet the least covered concepts of J ava developm ent: the whys. S e a n B ra d y
Your exam ples are clear and easy to understand. You took care of m any im portant details of J ava that can’t be found easily in the weak J ava docum entation. And you don’t waste the reader’s tim e with the basic facts a program m er already knows. Ka i En ge rt, In n o va tive S o ftw a re ,
Ge rm a n y
I’m a great fan of your Thinking in C++ and have recom m ended it to associates. As I go through the electronic version of your J ava book, I’m fin din g that you’ve retain ed the sam e high level of writin g. Than k you!
P e te r R. N e u w a ld
VERY well-written J ava book...I think you’ve done a GREAT job on it. As the leader of a Chicago-area J ava special interest group, I’ve favorably m entioned your book and Web site several tim es at our recent m eetings. I would like to use Thinking in Jav a as the basis for a part of each m onthly SIG m eeting, in which we review and discuss each chapter in succession.
Ma rk Erte s
I really appreciate your work an d your book is good. I recom m en d it here to our users and Ph.D. students. H u gu e s Le ro y / / Iris a -In ria Re n n e s
Fra n ce , H e a d o f S cie n tific Co m p u tin g a n d In d u s tria l Tra n fe rt
OK, I’ve only read about 40 pages of Thinking in Jav a, but I’ve already found it to be the m ost clearly written and presented program m ing book I’ve com e across...and I’m a writer, m yself, so I am probably a little critical. I have Thinking in C++ on order and can’t wait to crack it—I’m fairly new to program m ing and am hitting learning curves head-on everywhere. So this is just a quick note to say thanks for your excellent work. I had begun to burn a little low on enthusiasm from slogging
through the m ucky, m urky prose of m ost com puter books—even ones that cam e with glowing recom m endations. I feel a whole lot better now.
Gle n n B e c ke r, Ed u ca tio n a l Th e a tre As s o c ia tio n
Than k you for m akin g your won derful book available. I have foun d it im m ensely useful in finally understanding what I experienced as
con fusin g in J ava an d C++. Readin g your book has been very satisfyin g.
I m ust congratulate you on an excellent book. I decided to have a look at
Thinking in Jav a based on m y experience with Thinking in C++, and I
was not disappointed. J a co va n d e r Me rw e , S o ftw a re S p e cia lis t,
D a ta Fu s io n S ys te m s Ltd , S te lle n bo s ch , S o u th Africa
This has to be one of the best J ava books I’ve seen. E.F. P ritch a rd ,
S e n io r S o ftw a re En gin e e r, Ca m brid ge An im a tio n S ys te m s Ltd ., U n ite d Kin gd o m
Your book m akes all the other J ava books I’ve read or flipped through seem doubly useless and insulting. B re tt g P o rte r, S e n io r
P ro gra m m e r, Art & Lo gic
I have been reading your book for a week or two and com pared to the books I have read earlier on J ava, your book seem s to have given m e a great start. I have recom m ended this book to a lot of m y friends and they have rated it excellent. Please accept m y congratulations for com ing out with an excellent book. Ra m a Kris h n a B h u p a th i, S o ftw a re
En gin e e r, TCS I Co rp o ra tio n , S a n J o s e
J ust wanted to say what a “brilliant” piece of work your book is. I’ve been using it as a m ajor reference for in-house J ava work. I find that the table of contents is just right for quickly locating the section that is required. It’s also nice to see a book that is not just a rehash of the API nor treats the program m er like a dum m y. Gra n t S a ye r, J a va Co m p o n e n ts
Gro u p Le a d e r, Ce e d a ta S ys te m s P ty Ltd , Au s tra lia
Wow! A readable, in-depth J ava book. There are a lot of poor (and adm ittedly a couple of good) J ava books out there, but from what I’ve seen yours is definitely one of the best. J o h n Ro o t, W e b D e ve lo p e r,
D e p a rtm e n t o f S o cia l S e cu rity, Lo n d o n
I’ve *just* started Thinking in Jav a. I expect it to be very good because I really liked Thinking in C++ (which I read as an experienced C++ program m er, trying to stay ahead of the curve). I’m som ewhat less experienced in J ava, but expect to be very satisfied. You are a wonderful author. Ke vin K. Le w is , Te ch n o lo gis t, Obje ctS p a ce , In c.
that your book isn’t a com m ercial brochure for J ava. It also shows the bad sides of J ava. YOU have done a great job here. Fre d e rik Fix, B e lgiu m I have been hooked to your books all the tim e. A couple of years ago, when I wanted to start with C++, it was C++ Inside & Out which took m e
around the fascinating world of C++. It helped m e in getting better opportun ities in life. Now, in pursuit of m ore kn owledge an d when I wanted to learn J ava, I bum ped into Thinking in Jav a—no doubts in m y m ind as to whether I need som e other book. J ust fantastic. It is m ore like rediscovering m yself as I get along with the book. It is just a m onth since I started with J ava, and heartfelt thanks to you, I am understanding it better now. An a n d Ku m a r S ., S o ftw a re En gin e e r,
Co m p u te rvis io n , In d ia
Your book stands out as an excellent general introduction. P e te r
Ro bin s o n , U n ive rs ity o f Ca m brid ge Co m p u te r La bo ra to ry
It’s by far the best m aterial I have com e across to help m e learn J ava and I just wan t you to kn ow how lucky I feel to have foun d it. TH ANKS! Ch u ck
P e te rs o n , P ro d u ct Le a d e r, In te rn e t P ro d u ct Lin e , IVIS In te rn a tio n a l
The book is great. It’s the third book on J ava I’ve started and I’m about two-thirds of the way through it now. I plan to finish this one. I found out about it because it is used in som e internal classes at Lucent Technologies and a friend told m e the book was on the Net. Good work. J e rry N o w lin ,
MTS , Lu ce n t Te ch n o lo gie s
Of the six or so J ava books I’ve accum ulated to date, your Thinking in
Jav a is by far the best an d clearest. Mich a e l Va n W a a s , P h .D .,
P re s id e n t, TMR As s o c ia te s
J ava. Ra y Fre d e rick D ja ja d in a ta , S tu d e n t a t Tris a kti U n ive rs ity,
J a ka rta
The m ere fact that you have m ade this work free over the Net puts m e into shock. I thought I’d let you know how m uch I appreciate and respect what you’re doin g. S h a n e Le B o u th illie r, Co m p u te r En gin e e rin g
s tu d e n t, U n ive rs ity o f Albe rta , Ca n a d a
I have to tell you how m uch I look forward to reading your m onthly colum n. As a newbie to the world of object oriented program m ing, I appreciate the tim e and thoughtfulness that you give to even the m ost elem entary topic. I have downloaded your book, but you can bet that I will purchase the hard copy when it is published. Than ks for all of your help.
D a n Ca s h m e r, B . C. Zie gle r & Co .
J ust want to congratulate you on a job well done. First I stum bled upon the PDF version of Thinking in Jav a. Even before I fin ished readin g it, I ran to the store and found Thinking in C++. Now, I have been in the com puter business for over eight years, as a consultant, software engineer, teacher/ trainer, and recently as self-em ployed, so I’d like to think that I have seen enough (not “have seen it all,” m ind you, but enough). H owever, these books cause m y girlfriend to call m e a ”geek.” Not that I have anything against the concept—it is just that I thought this phase was well beyond m e. But I find m yself truly enjoying both books, like n o other com puter book I have touched or bought so far. Excellen t writing style, very nice introduction of every new topic, and lots of wisdom in the books. Well done. S im o n Go la n d ,
s im o n s e z@s m a rtt.co m , S im o n S a ys Co n s u ltin g, In c.
I m ust say that your Thinking in Jav a is great! That is exactly the kind of docum entation I was looking for. Especially the sections about good and poor software design using J ava. D irk D u e h r, Le xiko n Ve rla g,
B e rte ls m a n n AG, Ge rm a n y
Than k you for writin g two great books (Thinking in C++, Thinking in
Jav a). You have helped m e im m ensely in m y progression to object
oriented program m ing. D o n a ld La w s o n , D CL En te rp ris e s
It’s the best J ava book I have ever read—and I read som e. J e a n -Yve s
MEN GAN T, Ch ie f S o ftw a re Arch ite ct N AT-S YS TEM, P a ris , Fra n ce
Thinking in Jav a gives the best coverage and explanation. Very easy to
read, and I m ean the code fragm ents as well. Ro n Ch a n , P h .D ., Exp e rt
Ch o ice , In c., P itts bu rgh P A
Your book is great. I have read lots of program m ing books and your book still adds in sights to program m in g in m y m in d. N in gjia n W a n g,
In fo rm a tio n S ys te m En gin e e r, Th e Va n gu a rd Gro u p
Thinking in Jav a is an excellent and readable book. I recom m end it to all
m y studen ts. D r. P a u l Go rm a n , D e p a rtm e n t o f Co m p u te r S cie n ce ,
U n ive rs ity o f Ota go , D u n e d in , N e w Ze a la n d
You m ake it possible for the proverbial free lunch to exist, not just a soup kitchen type of lunch but a gourm et delight for those who appreciate good software and books about it. J o s e S u rio l, S cyla x Co rp o ra tio n
Thanks for the opportunity of watching this book grow into a m asterpiece! IT IS TH E BEST book on the subject that I’ve read or browsed. J e ff
La p c h in s ky, P ro gra m m e r, N e t Re s u lts Te c h n o lo gie s
Your book is concise, accessible and a joy to read. Ke ith Ritc h ie , J a va
Re s e a rch & D e ve lo p m e n t Te a m , KL Gro u p In c.
It truly is the best book I’ve read on J ava! D a n ie l En g
The best book I have seen on J ava! Rich H o ffa rth , S e n io r Arch ite ct,
W e s t Gro u p
Than k you for a won derful book. I’m havin g a lot of fun goin g through the chapters. Fre d Trim ble , Ac tiu m Co rp o ra tio n
You have m astered the art of slowly and successfully m aking us grasp the details. You m ake learning VERY easy and satisfying. Thank you for a truly wonderful tutorial. Ra je s h Ra u , S o ftw a re Co n s u lta n t
Thinking in Jav a rocks the free world! Miko O’S u lliva n , P re s id e n t,
Ab o u t Th in k in g in C+ + :
B e s t B o o k! W in n e r o f th e
19 9 5 S o ftw a re D e ve lo p m e n t Ma ga zin e J o lt Aw a rd !
“This book is a trem en dous achievem en t. You owe it to yourself to have a copy on your shelf. The chapter on iostream s is the m ost
com prehen sive an d un derstan dable treatm en t of that subject I’ve seen to date.”
Al S te ve n s
Co n trib u tin g Ed ito r, D o c t o r D o b b s J o u r n a l
“Eckel’s book is the on ly on e to so clearly explain how to rethin k program con struction for object orien tation . That the book is also an excellent tutorial on the ins and outs of C++ is an added bonus.”
An d re w B in s to ck
Ed ito r, U n i x R e v i e w
“Bruce continues to am aze m e with his insight into C++, and Thin kin g
in C++ is his best collection of ideas yet. If you want clear answers to
difficult question s about C++, buy this outstan din g book.”
Ga ry En ts m in ge r
Au th o r, Th e Ta o o f O b je c t s
“Thin kin g in C++ patien tly an d m ethodically explores the issues of when an d how to use in lin es, referen ces, operator overloadin g, in heritan ce, an d dyn am ic objects, as well as advan ced topics such as the proper use of tem plates, exception s an d m ultiple in heritan ce. The en tire effort is woven in a fabric that includes Eckel’s own philosophy of object an d program design . A m ust for every C++ developer’s bookshelf, Thin kin g in C++ is the on e C++ book you m ust have if you’re doin g serious developm en t with C++.”
Thinking
in
J ava
Secon d Edition
Bruce Eckel
Presiden t, Min dView, In c.
Prentice H all
Library of Congress Cataloging-in-Publication Data Eckel, Bruce.
Thinking in Java / Bruce Eckel.--2nd ed. p. cm.
ISBN 0-13-027363-5
1. Java (Computer program language) I. Title. QA76.73.J38E25 2000
005.13'3--dc21 00-037522 CIP
Editorial/ Production Superv ision : Nicholas Radhuber Acquisition s Editor: Paul Petralia
Man ufacturin g Man ager: Maura Goldstaub Marketin g Man ager: Bryan Gam brel Cov er Design : Dan iel Will-H arris
In terior Design : Dan iel Will-H arris, www.will-harris.com
© 20 0 0 by Bruce Eckel, President, MindView, Inc. Published by Prentice H all PTR
Pren tice-H all, In c.
Upper Saddle River, NJ 0 7458
The in form ation in this book is distributed on an “as is” basis, without warran ty. While every precaution has been taken in the preparation of this book, n either the author n or the publisher shall have an y liability to an y person or en title with respect to an y liability, loss or dam age caused or alleged to be caused directly or in directly by in struction s con tain ed in this book or by the com puter software or hardware products described herein .
All rights reserved. No part of this book m ay be reproduced, in an y form or by an y m ean s, without perm ission in writin g from the publisher.
Pren tice-H all books are widely used by corporation s an d govern m en t agen cies for train in g, m arketin g, an d resale. The publisher offers discoun ts on this book when ordered in bulk quan tities. For m ore in form ation , con tact the Corporate Sales Departm en t at 8 0 0 -38 2-3419, fax: 20 1-236-7141, em ail:
corpsales@pren hall.com or write: Corporate Sales Departm en t, Pren tice H all PTR, On e Lake Street, Upper Saddle River, New J ersey 0 7458 .
J ava is a registered tradem ark of Sun Microsystem s, In c. Win dows 95 an d Win dows NT are tradem arks of Microsoft Corporation . All other product n am es an d com pan y n am es m en tion ed herein are the property of their respective own ers.
Prin ted in the Un ited States of Am erica 10 9 8 7 6 5 4 3 2 1
ISBN 0 -13-0 27363-5
Pren tice-H all In tern ation al (UK) Lim ited, Lon don Pren tice-H all of Australia Pty. Lim ited, Sy dn ey Pren tice-H all Can ada, In c., Toron to
Pren tice-H all H ispan oam erican a, S.A., M exico Pren tice-H all of In dia Private Lim ited, N ew Delhi Pren tice-H all of J apan , In c., Toky o
Pearson Education Asia Ltd., Sin gapore
Ch e ck w w w .Br u ce Eck e l.com
for in- dept h det ails
and t he dat e and locat ion
of t he nex t
H a n ds- On Ja v a Se m in a r
•
Based on this book
•
Taught by Bruce Eckel
•
Person al atten tion from Bruce Eckel
an d his sem in ar assistan ts
•
In cludes in -class program m in g exercises
•
In term ediate/ Advan ced sem in ars also offered
•
H un dreds have already en joyed this sem in ar—
Br u ce Eck e l’s H a n ds- On Ja va Se m in a r
Mult im edia CD
I t ’s lik e com ing t o t he sem inar !
Av ailable at w w w .Br uceEckel.com
!
The H ands-On Jav a Sem inar captured on a Multim edia CD!
!
Overhead slides an d syn chron ized audio voice n arration for all
the lectures. J ust play it to see an d hear the lectures!
!
Created and narrated by Bruce Eckel.
!
Based on the m aterial in this book.
Dedication
Over view
Preface
1
Introduction
9
1: Introduction to Objects
29
2: Everything is an Object
10 1
3: Con trollin g Program Flow
133
4: Initialization & Cleanup
191
5: H iding the Im plem entation
243
6: Reusing Classes
271
7: Polym orphism
311
8 : In terfaces & In ner Classes
349
9: H olding Your Objects
40 7
10 : Error H an dlin g with Exception s
531
11: The J ava I/ O System
573
12: Run-tim e Type Identification
659
13: Creatin g Win dows & Applets
68 9
14: Multiple Threads
8 25
15: Distributed Com puting
90 3
A: Passing & Returning Objects
10 13
B: The J ava Native Interface (J NI)
10 65
C: J ava Program m in g Guidelin es
10 77
D: Resources
10 91
What ’s I nside
Note on the cover design... 24
Acknowledgem ents ... 25
In tern et con tributors ... 28
1: Introduction
Is-a vs. is-like-a relation ships ...42
Interchangeable objects
Collection s an d iterators ... 51
The sin gly rooted hierarchy ... 53
Collection libraries an d support for easy collection use ... 54
The housekeepin g dilem m a:
Clien t-side program m ing ...63
Server-side program m in g ...70
A separate aren a:
Phase 5: Evolution ... 8 5 express an d un derstan d ...91
Maxim al leverage
Managem en t obstacles ... 95
J ava vs. C++? ... 97 Where storage lives ... 10 3 Special case: primitive types...10 5 Arrays in J ava...10 7 You never need to destroy an object ... 10 7 Scopin g... 10 8
Your first J ava program .. 119
Com pilin g an d runnin g ...121
Class docum en tation tags... 126
Variable docum en tation tags ... 127
Method docum en tation tags ... 127
Docum en tation exam ple ... 128 Using J ava operators ... 133
Castin g operators ...154
J ava has n o “sizeof”...158
Preceden ce revisited ...158
A com pen dium of operators ...159
Execution control... 170 Guaran teed in itialization with the constructor ...191
Method overloading... 194
Distin guishin g overloaded m ethods...196
Overloadin g with prim itives ...197
Overloadin g on return values ... 20 2 Default constructors ... 20 2 The th is keyword... 20 3 Cleanup: finalization and garbage collection ... 20 7 What is fin a lize ( ) for?... 20 8
Con structor in itialization ... 223
Array initialization ... 231
A custom tool library ... 251
Usin g im ports to chan ge behavior... 252
Package caveat ...254
J ava access specifiers ...255
“Frien dly”... 255
p u blic : in terface access ...256
p riva te :
In itializin g the base class ...278
developm ent ... 291 with inheritan ce ... 30 4 Sum m ary...30 6 Exercises ... 30 7
7: Polym orphism
311
Upcasting revisited ...311Forgettin g the object type ...313
The twist... 315
Method-call bin din g ...315
Producin g the right behavior ...316
Exten sibility ... 320
Order of con structor calls ... 330
In heritan ce an d fin a lize ( ) ... 333
Behavior of polym orphic m ethods in side con structors... 337
Designing with
“Multiple in heritan ce” in J ava ...354
Exten din g an in terface with inheritan ce...358
Groupin g constan ts ...359
In itializin g fields in in terfaces ... 361
Nestin g in terfaces ...362
Inner classes ... 365
In n er classes an d upcastin g ... 368
In n er classes in m ethods an d scopes ...370
An on ym ous inn er classes ... 373
The lin k to the outer class ... 376
s ta tic inn er classes ... 379
Referrin g to the outer class object ... 38 1 Reachin g outward from a m ultiply-n ested class ...38 3 In heritin g from inn er classes .... 38 4 Can in n er classes be overridden ? ...38 5 In n er class iden tifiers ...38 7 Why inn er classes? ... 38 8
Return in g an array...413
The Arrays class ...415
Fillin g an array... 428
Copyin g an array ... 429
Com parin g arrays ... 430
Array elem en t com parison s ...431
Sortin g an array ... 435
Searchin g a sorted array ... 437
Array summ ary ... 439
Introduction to
containers ...439
Prin tin g con tain ers ...441
Fillin g con tain ers ... 442
Container disadvantage: unknown type ...450
Som etim es it works an yway... 452
Makin g a type-con scious
ArrayLis t ... 454
S e t functionality ... 473
So rte d Se t ... 476
Vector & Enum eration ... 519
H ashtable... 521
Exception argum en ts... 533
Catching an exception .... 534
Catchin g an y exception ...543
Rethrowin g an exception ... 545
Standard J ava
exceptions... 549
The special case of
Ru n tim e Exc e ptio n ...550
with finally ... 552
Exception guidelin es ... 568
Sum m ary...568
and useful interfaces ... 58 5
Readin g from an In p u tStre a m
with Filte rIn p u tStre a m ... 58 6
Writin g to an Ou tp u tStre a m
with Filte rOu tp u tStre a m ... 58 7
Re a d e rs & W rite rs...58 9
Sources an d sin ks of data... 590
Modifyin g stream behavior...591
Un chan ged Classes ... 592
Off by itself:
Multifile storage with Zip ... 60 8
J ava ARchives (J ARs) ...611
Object serialization ... 613
Fin din g the class... 618
Con trollin g serialization ... 619
Usin g persisten ce ... 630
Tokenizing input ... 639
Stre a m To ke n ize r ...639 Strin gTo ke n ize r ...642
Checkin g capitalization style ...645
Sum m ary ...655
Checkin g before a cast ...665
RTTI syntax ...674 Reflection: run-tim e
class inform ation ...677
A class m ethod extractor ...679
a Web browser... 695
Usin g Appletv iew er ... 698
Testin g applets ... 698
Running applets from the com m and line ...70 0
A display fram ework ... 70 2
Usin g the Win dows Explorer ... 70 5
Making a button ...70 6 Capturing an event ... 70 7 Text areas ... 711
The Swing event m odel ... 722
Even t an d listen er types... 723
Trackin g multiple even ts ... 730
A catalog of Swing
Sliders an d progress bars ... 78 0
Trees ... 78 1
Bin din g even ts dyn am ically ...794
Separatin g busin ess
logic from UI logic ...796
A m ore sophisticated Bean ... 8 11
Packagin g a Bean ... 8 16
More com plex Bean support ... 8 18
More to Bean s... 8 19
Sum m ary ...8 19 Exercises... 8 20
14: Multiple Threads
8 25
Responsive
user interfaces ... 8 26
In heritin g from Th re a d ... 8 28
Threadin g for a
respon sive in terface... 8 31
with the m ain class ... 8 34
Makin g man y threads ... 8 36
Daem on threads...8 40
Sharing
lim ited resources...8 42
Im properly accessin g
resources ... 8 42
H ow J ava shares resources ... 8 48
J avaBeans revisited ... 8 54
Blocking ...8 59
Becom in g blocked ...8 60
Deadlock... 8 72
Priorities ... 8 77
Readin g an d
settin g priorities ... 8 78
Thread groups ... 8 8 2
Network program m ing ...90 4
Iden tifyin g a m achin e ... 90 5
Sockets ... 90 9
Servin g multiple clien ts ...917
Datagram s ... 923
Getting the exam ple to work...931
A GUI version
of the lookup program ... 935
Why the J DBC API
seem s so com plex... 938
A m ore sophisticated
exam ple...939
Servlets ... 948
The basic servlet ...949
Servlets an d m ultithreadin g...954
H an dlin g session s
with servlets ... 955
Run n in g the
servlet exam ples ... 960
J ava Server Pages ... 960
Im plicit objects ...962
J SP directives ...963
J SP scriptin g elem en ts ...964
Extractin g fields an d values ...966
J SP page
attributes an d scope ... 968
Man ipulatin g
Creatin g stubs an d skeleton s...978
Usin g the rem ote object ...979
EJ B com pon en t ... 994
The discovery process ... 10 0 6
The join process ... 10 0 6
The lookup process ... 10 0 7
Separation of in terface
an d im plem en tation... 10 0 8
Abstractin g
distributed system s ... 10 0 9
Sum m ary... 10 10
Addin g clon eability
to a class ... 10 20
Successful clon in g ... 10 22
The effect of
Obje ct.c lo n e ( ) ... 10 25
Clon in g a com posed object ...10 27
A deep copy
with Arra yLis t... 10 30
Deep copy via serialization ... 10 32
Addin g clon eability
further down a hierarchy... 10 34
Why this stran ge design? ... 10 35
Controlling
cloneability ...10 36
The copy con structor ... 10 42
Read-only classes ...10 47
Creatin g read-on ly classes...10 49
The drawback
gen erator: javah ... 10 67
Nam e m an glin g an d
fun ction sign atures ...10 68
Im plem en tin g your DLL...10 68
Accessing J NI functions: the J N IEn v argum ent ..10 69
Accessin g J ava Strin gs ... 10 71
Passing and
C: J ava Program m in g
Guidelin es 10 77
Design ... 10 77 Im plem entation ... 10 8 4
D: Resources
10 91
Software ... 10 91
Books ... 10 91
An alysis & design ... 10 93
Python ... 10 95
My own list of books...10 96
Pr eface
I suggested to m y brother Todd, who is m akin g the leap
from hardware in to program m in g, that the n ext big
revolution will be in gen etic en gin eering.
We’ll have m icrobes design ed to m ake food, fuel, and plastic; they’ll clean up pollution and in general allow us to m aster the m anipulation of the physical world for a fraction of what it costs now. I claim ed that it would m ake the com puter revolution look sm all in com parison.
Then I realized I was m aking a m istake com m on to science fiction writers: gettin g lost in the techn ology (which is of course easy to do in scien ce fiction). An experienced writer knows that the story is never about the things; it’s about the people. Genetics will have a very large im pact on our lives, but I’m not so sure it will dwarf the com puter revolution (which enables the genetic revolution)—or at least the inform ation revolution. Inform ation is about talking to each other: yes, cars and shoes and especially genetic cures are im portant, but in the end those are just trappings. What truly m atters is how we relate to the world. And so m uch of that is about com m unication.
This book is a case in poin t. A m ajority of folks thought I was very bold or a little crazy to put the entire thing up on the Web. “Why would anyone buy it?” they asked. If I had been of a m ore conservative nature I wouldn’t have done it, but I really didn’t want to write another com puter book in the sam e old way. I didn’t know what would happen but it turned out to be the sm artest thing I’ve ever done with a book.
For on e thin g, people started sen din g in correction s. This has been an am azing process, because folks have looked into every nook and cranny and caught both technical and gram m atical errors, and I’ve been able to elim inate bugs of all sorts that I know would have otherwise slipped through. People have been sim ply terrific about this, very often saying “Now, I don’t m ean this in a critical way…” and then giving m e a
been a kind of group process and it has really m ade the book into som ething special.
But then I started hearing “OK, fine, it’s nice you’ve put up an electronic version, but I want a printed and bound copy from a real publisher.” I tried very hard to m ake it easy for everyon e to prin t it out in a n ice lookin g form at but that didn’t stem the dem and for the published book. Most people don’t want to read the entire book on screen, and hauling around a sheaf of papers, no m atter how nicely printed, didn’t appeal to them either. (Plus, I think it’s not so cheap in term s of laser printer toner.) It seem s that the com puter revolution won’t put publishers out of business, after all. H owever, one student suggested this m ay becom e a m odel for future publishing: books will be published on the Web first, and only if sufficient in terest warran ts it will the book be put on paper. Curren tly, the great m ajority of all books are financial failures, and perhaps this new approach could m ake the publishing industry m ore profitable.
This book becam e an enlightening experience for m e in another way. I originally approached J ava as “just another program m ing language,” which in m an y sen ses it is. But as tim e passed an d I studied it m ore deeply, I began to see that the fundam ental intention of this language is differen t from all the other lan guages I have seen.
Program m ing is about m anaging com plexity: the com plexity of the problem you want to solve, laid upon the com plexity of the m achine in which it is solved. Because of this com plexity, m ost of our program m in g projects fail. And yet, of all the program m ing languages of which I am aware, none of them have gone all-out and decided that their m ain design goal would be to conquer the com plexity of developing and m aintaining program s1. Of course, m any language design decisions were m ade with
com plexity in m ind, but at som e point there were always som e other issues that were considered essential to be added into the m ix. Inevitably, those other issues are what cause program m ers to eventually “hit the wall” with that language. For exam ple, C++ had to be
backwards-com patible with C (to allow easy m igration for C program m ers), as well as
1 I take this back on the 2n d edition: I believe that the Python language com es closest to
efficient. Those are both very useful goals an d accoun t for m uch of the success of C++, but they also expose extra com plexity that prevents som e projects from being finished (certainly, you can blam e program m ers and m anagem ent, but if a language can help by catching your m istakes, why shouldn’t it?). As another exam ple, Visual Basic (VB) was tied to BASIC, which wasn’t really designed to be an extensible language, so all the extensions piled upon VB have produced som e truly horrible and unm aintainable syntax. Perl is backwards-com patible with Awk, Sed, Grep, and other Unix tools it was m eant to replace, and as a result is often accused of producing “write-only code” (that is, after a few m onths you can’t read it). On the other hand, C++, VB, Perl, and other languages like Sm alltalk had som e of their design efforts focused on the issue of
com plexity and as a result are rem arkably successful in solving certain types of problem s.
What has im pressed m e m ost as I have com e to un derstan d J ava is what seem s like an unflinching goal of reducing com plexity for the
program m er. As if to say “we don’t care about anything except reducing
the tim e and difficulty of producing robust code.” In the early days, this goal has resulted in code that doesn’t run very fast (although there have been m any prom ises m ade about how quickly J ava will som eday run) but it has in deed produced am azin g reduction s in developm ent tim e; half or less of the tim e that it takes to create an equivalent C++ program . This result alone can save incredible am ounts of tim e and m oney, but J ava doesn’t stop there. It goes on to wrap all the com plex tasks that have becom e im portant, such as m ultithreading and network program m ing, in language features or libraries that can at tim es m ake those tasks trivial. And finally, it tackles som e really big com plexity problem s: cross-platform program s, dynam ic code changes, and even security, each of which can fit on your com plexity spectrum anywhere from “im pedim ent” to “show-stopper.” So despite the perform ance problem s we’ve seen, the prom ise of J ava is trem endous: it can m ake us sign ifican tly m ore productive
program m ers.
businesses). As we talk to each other m ore, am azing things begin to happen, possibly m ore am azing even than the prom ise of genetic engineering.
In all ways—creating the program s, working in team s to create the program s, building user interfaces so the program s can com m unicate with the user, running the program s on different types of m achines, and easily writing program s that com m unicate across the Internet—J ava increases the com m unication bandwidth betw een people. I think that perhaps the results of the com m unication revolution will not be seen from the effects of m oving large quantities of bits around; we shall see the true revolution because we will all be able to talk to each other m ore easily: one-on-one, but also in groups and, as a planet. I've heard it suggested that the next revolution is the form ation of a kind of global m ind that results from enough people and enough interconnectedness. J ava m ay or m ay not be the tool that fom ents that revolution, but at least the
possibility has m ade m e feel like I'm doin g som ethin g m ean in gful by attem pting to teach the language.
Pr eface t o t he 2
nd
edit ion
w w w .BruceEckel.com ). If you wan t the old stuff, it’s still there, an d this is
a wonderful relief for an author. For exam ple, you m ay notice that the original last chapter, “Projects,” is no longer here; two of the projects have been integrated into other chapters, and the rest were no longer
appropriate. Also, the “Design Pattens” chapter becam e too big and has been m oved into a book of its own (also downloadable at the Web site). So, by all rights the book should be thinner.
But alas, it is not to be.
The biggest issue is the continuing developm ent of the J ava language itself, an d in particular the expan din g APIs that prom ise to provide standard interfaces for just about everything you’d like to do (and I won’t be surprised to see the “J Toaster” API eventually appear). Covering all these APIs is obviously beyond the scope of this book and is a task
relegated to other authors, but som e issues cannot be ignored. The biggest of these include server-side J ava (prim arily Servlets & J ava Server pages, or JSPs), which is truly an excellent solution to the World Wide Web problem , wherein we’ve discovered that the various Web browser platform s are just not consistent enough to support client-side
program m ing. In addition, there is the whole problem of easily creating applications to interact with databases, transactions, security, and the like, which is involved with Enterprise J ava Beans (EJ Bs). These topics are wrapped into the chapter form erly called “Network Program m ing” and now called “Distributed Com puting,” a subject that is becom ing essential to everyone. You’ll also find this chapter has been expanded to include an overview of J ini (pronounced “genie,” and it isn’t an acronym , just a nam e), which is a cutting-edge technology that allows us to change the way we think about interconnected applications. And of course the book has been changed to use the Swing GUI library throughout. Again, if you wan t the old J ava 1.0 / 1.1 stuff you can get it from the
function works (so that you can know how to properly create one). There have been other m ovem ents and changes, including a rewrite of Chapter 1, and rem oval of som e appendices and other m aterial that I consider no longer necessary for the printed book, but those are the bulk of them . In general, I’ve tried to go over everything, rem ove from the 2nd edition what
is n o lon ger n ecessary (but which still exists in the electron ic first edition ), include changes, and im prove everything I could. As the language
continues to change—albeit not quite at the sam e breakneck pace as before—there will n o doubt be further edition s of this book.
For those of you who still can’t stand the size of the book, I do apologize. Believe it or not, I have worked hard to keep it sm all. Despite the bulk, I feel like there m ay be enough alternatives to satisfy you. For one thing, the book is available electronically (from the Web site, and also on the CD ROM that accom pan ies this book), so if you carry your laptop you can carry the book on that with no extra weight. If you’re really into slim m ing down, there are actually Palm Pilot versions of the book floating around. (On e person told m e he would read the book in bed on his Palm with the backlighting on to keep from annoying his wife. I can only hope that it helps sen d him to slum berland.) If you n eed it on paper, I know of people who print a chapter at a tim e and carry it in their briefcase to read on the train.
Java 2
At this writin g, the release of Sun ’s Jav a Dev elopm ent Kit (J DK) 1.3 is im m inent, and the proposed changes for J DK 1.4 have been publicized. Although these version num bers are still in the “ones,” the standard way to refer to any version of the language that is J DK 1.2 or greater is to call it “J ava 2.” This indicates the very significant changes between “old J ava”— which had m an y warts that I com plain ed about in the first edition of this book—and this m ore m odern and im proved version of the language, which has far fewer warts and m any additions and nice designs.
This book is written for J ava 2. I have the great luxury of getting rid of all the old stuff an d writin g to on ly the n ew, im proved lan guage because the old in form ation still exists in the electron ic 1st edition on the Web and on
J DK from java.sun .com , it m ean s that by writin g to J ava 2 I’m n ot im posing a financial hardship on som eone by forcing them to upgrade. There is a bit of a catch, however. J DK 1.3 has som e im provem ents that I’d really like to use, but the version of J ava that is currently being released for Linux is J DK 1.2.2. Linux (see www.Linux.org) is a very im portan t developm ent in con jun ction with J ava, because it is fast becom ing the m ost im portant server platform out there—fast, reliable, robust, secure, well-m aintained, and free, a true revolution in the history of com puting (I don’t think we’ve ever seen all of those features in any tool before). And J ava has found a very im portant niche in server-side program m ing in the form of Serv lets, a technology that is a huge im provem ent over the tradition al CGI program m in g (this is covered in the “Distributed Program m ing” chapter).
So although I would like to on ly use the very n ewest features, it’s critical that everything com piles under Linux, and so when you unpack the source code an d com pile it un der that OS (with the latest J DK) you’ll discover that everything will com pile. H owever, you will find that I’ve put notes about features in J DK 1.3 here and there.
The CD ROM
An other bon us with this edition is the CD ROM that is packaged in the back of the book. I’ve resisted puttin g CD ROMs in the back of m y books in the past because I felt the extra charge for a few Kbytes of source code on this enorm ous CD was n ot justified, preferrin g in stead to allow people to down load such thin gs from m y Web site. H owever, you’ll soon see that this CD ROM is differen t.
The CD does contain the source code from the book, but it also contains the book in its entirety, in several electronic form ats. My favorite of these is the H TML form at, because it is fast an d fully in dexed—you just click on an entry in the index or table of contents and you’re im m ediately at that portion of the book.
stand-alone product, but decided to include it with the second editions of both Thinking in C++ and Thinking in Jav a because of the consistent experience of having people com e to sem inars without an adequate background in C. The thinking apparently goes “I’m a sm art program m er and I don’t w ant to learn C, but rather C++ or J ava, so I’ll just skip C an d go directly to C++/ J ava.” After arriving at the sem inar, it slowly dawns on folks that the prerequisite of understanding C syntax is there for a very good reason. By including the CD ROM with the book, we can ensure that everyone attends a sem inar with adequate preparation.
I nt r oduct ion
Like an y hum an lan guage, J ava provides a way to express
con cepts. If successful, this m edium of expression will be
sign ifican tly easier an d m ore flexible than the altern atives
as problem s grow larger an d m ore com plex.
You can’t look at J ava as just a collection of features—som e of the features m ake no sense in isolation. You can use the sum of the parts only if you are thinking about design, not sim ply coding. And to understand J ava in this way, you m ust understand the problem s with it and with
program m ing in general. This book discusses program m ing problem s, why they are problem s, and the approach J ava has taken to solve them . Thus, the set of features I explain in each chapter are based on the way I see a particular type of problem being solved with the language. In this way I hope to m ove you, a little at a tim e, to the point where the J ava m indset becom es your native tongue.
Throughout, I’ll be taking the attitude that you want to build a m odel in your head that allows you to develop a deep understanding of the
lan guage; if you encoun ter a puzzle you’ll be able to feed it to your m odel and deduce the answer.
Pr er equisit es
willing to work hard; also, the m ultim edia CD that accom panies this book will bring you up to speed on the basic C syntax necessary to learn J ava). I’ll be introducing the concepts of object-oriented program m ing (OOP) and J ava’s basic control m echanism s, so you’ll be exposed to those, and the first exercises will involve the basic control-flow statem ents.
Although references will often be m ade to C and C++ language features, these are not intended to be insider com m ents, but instead to help all program m ers put J ava in perspective with those languages, from which, after all, J ava is descended. I will attem pt to m ake these references sim ple and to explain anything that I think a non- C/ C++ program m er would not be fam iliar with.
Lear ning Java
At about the sam e tim e that m y first book Using C++ (Osborne/ McGraw-H ill, 198 9) cam e out, I began teaching that language. Teaching
the short lessons. I now give this course in public J ava sem inars, which you can find out about at w w w .BruceEckel.com . (The introductory sem inar is also available as a CD ROM. Inform ation is available at the sam e Web site.)
The feedback that I get from each sem inar helps m e change and refocus the m aterial until I think it works well as a teaching m edium . But this book isn’t just sem inar notes—I tried to pack as m uch inform ation as I could within these pages, and structured it to draw you through onto the next subject. More than anything, the book is designed to serve the solitary reader who is struggling with a new program m ing language.
Goals
Like m y previous book Thinking in C++, this book has com e to be
structured around the process of teaching the language. In particular, m y m otivation is to create som ething that provides m e with a way to teach the language in m y own sem inars. When I think of a chapter in the book, I think in term s of what m akes a good lesson during a sem inar. My goal is to get bite-sized pieces that can be taught in a reasonable am ount of tim e, followed by exercises that are feasible to accom plish in a classroom situation.
My goals in this book are to:
1. Present the m aterial one sim ple step at a tim e so that you can easily digest each concept before m oving on.
2. Use exam ples that are as sim ple and short as possible. This som etim es preven ts m e from tacklin g “real world” problem s, but I’ve found that beginners are usually happier when they can
3. Carefully sequence the presentation of features so that you aren’t seeing som ething that you haven’t been exposed to. Of course, this isn’t always possible; in those situations, a brief introductory description is given .
4. Give you what I think is im portant for you to understand about the language, rather than everything I know. I believe there is an inform ation im portance hierarchy, and that there are som e facts that 95 percent of program m ers will never need to know and that just confuse people and adds to their perception of the com plexity of the language. To take an exam ple from C, if you m em orize the operator precedence table (I never did), you can write clever code. But if you need to think about it, it will also confuse the
reader/ m aintainer of that code. So forget about precedence, and use parentheses when things aren’t clear.
5. Keep each section focused enough so that the lecture tim e—and the tim e between exercise periods—is sm all. Not only does this keep the audience’s m inds m ore active and involved during a hands-on sem inar, but it gives the reader a greater sense of accom plishm ent.
6. Provide you with a solid foun dation so that you can un derstan d the issues well en ough to m ove on to m ore difficult coursework an d books.
Online docum ent at ion
Chapt er s
This book was designed with one thing in m ind: the way people learn the J ava language. Sem inar audience feedback helped m e understand the difficult parts that needed illum ination. In the areas where I got am bitious and included too m any features all at once, I cam e to know—through the process of presenting the m aterial—that if you include a lot of new features, you need to explain them all, and this easily com pounds the student’s confusion. As a result, I’ve taken a great deal of trouble to introduce the features as few at a tim e as possible.
The goal, then, is for each chapter to teach a single feature, or a sm all group of associated features, without relying on additional features. That way you can digest each piece in the context of your current knowledge before m oving on.
H ere is a brief description of the chapters contained in the book, which correspond to lectures and exercise periods in m y hands-on sem inars.
Ch a p t e r 1:
In t r o d u c t i o n t o O b je c t s
This chapter is an overview of what object-oriented
program m ing is all about, including the answer to the basic question “What’s an object?”, interface vs. im plem entation, abstraction and encapsulation, m essages and functions, inheritance and com position, and the all-im portant
polym orphism . You’ll also get an overview of issues of object creation such as constructors, where the objects live, where to put them once they’re created, and the m agical garbage collector that cleans up the objects that are no longer needed. Other issues will be in troduced, in cludin g error han dlin g with exceptions, m ultithreading for responsive user interfaces, and networking and the Internet. You’ll learn what m akes J ava special, why it’s been so successful, and about object-oriented analysis and design.
Ch a p t e r 2 :
Ev e r y t h i n g i s a n O b je c t
This chapter m oves you to the point where you can write your first J ava program , so it m ust give an overview of the
how to create an object; an introduction to prim itive types and arrays; scoping and the way objects are destroyed by the garbage collector; how everything in J ava is a new data type (class) and how to create your own classes; functions, argum ents, and return values; nam e visibility and using com ponents from other libraries; the s ta tic keyword; and com m ents and em bedded docum entation.
Ch a p t e r 3 :
Co n t r o lli n g P r o g r a m Flo w
This chapter begins with all of the operators that com e to J ava from C and C++. In addition, you’ll discover com m on
operator pitfalls, casting, prom otion, and precedence. This is followed by the basic control-flow and selection operations that you get with virtually any program m ing language: choice with if-else; looping with for and while; quitting a loop with break and continue as well as J ava’s labeled break and labeled continue (which account for the “m issing goto” in J ava); and selection usin g switch. Although m uch of this m aterial has com m on threads with C and C++ code, there are som e differences. In addition, all the exam ples will be full J ava exam ples so you’ll get m ore com fortable with what J ava looks like.
Ch a p t e r 4 :
In i t i a li z a t i o n & Cle a n u p
This chapter begins by introducing the constructor, which guarantees proper initialization. The definition of the constructor leads into the concept of function overloading (sin ce you m ight wan t several con structors). This is followed by a discussion of the process of cleanup, which is not always as sim ple as it seem s. Norm ally, you just drop an object when you’re done with it and the garbage collector eventually com es along and releases the m em ory. This portion explores the garbage collector and som e of its idiosyncrasies. The chapter concludes with a closer look at how things are initialized: autom atic m em ber in itialization , specifyin g m em ber
Ch a p t e r 5 :
H i d i n g t h e Im p le m e n t a t io n
This chapter covers the way that code is packaged together, and why som e parts of a library are exposed while other parts are hidden. It begins by looking at the p a cka ge and im p o rt keywords, which perform file-level packaging and allow you to build libraries of classes. It then exam ines subject of directory paths and file nam es. The rem ainder of the chapter looks at the p u blic, p riva te , and p ro te c te d keywords, the concept of “friendly” access, and what the different levels of access control m ean when used in various contexts.
Ch a p t e r 6 :
R e u s i n g Cla s s e s
The concept of inheritance is standard in virtually all OOP languages. It’s a way to take an existing class and add to its functionality (as well as change it, the subject of Chapter 7). Inheritance is often a way to reuse code by leaving the “base class” the sam e, and just patching things here and there to produce what you want. H owever, inheritance isn’t the only way to m ake new classes from existing ones. You can also em bed an object inside your new class with com position . In this chapter you’ll learn about these two ways to reuse code in J ava, and how to apply them .
Ch a p t e r 7:
P o ly m o r p h i s m
On your own, you m ight take nine m onths to discover and understand polym orphism , a cornerstone of OOP. Through sm all, sim ple exam ples you’ll see how to create a fam ily of types with inheritance and m anipulate objects in that fam ily through their com m on base class. J ava’s polym orphism allows you to treat all objects in this fam ily generically, which m ean s the bulk of your code doesn ’t rely on specific type in form ation . This m akes your program s exten sible, so building program s and code m aintenance is easier and cheaper.
Ch a p t e r 8 :
In t e r fa c e s & In n e r Cla s s e s
abstract class taken to the extrem e, since it allows you to perform a variation on C++’s “m ultiple inheritance,” by creating a class that can be upcast to m ore than one base type. At first, inner classes look like a sim ple code hiding
m echanism : you place classes inside other classes. You’ll learn, however, that the inner class does m ore than that—it knows about and can com m unicate with the surrounding class—and that the kind of code you can write with inner classes is m ore elegant and clear, although it is a new concept to m ost and takes som e tim e to becom e com fortable with design using inner classes.
Ch a p t e r 9 :
H o ld in g y o u r O b je c t s
It’s a fairly sim ple program that has only a fixed quantity of objects with known lifetim es. In general, your program s will always be creating new objects at a variety of tim es that will be known only while the program is running. In addition, you won’t know until run-tim e the quantity or even the exact type of the objects you need. To solve the general program m ing problem , you need to create any num ber of objects, anytim e, anywhere. This chapter explores in depth the container library that J ava 2 supplies to hold objects while you’re working with them : the sim ple arrays and m ore sophisticated containers (data structures) such as Arra yLis t and
H a s h Ma p .
Ch a p t e r 10 : Er r o r H a n d li n g w i t h Exc e p t i o n s
The basic philosophy of J ava is that badly-form ed code will n ot be run . As m uch as possible, the com piler catches problem s, but som etim es the problem s—either program m er error or a natural error condition that occurs as part of the norm al execution of the program —can be detected and dealt with only at run-tim e. J ava has exception handling to deal with any problem s that arise while the program is running. This chapter exam ines how the keywords try, ca tch , th ro w ,
th ro w s , and fin a lly work in J ava; when you should throw
what happens with exceptions in constructors, and how exception handlers are located.
Ch a p t e r 11:
Th e J a v a I/ O S y s t e m
Theoretically, you can divide any program into three parts: in put, process, an d output. This im plies that I/ O
(input/ output) is an im portant part of the equation. In this chapter you’ll learn about the different classes that J ava provides for readin g an d writin g files, blocks of m em ory, an d the console. The distinction between “old” I/ O and “new” J ava I/ O will be shown. In addition, this chapter exam ines the process of taking an object, “stream ing” it (so that it can be placed on disk or sent across a network) and reconstructing it, which is han dled for you with J ava’s object serialization. Also, J ava’s com pression libraries, which are used in the J ava ARchive file form at (J AR), are exam ined.
Ch a p t e r 12 : R u n -Ti m e Ty p e Id e n t i fi c a t i o n
J ava run-tim e type identification (RTTI) lets you find the exact type of an object when you have a reference to only the base type. Norm ally, you’ll want to intentionally ignore the exact type of an object and let J ava’s dynam ic binding
m echanism (polym orphism ) im plem ent the correct behavior for that type. But occasionally it is very helpful to know the exact type of an object for which you have only a base reference. Often this inform ation allows you to perform a special-case operation m ore efficiently. This chapter explains what RTTI is for, how to use it, and how to get rid of it when it doesn’t belong there. In addition, this chapter introduces the J ava reflection m echanism .
Ch a p t e r 13 : Cr e a t i n g W i n d o w s a n d A p p le t s
J ava com es with the “Swing” GUI library, which is a set of classes that handle windowing in a portable fashion. These windowed program s can either be applets or stand-alone applications. This chapter is an introduction to Swing and the creation of World Wide Web applets. The im portant
for the creation of Rapid-Application Developm ent (RAD) program -building tools.
Ch a p t e r 14 : M u lt i p le Th r e a d s
J ava provides a built-in facility to support m ultiple
concurrent subtasks, called threads, running within a single program . (Unless you have m ultiple processors on your m achin e, this is on ly the appearance of m ultiple subtasks.) Although these can be used anywhere, threads are m ost apparent when trying to create a responsive user interface so, for exam ple, a user isn’t prevented from pressing a button or enterin g data while som e processin g is goin g on . This chapter looks at the syntax and sem antics of m ultithreading in J ava.
Ch a p t e r 15 : D i s t r i b u t e d Co m p u t i n g
All the J ava features and libraries seem to really com e together when you start writing program s to work across networks. This chapter explores com m unication across networks and the Internet, and the classes that J ava provides to m ake this easier. It introduces the very im portant concepts of Serv lets and JSPs (for server-side program m ing), along
w ith Jav a DataBase Con n ectiv ity (J DBC), and R em ote M ethod In v ocation (RMI). Finally, there’s an introduction to
the new technologies of JIN I, Jav aSpaces, and Enterprise
Jav aBeans (EJ Bs).
A p p e n d i x A : P a s s i n g & R e t u r n i n g O b je c t s
Since the only way you talk to objects in J ava is through references, the concepts of passing an object into a function and returning an object from a function have som e interesting consequences. This appendix explains what you need to know to m anage objects when you’re m oving in and out of
functions, and also shows the S trin g class, which uses a different approach to the problem .
Ap p e n d i x B : Th e J a v a N a t i v e In t e r fa c e ( J N I)
dram atically speed up certain operations by m aking them
nativ e m ethods, which are functions that are written in
another program m ing language (currently, only C/ C++ is supported). This appendix gives you enough of an
introduction to this feature that you should be able to create sim ple exam ples that interface with non-J ava code.
A p p e n d i x C: J a v a P r o g r a m m i n g Gu i d e li n e s
This appendix contains suggestions to help guide you while perform ing low-level program design and writing code.
A p p e n d ix D : R e c o m m e n d e d R e a d in g
A list of som e of the J ava books I’ve foun d particularly useful.
Exer cises
I’ve discovered that sim ple exercises are exceptionally useful to com plete a student’s understanding during a sem inar, so you’ll find a set at the end of each chapter.
Most exercises are designed to be easy enough that they can be finished in a reasonable am ount of tim e in a classroom situation while the instructor observes, m aking sure that all the students are absorbing the m aterial. Som e exercises are m ore advanced to prevent boredom for experienced students. The m ajority are designed to be solved in a short tim e and test and polish your knowledge. Som e are m ore challenging, but none present m ajor challenges. (Presum ably, you’ll find those on your own—or m ore likely they’ll find you).
Solutions to selected exercises can be found in the electronic docum ent
The Thin kin g in Jav a An n otated Solution Guide, available for a sm all fee
from www.BruceEckel.com .
Mult im edia CD ROM
A second Multim edia CD ROM is available, which is based on the con tents of the book. This CD ROM is a separate product and contains the e n tire contents of the week-long “H ands-On J ava” training sem inar. This is m ore than 15 hours of lectures that I have recorded, synchronized with hun dreds of slides of in form ation . Because the sem in ar is based on this book, it is an ideal accom panim ent.
The CD ROM contains all the lectures (with the im portant exception of personalized attention!) from the five-day full-im m ersion training sem inars. We believe that it sets a new standard for quality.
The H ands-On J ava CD ROM is available only by ordering directly from the Web site w w w .BruceEckel.com .
Sour ce code
All the source code for this book is available as copyrighted freeware, distributed as a single package, by visiting the Web site
w w w .BruceEckel.com . To m ake sure that you get the m ost current
version, this is the official site for distribution of the code and the electronic version of the book. You can find m irrored versions of the electronic book and the code on other sites (som e of these sites are found at w w w .BruceEckel.com ), but you should check the official site to ensure that the m irrored version is actually the m ost recent edition. You m ay distribute the code in classroom and other educational situations.
The prim ary goal of the copyright is to ensure that the source of the code is properly cited, and to prevent you from republishing the code in print m edia without perm ission. (As long as the source is cited, using exam ples from the book in m ost m edia is generally not a problem .)
In each source code file you will fin d a referen ce to the followin g copyright notice:
//:! :CopyRight.txt
Copyright ©2000 Bruce Eckel
Source code file from the 2nd edition of the book
"Thinking in Java." All rights reserved EXCEPT as
allowed by the following statements:
for your own work (personal or commercial),
including modifications and distribution in
executable form only. Permission is granted to use
this file in classroom situations, including its
use in presentation materials, as long as the book
"Thinking in Java" is cited as the source.
Except in classroom situations, you cannot copy
and distribute this code; instead, the sole
distribution point is http://www.BruceEckel.com
(and official mirror sites) where it is
freely available. You cannot remove this
copyright and notice. You cannot distribute
modified versions of the source code in this
package. You cannot use this file in printed
media without the express permission of the
author. Bruce Eckel makes no representation about
the suitability of this software for any purpose.
It is provided "as is" without express or implied
warranty of any kind, including any implied
warranty of merchantability, fitness for a
particular purpose or non-infringement. The entire
risk as to the quality and performance of the
software is with you. Bruce Eckel and the
publisher shall not be liable for any damages
suffered by you or any third party as a result of
using or distributing software. In no event will
Bruce Eckel or the publisher be liable for any
lost revenue, profit, or data, or for direct,
indirect, special, consequential, incidental, or
punitive damages, however caused and regardless of
the theory of liability, arising out of the use of
or inability to use software, even if Bruce Eckel
and the publisher have been advised of the
possibility of such damages. Should the software
prove defective, you assume the cost of all
necessary servicing, repair, or correction. If you
think you've found an error, please submit the
correction using the form you will find at
www.BruceEckel.com. (Please use the same
form for non-code errors found in the book.)