ThinkInJava2. 3.98MB 2013-07-11 22:00:30
Thinking in J ava,
2 nd Edition, Release 11
To be published by Prentice-Hall m id-J une, 20 0 0
Bruce Eckel, President,
MindView, Inc.
Planet PDF brings you the Portable Docum ent
Form at (PDF) version of Thinking in J ava (2nd
Edition). Planet PDF is the prem ier PDF-related
site on the web. There is news, software, white
papers, interviews, product reviews, Web links,
code sam ples, a forum , and regular articles by
m any of the m ost prom inent and respected PDF
experts in the world. Visit our sites for m ore detail:
http:/ / www.planetpdf.com /
http:/ / www.codecuts.com /
http:/ / www.pdfforum .com /
http:/ / www.pdfstore.com /
Thinking
in
J ava
Second Edition
Bruce Eckel
President, MindView, Inc.
Com m ent s from readers:
Much 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
and intelligent, not dum bed-down, explanations ... In contrast to m any
other J ava books I found it to be unusually m ature, consistent,
intellectually honest, well-written and precise. IMHO, an ideal book for
studying J ava. An ato ly Vo ro be y, Te ch n io n U n ive rs ity, H aifa,
Is rae l
One of the absolutely best programming tutorials I’ve seen for any
language. Jo akim Zie gle r, FIX s ys o p
Thank you for your wonderful, wonderful book on J ava. D r. Gavin
Pillay, Re gis trar, Kin g Ed w ard VIII H o s p ital, So u th Africa
Thank you again for your awesom e book. I was really floundering (being a
non-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. Hopefully I will be able to
attend your sem inar in the not-too-distant future. Ran d all R. H aw le y,
Au to m atio n Te ch n ician , Eli Lilly & Co .
The best computer book writing I have seen. To m H o llan 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. Ravin d ra Pai, Oracle
Co rp o ratio n , SU N OS p ro d u ct lin e
This is the best book on J ava that I have ever found! You have done a
great job. Your depth is am azing. I will be purchasing the book when it is
published. I have been learning J ava since October 96. I have read a few
books, and consider yours a “MUST READ.” These past few m onths we
have been focused on a product written entirely in J ava. Your book has
helped solidify topics I was shaky on and has expanded m y knowledge
base. I have even used som e of your explanations as inform ation in
interviewing contractors to help our team . I have found how m uch J ava
knowledge they have by asking them about things I have learned from
reading your book (e.g., the difference between arrays and Vectors). Your
book is great! Ste ve W ilkin s o n , Se n io r Staff Sp e cialis t, MCI
Te le co m m u n icatio n s
Great book. Best book on J ava I have seen so far. Je ff Sin clair,
So ftw are En gin e e r, Ke s tral Co m p u tin g
Thank you for Thinking in Java. It’s tim e som eone went beyond m ere
language description to a thoughtful, penetrating analytic tutorial that
doesn’t kowtow to The Manufacturers. I’ve read almost 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 ard Bro o ks ,
Java Co n s u ltan t, Su n Pro fe s s io n al Se rvice s , D allas
Other books cover the WHAT of J ava (describing the syntax and the
libraries) or the HOW of J ava (practical program m ing exam ples).
Thinking in Java is the only book I know that explains the WHY 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 Java is definitely the thinking person’s choice in a J ava book.
Ro be rt S. Ste 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 want to com m end you for your work on Thinking in Java. It is
people like you that dignify the future of the Internet and I just want to
thank you for your effort. It is very m uch appreciated. Patrick Barre ll,
N e tw o rk Office r Mam co , QAF Mfg. In c.
Most of the J ava books out there are fine for a start, and most just have
beginning stuff and 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 Java.
Ge o rge Lafram 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 Modern
Problem s) “I like it!” Very inform ative and explanatory, without reading
like a dry textbook. You cover the m ost im portant yet the least covered
concepts of J ava developm ent: the whys. Se an Brad 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
documentation. And you don’t waste the reader’s time with the basic facts
a program m er already knows. Kai En ge rt, In n o vative So ftw are ,
Ge rm an 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
finding that you’ve retained the sam e high level of writing. Thank you!
Pe te r R. N e u w ald
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 Java as the basis for a part of each m onthly
SIG m eeting, in which we review and discuss each chapter in succession.
Mark Erte s
I really appreciate your work and your book is good. I recom m end 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
Fran ce , H e ad o f Scie n tific Co m p u tin g an d In d u s trial Tran fe rt
OK, I’ve only read about 40 pages of Thinking in Java, 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, myself, 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 most computer books—even ones that
cam e with glowing recommendations. I feel a whole lot better now.
Gle n n Be cke r, Ed u catio n al Th e atre As s o ciatio n
Thank you for m aking your wonderful book available. I have found it
im m ensely useful in finally understanding what I experienced as
confusing in J ava and C++. Reading your book has been very satisfying.
Fe lix Bizao u i, Tw in Oaks In d u s trie s , Lo u is a, Va.
I m ust congratulate you on an excellent book. I decided to have a look at
Thinking in Java based on my experience with Thinking in C++, and I
was not disappointed. Jaco van d e r Me rw e , So ftw are Sp e cialis t,
D ataFu s io n Sys te m s Ltd , Ste lle n bo s ch , So u th Africa
This has to be one of the best J ava books I’ve seen. E.F. Pritch ard ,
Se n io r So ftw are En gin e e r, Cam brid ge An im atio n Sys 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. Bre tt g Po rte r, Se n io r
Pro gram m e r, Art & Lo gic
I have been reading your book for a week or two and compared 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. Ram a Kris h n a Bh u p ath i, So ftw are
En gin e e r, TCSI Co rp o ratio n , San Jo 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. Gran t Saye r, Java Co m p o n e n ts
Gro u p Le ad e r, Ce e d ata Sys te m s Pty Ltd , Au s tralia
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. Jo h n Ro o t, W e b D e ve lo p e r,
D e p artm e n t o f So cial Se cu rity, Lo n d o n
I’ve *just* started Thinking in Java. I expect it to be very good because I
really liked Thinking in C++ (which I read as an experienced C++
programmer, trying to stay ahead of the curve). I’m somewhat 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 ctSp ace , In c.
I think it’s a great book. I learned all I know about J ava from this book.
Thank you for m aking it available for free over the Internet. If you
wouldn’t have I’d know nothing about J ava at all. But the best thing is
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, Be 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
opportunities in life. Now, in pursuit of m ore knowledge and when I
wanted to learn J ava, I bumped into Thinking in Java—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 an d Ku m ar S., So ftw are 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. Pe te r
Ro bin s o n , U n ive rs ity o f Cam brid ge Co m p u te r Labo rato ry
It’s by far the best m aterial I have come across to help me learn J ava and I
just want you to know how lucky I feel to have found it. THANKS! Ch u ck
Pe te rs o n , Pro d u ct Le ad e r, In te rn e t Pro d u ct Lin e , IVIS
In te rn atio n al
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. Je 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
Java is by far the best and clearest. Mich ae l Van W aas , Ph .D .,
Pre s id e n t, TMR As s o ciate s
I just want to say thanks for Thinking in Java. What a wonderful book
you’ve m ade here! Not to m ention downloadable for free! As a student I
find your books invaluable (I have a copy of C++ Inside Out, another great
book about C++), because they not only teach m e the how-to, but also the
whys, which are of course very im portant in building a strong foundation
in languages such as C++ or J ava. I have quite a lot of friends here who
love program m ing just as I do, and I’ve told them about your books. They
think it’s great! Thanks again! By the way, I’m Indonesian and I live in
J ava. Ray Fre d e rick D jajad in ata, Stu d e n t at Tris akti U n ive rs ity,
Jakarta
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 doing. Sh an e Le Bo 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, Can ad 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. Thanks for all of your help.
D an Cas 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 Java. Even before I finished reading 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-employed, so I’d like to
think that I have seen enough (not “have seen it all,” mind you, but
enough). However, these books cause my girlfriend to call me 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 no other com puter book I have touched or bought so far. Excellent
writing style, very nice introduction of every new topic, and lots of
wisdom in the books. Well done. Sim o n Go lan d ,
s im o n s e z@s m artt.co m , Sim o n Says Co n s u ltin g, In c.
I m ust say that your Thinking in Java 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 rlag,
Be rte ls m an n AG, Ge rm an y
Thank you for writing two great books (Thinking in C++, Thinking in
Java). You have helped m e im m ensely in m y progression to object
oriented program m ing. D o n ald Law s o n , D CL En te rp ris e s
Thank you for taking the tim e to write a really helpful book on J ava. If
teaching m akes you understand som ething, by now you m ust be pretty
pleased with yourself. D o m in ic Tu rn e r, GEAC Su p p o rt
It’s the best J ava book I have ever read—and I read som e. Je an -Yve s
MEN GAN T, Ch ie f So ftw are Arch ite ct N AT-SYSTEM, Paris ,
Fran ce
Thinking in Java gives the best coverage and explanation. Very easy to
read, and I mean the code fragments as well. Ro n Ch an , Ph .D ., Exp e rt
Ch o ice , In c., Pitts bu rgh PA
Your book is great. I have read lots of program m ing books and your book
still adds insights to program m ing in m y m ind. N in gjian W an g,
In fo rm atio n Sys te m En gin e e r, Th e Van gu ard Gro u p
Thinking in Java is an excellent and readable book. I recommend it to all
m y students. D r. Pau l Go rm an , D e p artm e n t o f Co m p u te r Scie n ce ,
U n ive rs ity o f Otago , D u n e d in , N e w Ze alan d
You make 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. Jo s e Su rio l, Scylax Co rp o ratio n
Thanks for the opportunity of watching this book grow into a m asterpiece!
IT IS THE BEST book on the subject that I’ve read or browsed. Je ff
Lap ch in s ky, Pro gram m e r, N e t Re s u lts Te ch n o lo gie s
Your book is concise, accessible and a joy to read. Ke ith Ritch ie , Ja va
Re s e arch & D e ve lo p m e n t Te am , KL Gro u p In c.
It truly is the best book I’ve read on J ava! D an ie l En g
The best book I have seen on J ava! Rich H o ffarth , Se n io r Arch ite ct,
W e s t Gro u p
Thank you for a wonderful book. I’m having a lot of fun going through the
chapters. Fre d Trim ble , Actiu m Co rp o ratio 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. Raje s h Rau , So ftw are Co n s u ltan t
Thinking in Java rocks the free world! Miko O’Su llivan , Pre s id e n t,
Id o cs In c.
Abo u t Th in k in g in C+ + :
Be s t Bo o k! W in n e r o f th e
19 9 5 So ftw are D e ve lo p m e n t Magazin e Jo lt Aw ard !
“This book is a trem endous achievem ent. You owe it to yourself to
have a copy on your shelf. The chapter on iostream s is the m ost
com prehensive and understandable treatm ent of that subject I’ve seen
to date.”
Al Ste ve n s
Co n tribu tin g Ed ito r, D o ct o r D o b b s Jo u r n a l
“Eckel’s book is the only one to so clearly explain how to rethink
program construction for object orientation. That the book is also an
excellent tutorial on the ins and outs of C++ is an added bonus.”
An d re w Bin s to ck
Ed ito r, U n ix R e v ie w
“Bruce continues to am aze m e with his insight into C++, and Thinking
in C++ is his best collection of ideas yet. If you want clear answers to
difficult questions about C++, buy this outstanding book.”
Gary En ts m in ge r
Au th o r, Th e Ta o o f Ob je ct s
“Thinking in C++ patiently and m ethodically explores the issues of
when and how to use inlines, references, operator overloading,
inheritance, and dynam ic objects, as well as advanced topics such as
the proper use of tem plates, exceptions and m ultiple inheritance. The
entire effort is woven in a fabric that includes Eckel’s own philosophy
of object and program design. A m ust for every C++ developer’s
bookshelf, Thinking in C++ is the one C++ book you m ust have if
you’re doing serious developm ent with C++.”
Rich ard H ale Sh aw
Co n tribu tin g Ed ito r, PC Magazin e
Thinking
in
J ava
Second Edition
Bruce Eckel
President, MindView, Inc.
Prentice Hall
Upper Saddle River, New J ersey 0 7458
www.phptr.com
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 Supervision: Nicholas Radhuber
Acquisitions Editor: Paul Petralia
Manufacturing Manager: Maura Goldstaub
Marketing Manager: Bryan Gam brel
Cover Design: Daniel Will-Harris
Interior Design: Daniel Will-Harris, www.will-harris.com
© 20 0 0 by Bruce Eckel, President, MindView, Inc.
Published by Prentice Hall PTR
Prentice-Hall, Inc.
Upper Saddle River, NJ 0 7458
The inform ation in this book is distributed on an “as is” basis, without warranty. While every precaution
has been taken in the preparation of this book, neither the author nor the publisher shall have any liability
to any person or entitle with respect to any liability, loss or damage caused or alleged to be caused directly
or indirectly by instructions contained in this book or by the computer software or hardware products
described herein.
All rights reserved. No part of this book m ay be reproduced, in any form or by any m eans, without
perm ission in writing from the publisher.
Prentice-Hall books are widely used by corporations and governm ent agencies for training, m arketing, and
resale. The publisher offers discounts on this book when ordered in bulk quantities. For m ore inform ation,
contact the Corporate Sales Departm ent at 80 0 -382-3419, fax: 20 1-236-7141, em ail:
[email protected] or write: Corporate Sales Departm ent, Prentice Hall PTR, One Lake Street,
Upper Saddle River, New J ersey 0 7458.
J ava is a registered tradem ark of Sun Microsystem s, Inc. Windows 95 and Windows NT are tradem arks of
Microsoft Corporation. All other product nam es and com pany nam es m entioned herein are the property of
their respective owners.
Printed in the United States of Am erica
10 9 8 7 6 5 4 3 2 1
ISBN 0 -13-0 27363-5
Prentice-Hall International (UK) Limited, London
Prentice-Hall of Australia Pty. Lim ited, Sy dney
Prentice-Hall Canada, Inc., Toronto
Prentice-Hall Hispanoam ericana, S.A., Mexico
Prentice-Hall of India Private Lim ited, New Delhi
Prentice-Hall of J apan, Inc., Toky o
Pearson Education Asia Ltd., Singapore
Editora Prentice-Hall do Brasil, Ltda., Rio de Janeiro
Che ck w w w .Br uce Eck e l.com
for in- dept h det ails
and t he dat e and locat ion
of t he next
H a n ds- On Ja va Se m in a r
• Based on this book
• Taught by Bruce Eckel
• Personal attention from Bruce Eckel
and his sem inar assistants
• Includes in-class program m ing exercises
• Interm ediate/ Advanced sem inars also offered
• Hundreds have already enjoyed this sem inar—
see the Web site for their testim onials
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 like com ing t o t he sem inar!
Available at www.BruceEckel.com
! The Hands-On Java Sem inar captured on a Multim edia CD!
! Overhead slides and synchronized audio voice narration for all
the lectures. J ust play it to see and hear the lectures!
! Created and narrated by Bruce Eckel.
! Based on the m aterial in this book.
!
Dem o lecture available at w w w .BruceEckel.com
Dedication
To the person who, even now,
is creating the next great computer language
Overview
Preface
1
Introduction
9
1: Introduction to Objects
29
2: Everything is an Object
10 1
3: Controlling Program Flow
133
4: Initialization & Cleanup
191
5: Hiding the Im plem entation
243
6: Reusing Classes
271
7: Polym orphism
311
8: Interfaces & Inner Classes
349
9: Holding Your Objects
40 7
10 : Error Handling with Exceptions
531
11: The J ava I/ O System
573
12: Run-tim e Type Identification
659
13: Creating Windows & Applets
689
14: Multiple Threads
825
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 ing Guidelines
10 77
D: Resources
10 91
Index
10 99
What ’s I nside
Preface
1
Preface to the 2 nd edition .... 4
J ava 2 ............................................. 6
The CD ROM....................... 7
Introduction
9
Prerequisites ....................... 9
Learning J ava.................... 10
Goals ..................................11
Online docum entation ...... 12
Chapters ............................ 13
Exercises ........................... 19
Multim edia CD ROM ........ 19
Source code .......................20
Coding standards ......................... 22
im plem entation .................37
Inheritance: reusing
the interface...................... 38
Is-a vs. is-like-a relationships ......42
Interchangeable objects
with polym orphism .......... 44
Abstract base classes
and interfaces ...............................48
Object landscapes and
lifetim es ............................ 49
Collections and iterators .............. 51
The singly rooted hierarchy ......... 53
Collection libraries and
support for easy collection use .....54
The housekeeping dilem m a:
J ava versions..................... 22
Sem inars and
m entoring ......................... 23
Errors ................................ 23
Note on the cover design...24
Acknowledgem ents ........... 25
Exception handling:
dealing with errors ............57
Multithreading ................. 58
Persistence........................ 60
J ava and the Internet ....... 60
Internet contributors ................... 28
What is the Web?......................... 60
1: Introduction
to Objects
who should clean up? ................... 55
Client-side program m ing .............63
29
The progress
of abstraction ....................30
An object has
an interface ....................... 32
The hidden
im plem entation................. 35
Reusing the
Server-side program m ing ............70
A separate arena:
applications .................................. 71
Analysis and design ........... 71
Phase 0 : Make a plan.................... 74
Phase 1: What are we m aking?..... 75
Phase 2: How will we build it? ..... 79
Phase 3: Build the core .................83
Phase 4: Iterate the use cases.......84
Phase 5: Evolution ....................... 85
J ava program ................... 115
Plans pay off................................. 87
Nam e visibility.............................115
Extrem e program m ing .....88
Using other com ponents .............116
Write tests first............................. 88
The s tatic keyword .....................117
Pair program ming........................ 90
Your first J ava program .. 119
Why J ava succeeds............ 91
Com piling and running ...............121
System s are easier to
express and understand ................91
Com m ents and em bedded
docum entation ................ 122
Maximal leverage
Com m ent docum entation .......... 123
with libraries ................................ 92
Syntax ......................................... 124
Error handling ............................. 92
Em bedded HTML....................... 125
Program m ing in the large ............ 92
@s e e : referring to
Strategies for transition ....93
other classes................................ 125
Guidelines .................................... 93
Class docum entation tags........... 126
Managem ent obstacles ................ 95
Variable docum entation tags ..... 127
J ava vs. C++? .................... 97
Sum m ary...........................98
Method docum entation tags ...... 127
2: Everything is
an Object
10 1
You m anipulate objects
with references................ 10 1
You m ust create
all the objects .................. 10 3
Docum entation exam ple ............ 128
Coding style .....................129
Sum m ary .........................130
Exercises..........................130
3: Controlling
Program Flow
133
Using J ava operators....... 133
Where storage lives .................... 10 3
Precedence .................................. 134
Special case: primitive types.......10 5
Assignm ent ................................. 134
Arrays in J ava..............................10 7
Mathem atical operators ............. 137
You never need to
destroy an object ............. 10 7
Auto increm ent
and decrem ent ............................ 139
Scoping....................................... 10 8
Relational operators ....................141
Scope of objects.......................... 10 9
Logical operators ........................ 143
Creating new data
types: class ...................... 110
Bitwise operators ........................ 146
Fields and m ethods ..................... 110
Ternary if-else operator...............151
Methods, arguments,
and return values .............112
The com m a operator .................. 152
The argum ent list ........................ 114
Building a
Shift operators ............................ 147
Strin g operator + ...................... 153
Com m on pitfalls
when using operators ................. 153
Casting operators ........................154
Multidim ensional arrays ............236
J ava has no “sizeof”.....................158
Sum m ary ........................ 239
Exercises......................... 240
Precedence revisited ...................158
A com pendium of operators .......159
Execution control............ 170
true and false...............................170
if-else ........................................... 171
Iteration ......................................172
do-while.......................................173
for ................................................173
break and continue ..................... 175
switch ......................................... 183
Sum m ary......................... 187
Exercises ......................... 188
4: Initialization
& Cleanup
5: Hiding the
Im plem entation
243
p ackage :
the library unit................ 244
Creating unique
package nam es............................247
A custom tool library.................. 251
Using im ports to
change behavior..........................252
Package caveat ............................254
J ava access specifiers ......255
“Friendly”.................................... 255
191
Guaranteed initialization
with the constructor .........191
Method overloading........ 194
Distinguishing
overloaded m ethods....................196
Overloading with prim itives .......197
Overloading 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 alize ( ) for?.............20 8
You must perform cleanup ........ 20 9
The death condition ....................214
How a garbage
collector works ............................215
Mem ber initialization ..... 219
Specifying initialization ..............221
Constructor initialization........... 223
Array initialization .......... 231
pu blic: interface access .............256
p rivate :
you can’t touch that!...................258
p ro te cte d : “sort of friendly”.... 260
Interface and
im plem entation ...............261
Class access .................... 263
Sum m ary .........................267
Exercises......................... 268
6: Reusing Classes
271
Composition syntax......... 271
Inheritance syntax...........275
Initializing the base class ...........278
Com bining com position
and inheritance ...............281
Guaranteeing
proper cleanup............................283
Nam e hiding .............................. 286
Choosing com position
vs. inheritance ................ 288
protected ........................ 290
Incremental
developm ent ................... 291
Upcasting ........................ 291
Why “upcasting”?....................... 293
The fin al keyword ..........294
Final data ................................... 294
Final m ethods ............................ 299
Final classes ............................... 30 1
Final caution .............................. 30 2
Initialization and
class loading....................30 4
8: Interfaces &
Inner Classes
349
Interfaces........................ 349
“Multiple inheritance”
in J ava.........................................354
Extending an interface
with inheritance..........................358
Grouping constants ....................359
Initialization
with inheritance ......................... 30 4
Sum m ary.........................30 6
Exercises .........................30 7
7: Polym orphism
Sum m ary ........................ 346
Exercises......................... 346
311
Upcasting revisited ..........311
Initializing fields
in interfaces ................................ 361
Nesting interfaces .......................362
Inner classes ................... 365
Inner classes and upcasting ...... 368
Inner classes in
Forgetting the object type ...........313
m ethods and scopes ...................370
The twist.......................... 315
Anonym ous inner classes ........... 373
Method-call binding ...................315
The link to the outer class ..........376
Producing the right behavior ......316
s tatic inner classes ....................379
Extensibility ............................... 320
Referring to the
Overriding vs.
overloading .....................324
Abstract classes
and m ethods ................... 325
Constructors and
polymorphism .................330
outer class object ........................ 381
Reaching outward from
a m ultiply-nested class ...............383
Inheriting from inner classes .... 384
Can inner classes
be overridden? ............................385
Order of constructor calls .......... 330
Inner class identifiers .................387
Inheritance and fin alize ( ) ...... 333
Why inner classes? .................... 388
Behavior of polym orphic
Inner classes &
m ethods inside constructors..... 337
control fram eworks ....................394
Designing with
inheritance ......................339
Sum m ary ........................ 40 2
Exercises......................... 40 3
Pure inheritance
vs. extension ................................341
Downcasting and run-time
type identification ...................... 343
9: Holding
Your Objects
40 7
Arrays ............................. 40 7
Arrays are first-class objects ..... 40 9
Returning an array......................413
Choosing between Lis ts .............50 2
The Arrays class ........................415
Choosing between Se ts ..............50 6
Filling an array........................... 428
Choosing between Map s........... 50 8
Copying an array........................ 429
Sorting and
searching Lis ts................ 511
Utilities ............................ 512
Com paring arrays ...................... 430
Array elem ent com parisons ........431
Sorting an array ......................... 435
Making a Co lle ctio n
Searching a sorted array ............ 437
or Map unm odifiable................. 513
Array summ ary .......................... 439
Synchronizing a
Introduction to
containers .......................439
Printing containers .....................441
Filling containers ....................... 442
Co lle ctio n or Map ................... 514
Unsupported
operations........................ 516
J ava 1.0 / 1.1 containers .... 519
Container disadvantage:
unknown type .................450
Vector & Enum eration ............... 519
Som etim es it works anyway....... 452
Stack ........................................... 521
Making a type-conscious
ArrayLis t.................................. 454
Iterators ..........................456
Container taxonom y .......460
Co lle ctio n
functionality....................463
Lis t functionality............ 467
Making a stack
from a Lin ke d Lis t .....................471
Making a queue
from a Lin ke d Lis t .................... 472
Se t functionality ............. 473
So rte d Se t ................................. 476
Map functionality........... 476
So rte dMap ............................... 482
Hashing and hash codes ............ 482
Overriding h as h Co d e ( ) .......... 492
Holding references..........495
The W e akH as h Map ............... 498
Iterators revisited........... 50 0
Choosing an
im plem entation............... 50 1
Hashtable.................................... 521
BitSet ..........................................522
Sum m ary ........................ 524
Exercises..........................525
10 : Error Handling
with Exceptions
531
Basic exceptions ............. 532
Exception argum ents..................533
Catching an exception .... 534
The try block .............................. 535
Exception handlers..................... 535
Creating your own
exceptions........................537
The exception
specification ................... 542
Catching any exception ..............543
Rethrowing an exception ........... 545
Standard J ava
exceptions....................... 549
The special case of
Ru n tim e Exce ptio n .................550
Perform ing cleanup
with finally ...................... 552
What’s fin ally for? .................... 554
Reading from standard input .... 60 3
Changing Sys te m .o u t
Pitfall: the lost exception ............557
to a Prin tW rite r...................... 60 4
Exception restrictions .....558
Constructors.................... 562
Exception m atching ........566
Redirecting standard I/ O .......... 60 4
Compression................... 60 6
Exception guidelines .................. 568
with GZIP....................................60 7
Sum m ary.........................568
Exercises .........................569
Multifile storage with Zip .......... 60 8
11: The J ava
I/ O System
Sim ple com pression
J ava ARchives (J ARs) .................611
Object serialization ..........613
573
The File class.................. 574
A directory lister ........................ 574
Checking for and
creating directories .................... 578
Input and output ............. 581
Types of In p u tStre am ..............581
Types of Ou tp u tStre am .......... 583
Adding attributes
and useful interfaces .......585
Reading from an In p u tStre am
with Filte rIn p u tStre am ......... 586
Writing to an Ou tp u tStre am
Finding the class......................... 618
Controlling serialization ............. 619
Using persistence ...................... 630
Tokenizing input ............ 639
Stre am To ke n ize r ...................639
Strin gTo ke n ize r .....................642
Checking capitalization style......645
Sum m ary .........................655
Exercises......................... 656
12: Run-tim e Type
Identification
659
The need for RTTI .......... 659
The Clas s object.........................662
with Filte rOu tp u tStre am ...... 587
Checking before a cast ................665
Re ade rs & W rite rs.......589
RTTI syntax .....................674
Reflection: run-tim e
class inform ation .............677
Sources and sinks of data........... 590
Modifying stream behavior.........591
Unchanged Classes .................... 592
A class m ethod extractor ............679
Off by itself:
Random AccessFile.......... 593
Typical uses of
I/ O stream s .....................594
Sum m ary ........................ 685
Exercises......................... 686
Input streams ............................. 597
Output stream s .......................... 599
A bug?......................................... 60 1
Piped stream s............................. 60 2
Standard I/ O ...................60 2
13: Creating Windows
& Applets
689
The basic applet.............. 692
Applet restrictions ......................692
Applet advantages ......................693
Application fram eworks .............694
Running applets inside
a Web browser............................ 695
Pop-up m enus ............................766
Using Appletview er ................... 698
Drawing ......................................768
Testing applets ........................... 698
Dialog Boxes ............................... 771
Running applets from
the com m and line ...........70 0
File dialogs.................................. 776
A display fram ework .................. 70 2
Swing com ponents ..................... 779
HTML on
Using the Windows Explorer ..... 70 5
Sliders and progress bars .......... 780
Making a button ..............70 6
Capturing an event .......... 70 7
Text areas ......................... 711
Controlling layout ........... 712
Trees ........................................... 781
BorderLayout ..............................713
GridBagLayout ............................716
Packaging an applet
into a J AR file ..................793
Program m ing
techniques .......................794
Absolute positioning ...................716
Binding events dynam ically .......794
BoxLayout ................................... 717
Separating business
The best approach? .....................721
logic from UI logic .....................796
FlowLayout..................................714
GridLayout .................................. 715
Tables..........................................784
Selecting Look & Feel ................. 787
The clipboard ..............................790
The Swing event model ... 722
A canonical form ........................799
Event and listener types............. 723
Visual program m ing
and Beans ....................... 80 0
Tracking multiple events ........... 730
A catalog of Swing
components..................... 734
What is a Bean? ..........................80 1
Buttons ....................................... 734
with the In tro s p e cto r ............. 80 4
Icons ........................................... 738
A m ore sophisticated Bean ......... 811
Tool tips...................................... 740
Packaging a Bean ........................ 816
Text fields ................................... 740
More com plex Bean support ......818
Borders ....................................... 743
More to Beans............................. 819
J ScrollPanes ............................... 744
Sum m ary .........................819
Exercises......................... 820
A m ini-editor .............................. 747
Check boxes................................ 748
Radio buttons............................. 750
Com bo boxes
(drop-down lists) ........................ 751
List boxes ................................... 753
Tabbed panes ..............................755
Message boxes............................ 756
Menus......................................... 759
Extracting Be an In fo
14: Multiple Threads
825
Responsive
user interfaces ................ 826
Inheriting from Th re ad ........... 828
Threading for a
responsive interface.................... 831
Com bining the thread
with the m ain class .................... 834
A m ore sophisticated
Making many threads ................ 836
exam ple.......................................939
Daem on threads.........................840
Servlets ........................... 948
Sharing
lim ited resources.............842
The basic servlet .........................949
Servlets and m ultithreading.......954
Im properly accessing
Handling sessions
resources .................................... 842
with servlets ................................ 955
How J ava shares resources ........848
Running the
J avaBeans revisited ................... 854
servlet exam ples ........................ 960
Blocking ..........................859
J ava Server Pages ........... 960
Becom ing blocked ......................860
Im plicit objects ...........................962
Deadlock..................................... 872
J SP directives .............................963
Priorities ......................... 877
J SP scripting elem ents ...............964
Reading and
Extracting fields and values .......966
setting priorities ......................... 878
J SP page
Thread groups ............................ 882
attributes and scope .................. 968
Ru n n able revisited ....... 891
Too m any threads ...................... 894
Sum m ary.........................899
Exercises ......................... 90 1
15: Distributed
Com puting
Manipulating
sessions in J SP............................969
Creating and
m odifying cookies....................... 971
J SP summ ary..............................972
90 3
Network programm ing ...90 4
Identifying a m achine ................ 90 5
Sockets ....................................... 90 9
Serving multiple clients ..............917
Datagram s .................................. 923
Using URLs from
within an applet ......................... 923
More to networking ................... 926
J ava Database
Connectivity (J DBC) ....... 927
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
RMI (Remote Method
Invocation) ......................973
Rem ote interfaces.......................973
Im plem enting the
rem ote interface .........................974
Creating stubs and skeletons......978
Using the rem ote object .............979
CORBA ........................... 980
CORBA fundam entals ................ 981
An exam ple ................................ 983
J ava Applets and CORBA.......... 989
CORBA vs. RMI ......................... 989
Enterprise J avaBeans..... 990
J avaBeans vs. EJ Bs .................... 991
The EJ B specification .................992
EJ B com ponents.........................993
The pieces of an
EJ B com ponent.......................... 994
further down a hierarchy..........10 34
EJ B operation ............................ 995
Why this strange design? ......... 10 35
Types of EJ Bs ............................. 996
Controlling
cloneability ....................10 36
Developing an EJ B..................... 997
EJ B summ ary........................... 10 0 3
The copy constructor ................10 42
J ini: distributed
services..........................10 0 3
Read-only classes ..........10 47
Creating read-only classes........10 49
J ini in context .......................... 10 0 3
The drawback
What is J ini? ............................ 10 0 4
to im mutability.........................10 50
How J ini works ........................ 10 0 5
Im m utable Strin gs .................. 10 52
The discovery process .............. 10 0 6
The Strin g and
The join process ....................... 10 0 6
Strin gBu ffe r classes .............. 10 56
The lookup process .................. 10 0 7
Separation of interface
and im plem entation................. 10 0 8
Abstracting
distributed system s .................. 10 0 9
Sum m ary....................... 10 10
Exercises ....................... 10 10
A: Passing &
Returning Objects
Strin gs are special...................10 60
Sum m ary ...................... 10 60
Exercises........................10 62
B: The J ava Native
Interface (J NI)
10 65
Calling a
native m ethod................10 66
The header file
10 13
Passing
references around ......... 10 14
generator: javah ........................ 10 67
Nam e m angling and
function signatures ...................10 68
Aliasing......................................10 14
Im plem enting your DLL...........10 68
Making local copies........10 17
Accessing J NI functions:
the JN IEn v argument ..10 69
Pass by value .............................10 18
Cloning objects..........................10 18
Adding cloneability
to a class ................................... 10 20
Successful cloning.................... 10 22
The effect of
Obje ct.clo n e ( ) ...................... 10 25
Cloning a com posed object .......10 27
A deep copy
with ArrayLis t........................ 10 30
Deep copy via serialization ...... 10 32
Adding cloneability
Accessing J ava Strings ............. 10 71
Passing and
using J ava objects.......... 10 71
J NI and
J ava exceptions .............10 74
J NI and threading ......... 10 75
Using a preexisting
code base ....................... 10 75
Additional
inform ation ...................10 76
C: J ava Program m ing
Guidelines
Books ............................. 10 91
10 77
Analysis & design......................10 93
Design ........................... 10 77
Im plem entation ............10 84
Python ....................................... 10 95
D: Resources
10 91
Software ........................ 10 91
My own list of books.................10 96
Index
10 99
Preface
I suggested to m y brother Todd, who is m aking the leap
from hardware into program m ing, that the next big
revolution will be in genetic engineering.
We’ll have m icrobes designed 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:
getting lost in the technology (which is of course easy to do in science
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 point. 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 one thing, people started sending in corrections. This has been an
am azing process, because folks have looked into every nook and cranny
and caught both technical and grammatical 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
collection of errors I’m sure I never would have found. I feel like this has
1
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 everyone to print it out in a nice looking
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. However, 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 interest warrants it will the book be put on paper. Currently, 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
2 nd Edition, Release 11
To be published by Prentice-Hall m id-J une, 20 0 0
Bruce Eckel, President,
MindView, Inc.
Planet PDF brings you the Portable Docum ent
Form at (PDF) version of Thinking in J ava (2nd
Edition). Planet PDF is the prem ier PDF-related
site on the web. There is news, software, white
papers, interviews, product reviews, Web links,
code sam ples, a forum , and regular articles by
m any of the m ost prom inent and respected PDF
experts in the world. Visit our sites for m ore detail:
http:/ / www.planetpdf.com /
http:/ / www.codecuts.com /
http:/ / www.pdfforum .com /
http:/ / www.pdfstore.com /
Thinking
in
J ava
Second Edition
Bruce Eckel
President, MindView, Inc.
Com m ent s from readers:
Much 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
and intelligent, not dum bed-down, explanations ... In contrast to m any
other J ava books I found it to be unusually m ature, consistent,
intellectually honest, well-written and precise. IMHO, an ideal book for
studying J ava. An ato ly Vo ro be y, Te ch n io n U n ive rs ity, H aifa,
Is rae l
One of the absolutely best programming tutorials I’ve seen for any
language. Jo akim Zie gle r, FIX s ys o p
Thank you for your wonderful, wonderful book on J ava. D r. Gavin
Pillay, Re gis trar, Kin g Ed w ard VIII H o s p ital, So u th Africa
Thank you again for your awesom e book. I was really floundering (being a
non-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. Hopefully I will be able to
attend your sem inar in the not-too-distant future. Ran d all R. H aw le y,
Au to m atio n Te ch n ician , Eli Lilly & Co .
The best computer book writing I have seen. To m H o llan 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. Ravin d ra Pai, Oracle
Co rp o ratio n , SU N OS p ro d u ct lin e
This is the best book on J ava that I have ever found! You have done a
great job. Your depth is am azing. I will be purchasing the book when it is
published. I have been learning J ava since October 96. I have read a few
books, and consider yours a “MUST READ.” These past few m onths we
have been focused on a product written entirely in J ava. Your book has
helped solidify topics I was shaky on and has expanded m y knowledge
base. I have even used som e of your explanations as inform ation in
interviewing contractors to help our team . I have found how m uch J ava
knowledge they have by asking them about things I have learned from
reading your book (e.g., the difference between arrays and Vectors). Your
book is great! Ste ve W ilkin s o n , Se n io r Staff Sp e cialis t, MCI
Te le co m m u n icatio n s
Great book. Best book on J ava I have seen so far. Je ff Sin clair,
So ftw are En gin e e r, Ke s tral Co m p u tin g
Thank you for Thinking in Java. It’s tim e som eone went beyond m ere
language description to a thoughtful, penetrating analytic tutorial that
doesn’t kowtow to The Manufacturers. I’ve read almost 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 ard Bro o ks ,
Java Co n s u ltan t, Su n Pro fe s s io n al Se rvice s , D allas
Other books cover the WHAT of J ava (describing the syntax and the
libraries) or the HOW of J ava (practical program m ing exam ples).
Thinking in Java is the only book I know that explains the WHY 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 Java is definitely the thinking person’s choice in a J ava book.
Ro be rt S. Ste 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 want to com m end you for your work on Thinking in Java. It is
people like you that dignify the future of the Internet and I just want to
thank you for your effort. It is very m uch appreciated. Patrick Barre ll,
N e tw o rk Office r Mam co , QAF Mfg. In c.
Most of the J ava books out there are fine for a start, and most just have
beginning stuff and 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 Java.
Ge o rge Lafram 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 Modern
Problem s) “I like it!” Very inform ative and explanatory, without reading
like a dry textbook. You cover the m ost im portant yet the least covered
concepts of J ava developm ent: the whys. Se an Brad 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
documentation. And you don’t waste the reader’s time with the basic facts
a program m er already knows. Kai En ge rt, In n o vative So ftw are ,
Ge rm an 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
finding that you’ve retained the sam e high level of writing. Thank you!
Pe te r R. N e u w ald
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 Java as the basis for a part of each m onthly
SIG m eeting, in which we review and discuss each chapter in succession.
Mark Erte s
I really appreciate your work and your book is good. I recom m end 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
Fran ce , H e ad o f Scie n tific Co m p u tin g an d In d u s trial Tran fe rt
OK, I’ve only read about 40 pages of Thinking in Java, 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, myself, 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 most computer books—even ones that
cam e with glowing recommendations. I feel a whole lot better now.
Gle n n Be cke r, Ed u catio n al Th e atre As s o ciatio n
Thank you for m aking your wonderful book available. I have found it
im m ensely useful in finally understanding what I experienced as
confusing in J ava and C++. Reading your book has been very satisfying.
Fe lix Bizao u i, Tw in Oaks In d u s trie s , Lo u is a, Va.
I m ust congratulate you on an excellent book. I decided to have a look at
Thinking in Java based on my experience with Thinking in C++, and I
was not disappointed. Jaco van d e r Me rw e , So ftw are Sp e cialis t,
D ataFu s io n Sys te m s Ltd , Ste lle n bo s ch , So u th Africa
This has to be one of the best J ava books I’ve seen. E.F. Pritch ard ,
Se n io r So ftw are En gin e e r, Cam brid ge An im atio n Sys 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. Bre tt g Po rte r, Se n io r
Pro gram m e r, Art & Lo gic
I have been reading your book for a week or two and compared 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. Ram a Kris h n a Bh u p ath i, So ftw are
En gin e e r, TCSI Co rp o ratio n , San Jo 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. Gran t Saye r, Java Co m p o n e n ts
Gro u p Le ad e r, Ce e d ata Sys te m s Pty Ltd , Au s tralia
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. Jo h n Ro o t, W e b D e ve lo p e r,
D e p artm e n t o f So cial Se cu rity, Lo n d o n
I’ve *just* started Thinking in Java. I expect it to be very good because I
really liked Thinking in C++ (which I read as an experienced C++
programmer, trying to stay ahead of the curve). I’m somewhat 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 ctSp ace , In c.
I think it’s a great book. I learned all I know about J ava from this book.
Thank you for m aking it available for free over the Internet. If you
wouldn’t have I’d know nothing about J ava at all. But the best thing is
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, Be 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
opportunities in life. Now, in pursuit of m ore knowledge and when I
wanted to learn J ava, I bumped into Thinking in Java—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 an d Ku m ar S., So ftw are 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. Pe te r
Ro bin s o n , U n ive rs ity o f Cam brid ge Co m p u te r Labo rato ry
It’s by far the best m aterial I have come across to help me learn J ava and I
just want you to know how lucky I feel to have found it. THANKS! Ch u ck
Pe te rs o n , Pro d u ct Le ad e r, In te rn e t Pro d u ct Lin e , IVIS
In te rn atio n al
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. Je 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
Java is by far the best and clearest. Mich ae l Van W aas , Ph .D .,
Pre s id e n t, TMR As s o ciate s
I just want to say thanks for Thinking in Java. What a wonderful book
you’ve m ade here! Not to m ention downloadable for free! As a student I
find your books invaluable (I have a copy of C++ Inside Out, another great
book about C++), because they not only teach m e the how-to, but also the
whys, which are of course very im portant in building a strong foundation
in languages such as C++ or J ava. I have quite a lot of friends here who
love program m ing just as I do, and I’ve told them about your books. They
think it’s great! Thanks again! By the way, I’m Indonesian and I live in
J ava. Ray Fre d e rick D jajad in ata, Stu d e n t at Tris akti U n ive rs ity,
Jakarta
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 doing. Sh an e Le Bo 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, Can ad 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. Thanks for all of your help.
D an Cas 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 Java. Even before I finished reading 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-employed, so I’d like to
think that I have seen enough (not “have seen it all,” mind you, but
enough). However, these books cause my girlfriend to call me 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 no other com puter book I have touched or bought so far. Excellent
writing style, very nice introduction of every new topic, and lots of
wisdom in the books. Well done. Sim o n Go lan d ,
s im o n s e z@s m artt.co m , Sim o n Says Co n s u ltin g, In c.
I m ust say that your Thinking in Java 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 rlag,
Be rte ls m an n AG, Ge rm an y
Thank you for writing two great books (Thinking in C++, Thinking in
Java). You have helped m e im m ensely in m y progression to object
oriented program m ing. D o n ald Law s o n , D CL En te rp ris e s
Thank you for taking the tim e to write a really helpful book on J ava. If
teaching m akes you understand som ething, by now you m ust be pretty
pleased with yourself. D o m in ic Tu rn e r, GEAC Su p p o rt
It’s the best J ava book I have ever read—and I read som e. Je an -Yve s
MEN GAN T, Ch ie f So ftw are Arch ite ct N AT-SYSTEM, Paris ,
Fran ce
Thinking in Java gives the best coverage and explanation. Very easy to
read, and I mean the code fragments as well. Ro n Ch an , Ph .D ., Exp e rt
Ch o ice , In c., Pitts bu rgh PA
Your book is great. I have read lots of program m ing books and your book
still adds insights to program m ing in m y m ind. N in gjian W an g,
In fo rm atio n Sys te m En gin e e r, Th e Van gu ard Gro u p
Thinking in Java is an excellent and readable book. I recommend it to all
m y students. D r. Pau l Go rm an , D e p artm e n t o f Co m p u te r Scie n ce ,
U n ive rs ity o f Otago , D u n e d in , N e w Ze alan d
You make 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. Jo s e Su rio l, Scylax Co rp o ratio n
Thanks for the opportunity of watching this book grow into a m asterpiece!
IT IS THE BEST book on the subject that I’ve read or browsed. Je ff
Lap ch in s ky, Pro gram m e r, N e t Re s u lts Te ch n o lo gie s
Your book is concise, accessible and a joy to read. Ke ith Ritch ie , Ja va
Re s e arch & D e ve lo p m e n t Te am , KL Gro u p In c.
It truly is the best book I’ve read on J ava! D an ie l En g
The best book I have seen on J ava! Rich H o ffarth , Se n io r Arch ite ct,
W e s t Gro u p
Thank you for a wonderful book. I’m having a lot of fun going through the
chapters. Fre d Trim ble , Actiu m Co rp o ratio 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. Raje s h Rau , So ftw are Co n s u ltan t
Thinking in Java rocks the free world! Miko O’Su llivan , Pre s id e n t,
Id o cs In c.
Abo u t Th in k in g in C+ + :
Be s t Bo o k! W in n e r o f th e
19 9 5 So ftw are D e ve lo p m e n t Magazin e Jo lt Aw ard !
“This book is a trem endous achievem ent. You owe it to yourself to
have a copy on your shelf. The chapter on iostream s is the m ost
com prehensive and understandable treatm ent of that subject I’ve seen
to date.”
Al Ste ve n s
Co n tribu tin g Ed ito r, D o ct o r D o b b s Jo u r n a l
“Eckel’s book is the only one to so clearly explain how to rethink
program construction for object orientation. That the book is also an
excellent tutorial on the ins and outs of C++ is an added bonus.”
An d re w Bin s to ck
Ed ito r, U n ix R e v ie w
“Bruce continues to am aze m e with his insight into C++, and Thinking
in C++ is his best collection of ideas yet. If you want clear answers to
difficult questions about C++, buy this outstanding book.”
Gary En ts m in ge r
Au th o r, Th e Ta o o f Ob je ct s
“Thinking in C++ patiently and m ethodically explores the issues of
when and how to use inlines, references, operator overloading,
inheritance, and dynam ic objects, as well as advanced topics such as
the proper use of tem plates, exceptions and m ultiple inheritance. The
entire effort is woven in a fabric that includes Eckel’s own philosophy
of object and program design. A m ust for every C++ developer’s
bookshelf, Thinking in C++ is the one C++ book you m ust have if
you’re doing serious developm ent with C++.”
Rich ard H ale Sh aw
Co n tribu tin g Ed ito r, PC Magazin e
Thinking
in
J ava
Second Edition
Bruce Eckel
President, MindView, Inc.
Prentice Hall
Upper Saddle River, New J ersey 0 7458
www.phptr.com
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 Supervision: Nicholas Radhuber
Acquisitions Editor: Paul Petralia
Manufacturing Manager: Maura Goldstaub
Marketing Manager: Bryan Gam brel
Cover Design: Daniel Will-Harris
Interior Design: Daniel Will-Harris, www.will-harris.com
© 20 0 0 by Bruce Eckel, President, MindView, Inc.
Published by Prentice Hall PTR
Prentice-Hall, Inc.
Upper Saddle River, NJ 0 7458
The inform ation in this book is distributed on an “as is” basis, without warranty. While every precaution
has been taken in the preparation of this book, neither the author nor the publisher shall have any liability
to any person or entitle with respect to any liability, loss or damage caused or alleged to be caused directly
or indirectly by instructions contained in this book or by the computer software or hardware products
described herein.
All rights reserved. No part of this book m ay be reproduced, in any form or by any m eans, without
perm ission in writing from the publisher.
Prentice-Hall books are widely used by corporations and governm ent agencies for training, m arketing, and
resale. The publisher offers discounts on this book when ordered in bulk quantities. For m ore inform ation,
contact the Corporate Sales Departm ent at 80 0 -382-3419, fax: 20 1-236-7141, em ail:
[email protected] or write: Corporate Sales Departm ent, Prentice Hall PTR, One Lake Street,
Upper Saddle River, New J ersey 0 7458.
J ava is a registered tradem ark of Sun Microsystem s, Inc. Windows 95 and Windows NT are tradem arks of
Microsoft Corporation. All other product nam es and com pany nam es m entioned herein are the property of
their respective owners.
Printed in the United States of Am erica
10 9 8 7 6 5 4 3 2 1
ISBN 0 -13-0 27363-5
Prentice-Hall International (UK) Limited, London
Prentice-Hall of Australia Pty. Lim ited, Sy dney
Prentice-Hall Canada, Inc., Toronto
Prentice-Hall Hispanoam ericana, S.A., Mexico
Prentice-Hall of India Private Lim ited, New Delhi
Prentice-Hall of J apan, Inc., Toky o
Pearson Education Asia Ltd., Singapore
Editora Prentice-Hall do Brasil, Ltda., Rio de Janeiro
Che ck w w w .Br uce Eck e l.com
for in- dept h det ails
and t he dat e and locat ion
of t he next
H a n ds- On Ja va Se m in a r
• Based on this book
• Taught by Bruce Eckel
• Personal attention from Bruce Eckel
and his sem inar assistants
• Includes in-class program m ing exercises
• Interm ediate/ Advanced sem inars also offered
• Hundreds have already enjoyed this sem inar—
see the Web site for their testim onials
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 like com ing t o t he sem inar!
Available at www.BruceEckel.com
! The Hands-On Java Sem inar captured on a Multim edia CD!
! Overhead slides and synchronized audio voice narration for all
the lectures. J ust play it to see and hear the lectures!
! Created and narrated by Bruce Eckel.
! Based on the m aterial in this book.
!
Dem o lecture available at w w w .BruceEckel.com
Dedication
To the person who, even now,
is creating the next great computer language
Overview
Preface
1
Introduction
9
1: Introduction to Objects
29
2: Everything is an Object
10 1
3: Controlling Program Flow
133
4: Initialization & Cleanup
191
5: Hiding the Im plem entation
243
6: Reusing Classes
271
7: Polym orphism
311
8: Interfaces & Inner Classes
349
9: Holding Your Objects
40 7
10 : Error Handling with Exceptions
531
11: The J ava I/ O System
573
12: Run-tim e Type Identification
659
13: Creating Windows & Applets
689
14: Multiple Threads
825
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 ing Guidelines
10 77
D: Resources
10 91
Index
10 99
What ’s I nside
Preface
1
Preface to the 2 nd edition .... 4
J ava 2 ............................................. 6
The CD ROM....................... 7
Introduction
9
Prerequisites ....................... 9
Learning J ava.................... 10
Goals ..................................11
Online docum entation ...... 12
Chapters ............................ 13
Exercises ........................... 19
Multim edia CD ROM ........ 19
Source code .......................20
Coding standards ......................... 22
im plem entation .................37
Inheritance: reusing
the interface...................... 38
Is-a vs. is-like-a relationships ......42
Interchangeable objects
with polym orphism .......... 44
Abstract base classes
and interfaces ...............................48
Object landscapes and
lifetim es ............................ 49
Collections and iterators .............. 51
The singly rooted hierarchy ......... 53
Collection libraries and
support for easy collection use .....54
The housekeeping dilem m a:
J ava versions..................... 22
Sem inars and
m entoring ......................... 23
Errors ................................ 23
Note on the cover design...24
Acknowledgem ents ........... 25
Exception handling:
dealing with errors ............57
Multithreading ................. 58
Persistence........................ 60
J ava and the Internet ....... 60
Internet contributors ................... 28
What is the Web?......................... 60
1: Introduction
to Objects
who should clean up? ................... 55
Client-side program m ing .............63
29
The progress
of abstraction ....................30
An object has
an interface ....................... 32
The hidden
im plem entation................. 35
Reusing the
Server-side program m ing ............70
A separate arena:
applications .................................. 71
Analysis and design ........... 71
Phase 0 : Make a plan.................... 74
Phase 1: What are we m aking?..... 75
Phase 2: How will we build it? ..... 79
Phase 3: Build the core .................83
Phase 4: Iterate the use cases.......84
Phase 5: Evolution ....................... 85
J ava program ................... 115
Plans pay off................................. 87
Nam e visibility.............................115
Extrem e program m ing .....88
Using other com ponents .............116
Write tests first............................. 88
The s tatic keyword .....................117
Pair program ming........................ 90
Your first J ava program .. 119
Why J ava succeeds............ 91
Com piling and running ...............121
System s are easier to
express and understand ................91
Com m ents and em bedded
docum entation ................ 122
Maximal leverage
Com m ent docum entation .......... 123
with libraries ................................ 92
Syntax ......................................... 124
Error handling ............................. 92
Em bedded HTML....................... 125
Program m ing in the large ............ 92
@s e e : referring to
Strategies for transition ....93
other classes................................ 125
Guidelines .................................... 93
Class docum entation tags........... 126
Managem ent obstacles ................ 95
Variable docum entation tags ..... 127
J ava vs. C++? .................... 97
Sum m ary...........................98
Method docum entation tags ...... 127
2: Everything is
an Object
10 1
You m anipulate objects
with references................ 10 1
You m ust create
all the objects .................. 10 3
Docum entation exam ple ............ 128
Coding style .....................129
Sum m ary .........................130
Exercises..........................130
3: Controlling
Program Flow
133
Using J ava operators....... 133
Where storage lives .................... 10 3
Precedence .................................. 134
Special case: primitive types.......10 5
Assignm ent ................................. 134
Arrays in J ava..............................10 7
Mathem atical operators ............. 137
You never need to
destroy an object ............. 10 7
Auto increm ent
and decrem ent ............................ 139
Scoping....................................... 10 8
Relational operators ....................141
Scope of objects.......................... 10 9
Logical operators ........................ 143
Creating new data
types: class ...................... 110
Bitwise operators ........................ 146
Fields and m ethods ..................... 110
Ternary if-else operator...............151
Methods, arguments,
and return values .............112
The com m a operator .................. 152
The argum ent list ........................ 114
Building a
Shift operators ............................ 147
Strin g operator + ...................... 153
Com m on pitfalls
when using operators ................. 153
Casting operators ........................154
Multidim ensional arrays ............236
J ava has no “sizeof”.....................158
Sum m ary ........................ 239
Exercises......................... 240
Precedence revisited ...................158
A com pendium of operators .......159
Execution control............ 170
true and false...............................170
if-else ........................................... 171
Iteration ......................................172
do-while.......................................173
for ................................................173
break and continue ..................... 175
switch ......................................... 183
Sum m ary......................... 187
Exercises ......................... 188
4: Initialization
& Cleanup
5: Hiding the
Im plem entation
243
p ackage :
the library unit................ 244
Creating unique
package nam es............................247
A custom tool library.................. 251
Using im ports to
change behavior..........................252
Package caveat ............................254
J ava access specifiers ......255
“Friendly”.................................... 255
191
Guaranteed initialization
with the constructor .........191
Method overloading........ 194
Distinguishing
overloaded m ethods....................196
Overloading with prim itives .......197
Overloading 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 alize ( ) for?.............20 8
You must perform cleanup ........ 20 9
The death condition ....................214
How a garbage
collector works ............................215
Mem ber initialization ..... 219
Specifying initialization ..............221
Constructor initialization........... 223
Array initialization .......... 231
pu blic: interface access .............256
p rivate :
you can’t touch that!...................258
p ro te cte d : “sort of friendly”.... 260
Interface and
im plem entation ...............261
Class access .................... 263
Sum m ary .........................267
Exercises......................... 268
6: Reusing Classes
271
Composition syntax......... 271
Inheritance syntax...........275
Initializing the base class ...........278
Com bining com position
and inheritance ...............281
Guaranteeing
proper cleanup............................283
Nam e hiding .............................. 286
Choosing com position
vs. inheritance ................ 288
protected ........................ 290
Incremental
developm ent ................... 291
Upcasting ........................ 291
Why “upcasting”?....................... 293
The fin al keyword ..........294
Final data ................................... 294
Final m ethods ............................ 299
Final classes ............................... 30 1
Final caution .............................. 30 2
Initialization and
class loading....................30 4
8: Interfaces &
Inner Classes
349
Interfaces........................ 349
“Multiple inheritance”
in J ava.........................................354
Extending an interface
with inheritance..........................358
Grouping constants ....................359
Initialization
with inheritance ......................... 30 4
Sum m ary.........................30 6
Exercises .........................30 7
7: Polym orphism
Sum m ary ........................ 346
Exercises......................... 346
311
Upcasting revisited ..........311
Initializing fields
in interfaces ................................ 361
Nesting interfaces .......................362
Inner classes ................... 365
Inner classes and upcasting ...... 368
Inner classes in
Forgetting the object type ...........313
m ethods and scopes ...................370
The twist.......................... 315
Anonym ous inner classes ........... 373
Method-call binding ...................315
The link to the outer class ..........376
Producing the right behavior ......316
s tatic inner classes ....................379
Extensibility ............................... 320
Referring to the
Overriding vs.
overloading .....................324
Abstract classes
and m ethods ................... 325
Constructors and
polymorphism .................330
outer class object ........................ 381
Reaching outward from
a m ultiply-nested class ...............383
Inheriting from inner classes .... 384
Can inner classes
be overridden? ............................385
Order of constructor calls .......... 330
Inner class identifiers .................387
Inheritance and fin alize ( ) ...... 333
Why inner classes? .................... 388
Behavior of polym orphic
Inner classes &
m ethods inside constructors..... 337
control fram eworks ....................394
Designing with
inheritance ......................339
Sum m ary ........................ 40 2
Exercises......................... 40 3
Pure inheritance
vs. extension ................................341
Downcasting and run-time
type identification ...................... 343
9: Holding
Your Objects
40 7
Arrays ............................. 40 7
Arrays are first-class objects ..... 40 9
Returning an array......................413
Choosing between Lis ts .............50 2
The Arrays class ........................415
Choosing between Se ts ..............50 6
Filling an array........................... 428
Choosing between Map s........... 50 8
Copying an array........................ 429
Sorting and
searching Lis ts................ 511
Utilities ............................ 512
Com paring arrays ...................... 430
Array elem ent com parisons ........431
Sorting an array ......................... 435
Making a Co lle ctio n
Searching a sorted array ............ 437
or Map unm odifiable................. 513
Array summ ary .......................... 439
Synchronizing a
Introduction to
containers .......................439
Printing containers .....................441
Filling containers ....................... 442
Co lle ctio n or Map ................... 514
Unsupported
operations........................ 516
J ava 1.0 / 1.1 containers .... 519
Container disadvantage:
unknown type .................450
Vector & Enum eration ............... 519
Som etim es it works anyway....... 452
Stack ........................................... 521
Making a type-conscious
ArrayLis t.................................. 454
Iterators ..........................456
Container taxonom y .......460
Co lle ctio n
functionality....................463
Lis t functionality............ 467
Making a stack
from a Lin ke d Lis t .....................471
Making a queue
from a Lin ke d Lis t .................... 472
Se t functionality ............. 473
So rte d Se t ................................. 476
Map functionality........... 476
So rte dMap ............................... 482
Hashing and hash codes ............ 482
Overriding h as h Co d e ( ) .......... 492
Holding references..........495
The W e akH as h Map ............... 498
Iterators revisited........... 50 0
Choosing an
im plem entation............... 50 1
Hashtable.................................... 521
BitSet ..........................................522
Sum m ary ........................ 524
Exercises..........................525
10 : Error Handling
with Exceptions
531
Basic exceptions ............. 532
Exception argum ents..................533
Catching an exception .... 534
The try block .............................. 535
Exception handlers..................... 535
Creating your own
exceptions........................537
The exception
specification ................... 542
Catching any exception ..............543
Rethrowing an exception ........... 545
Standard J ava
exceptions....................... 549
The special case of
Ru n tim e Exce ptio n .................550
Perform ing cleanup
with finally ...................... 552
What’s fin ally for? .................... 554
Reading from standard input .... 60 3
Changing Sys te m .o u t
Pitfall: the lost exception ............557
to a Prin tW rite r...................... 60 4
Exception restrictions .....558
Constructors.................... 562
Exception m atching ........566
Redirecting standard I/ O .......... 60 4
Compression................... 60 6
Exception guidelines .................. 568
with GZIP....................................60 7
Sum m ary.........................568
Exercises .........................569
Multifile storage with Zip .......... 60 8
11: The J ava
I/ O System
Sim ple com pression
J ava ARchives (J ARs) .................611
Object serialization ..........613
573
The File class.................. 574
A directory lister ........................ 574
Checking for and
creating directories .................... 578
Input and output ............. 581
Types of In p u tStre am ..............581
Types of Ou tp u tStre am .......... 583
Adding attributes
and useful interfaces .......585
Reading from an In p u tStre am
with Filte rIn p u tStre am ......... 586
Writing to an Ou tp u tStre am
Finding the class......................... 618
Controlling serialization ............. 619
Using persistence ...................... 630
Tokenizing input ............ 639
Stre am To ke n ize r ...................639
Strin gTo ke n ize r .....................642
Checking capitalization style......645
Sum m ary .........................655
Exercises......................... 656
12: Run-tim e Type
Identification
659
The need for RTTI .......... 659
The Clas s object.........................662
with Filte rOu tp u tStre am ...... 587
Checking before a cast ................665
Re ade rs & W rite rs.......589
RTTI syntax .....................674
Reflection: run-tim e
class inform ation .............677
Sources and sinks of data........... 590
Modifying stream behavior.........591
Unchanged Classes .................... 592
A class m ethod extractor ............679
Off by itself:
Random AccessFile.......... 593
Typical uses of
I/ O stream s .....................594
Sum m ary ........................ 685
Exercises......................... 686
Input streams ............................. 597
Output stream s .......................... 599
A bug?......................................... 60 1
Piped stream s............................. 60 2
Standard I/ O ...................60 2
13: Creating Windows
& Applets
689
The basic applet.............. 692
Applet restrictions ......................692
Applet advantages ......................693
Application fram eworks .............694
Running applets inside
a Web browser............................ 695
Pop-up m enus ............................766
Using Appletview er ................... 698
Drawing ......................................768
Testing applets ........................... 698
Dialog Boxes ............................... 771
Running applets from
the com m and line ...........70 0
File dialogs.................................. 776
A display fram ework .................. 70 2
Swing com ponents ..................... 779
HTML on
Using the Windows Explorer ..... 70 5
Sliders and progress bars .......... 780
Making a button ..............70 6
Capturing an event .......... 70 7
Text areas ......................... 711
Controlling layout ........... 712
Trees ........................................... 781
BorderLayout ..............................713
GridBagLayout ............................716
Packaging an applet
into a J AR file ..................793
Program m ing
techniques .......................794
Absolute positioning ...................716
Binding events dynam ically .......794
BoxLayout ................................... 717
Separating business
The best approach? .....................721
logic from UI logic .....................796
FlowLayout..................................714
GridLayout .................................. 715
Tables..........................................784
Selecting Look & Feel ................. 787
The clipboard ..............................790
The Swing event model ... 722
A canonical form ........................799
Event and listener types............. 723
Visual program m ing
and Beans ....................... 80 0
Tracking multiple events ........... 730
A catalog of Swing
components..................... 734
What is a Bean? ..........................80 1
Buttons ....................................... 734
with the In tro s p e cto r ............. 80 4
Icons ........................................... 738
A m ore sophisticated Bean ......... 811
Tool tips...................................... 740
Packaging a Bean ........................ 816
Text fields ................................... 740
More com plex Bean support ......818
Borders ....................................... 743
More to Beans............................. 819
J ScrollPanes ............................... 744
Sum m ary .........................819
Exercises......................... 820
A m ini-editor .............................. 747
Check boxes................................ 748
Radio buttons............................. 750
Com bo boxes
(drop-down lists) ........................ 751
List boxes ................................... 753
Tabbed panes ..............................755
Message boxes............................ 756
Menus......................................... 759
Extracting Be an In fo
14: Multiple Threads
825
Responsive
user interfaces ................ 826
Inheriting from Th re ad ........... 828
Threading for a
responsive interface.................... 831
Com bining the thread
with the m ain class .................... 834
A m ore sophisticated
Making many threads ................ 836
exam ple.......................................939
Daem on threads.........................840
Servlets ........................... 948
Sharing
lim ited resources.............842
The basic servlet .........................949
Servlets and m ultithreading.......954
Im properly accessing
Handling sessions
resources .................................... 842
with servlets ................................ 955
How J ava shares resources ........848
Running the
J avaBeans revisited ................... 854
servlet exam ples ........................ 960
Blocking ..........................859
J ava Server Pages ........... 960
Becom ing blocked ......................860
Im plicit objects ...........................962
Deadlock..................................... 872
J SP directives .............................963
Priorities ......................... 877
J SP scripting elem ents ...............964
Reading and
Extracting fields and values .......966
setting priorities ......................... 878
J SP page
Thread groups ............................ 882
attributes and scope .................. 968
Ru n n able revisited ....... 891
Too m any threads ...................... 894
Sum m ary.........................899
Exercises ......................... 90 1
15: Distributed
Com puting
Manipulating
sessions in J SP............................969
Creating and
m odifying cookies....................... 971
J SP summ ary..............................972
90 3
Network programm ing ...90 4
Identifying a m achine ................ 90 5
Sockets ....................................... 90 9
Serving multiple clients ..............917
Datagram s .................................. 923
Using URLs from
within an applet ......................... 923
More to networking ................... 926
J ava Database
Connectivity (J DBC) ....... 927
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
RMI (Remote Method
Invocation) ......................973
Rem ote interfaces.......................973
Im plem enting the
rem ote interface .........................974
Creating stubs and skeletons......978
Using the rem ote object .............979
CORBA ........................... 980
CORBA fundam entals ................ 981
An exam ple ................................ 983
J ava Applets and CORBA.......... 989
CORBA vs. RMI ......................... 989
Enterprise J avaBeans..... 990
J avaBeans vs. EJ Bs .................... 991
The EJ B specification .................992
EJ B com ponents.........................993
The pieces of an
EJ B com ponent.......................... 994
further down a hierarchy..........10 34
EJ B operation ............................ 995
Why this strange design? ......... 10 35
Types of EJ Bs ............................. 996
Controlling
cloneability ....................10 36
Developing an EJ B..................... 997
EJ B summ ary........................... 10 0 3
The copy constructor ................10 42
J ini: distributed
services..........................10 0 3
Read-only classes ..........10 47
Creating read-only classes........10 49
J ini in context .......................... 10 0 3
The drawback
What is J ini? ............................ 10 0 4
to im mutability.........................10 50
How J ini works ........................ 10 0 5
Im m utable Strin gs .................. 10 52
The discovery process .............. 10 0 6
The Strin g and
The join process ....................... 10 0 6
Strin gBu ffe r classes .............. 10 56
The lookup process .................. 10 0 7
Separation of interface
and im plem entation................. 10 0 8
Abstracting
distributed system s .................. 10 0 9
Sum m ary....................... 10 10
Exercises ....................... 10 10
A: Passing &
Returning Objects
Strin gs are special...................10 60
Sum m ary ...................... 10 60
Exercises........................10 62
B: The J ava Native
Interface (J NI)
10 65
Calling a
native m ethod................10 66
The header file
10 13
Passing
references around ......... 10 14
generator: javah ........................ 10 67
Nam e m angling and
function signatures ...................10 68
Aliasing......................................10 14
Im plem enting your DLL...........10 68
Making local copies........10 17
Accessing J NI functions:
the JN IEn v argument ..10 69
Pass by value .............................10 18
Cloning objects..........................10 18
Adding cloneability
to a class ................................... 10 20
Successful cloning.................... 10 22
The effect of
Obje ct.clo n e ( ) ...................... 10 25
Cloning a com posed object .......10 27
A deep copy
with ArrayLis t........................ 10 30
Deep copy via serialization ...... 10 32
Adding cloneability
Accessing J ava Strings ............. 10 71
Passing and
using J ava objects.......... 10 71
J NI and
J ava exceptions .............10 74
J NI and threading ......... 10 75
Using a preexisting
code base ....................... 10 75
Additional
inform ation ...................10 76
C: J ava Program m ing
Guidelines
Books ............................. 10 91
10 77
Analysis & design......................10 93
Design ........................... 10 77
Im plem entation ............10 84
Python ....................................... 10 95
D: Resources
10 91
Software ........................ 10 91
My own list of books.................10 96
Index
10 99
Preface
I suggested to m y brother Todd, who is m aking the leap
from hardware into program m ing, that the next big
revolution will be in genetic engineering.
We’ll have m icrobes designed 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:
getting lost in the technology (which is of course easy to do in science
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 point. 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 one thing, people started sending in corrections. This has been an
am azing process, because folks have looked into every nook and cranny
and caught both technical and grammatical 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
collection of errors I’m sure I never would have found. I feel like this has
1
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 everyone to print it out in a nice looking
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. However, 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 interest warrants it will the book be put on paper. Currently, 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