Thinking
in
Java
Third Edition
Bruce Eckel
Thinking
in
Java
Third Edition
Bruce Eckel
President, MindView, Inc.
PRENTICE HALL
Professional Technical Reference
Upper Saddle River, New Jersey 07458
www.phptr.com
PRENTICE HALL PTR
What's Inside
Preface 1
Preface to the 3
rdedition 4
Java 2, JDK 1.4 6
Introduction 9
Prerequisites 10
Learning Java 10
Goals 11
JDK HTML
documentation 12
Chapters 13
Exercises 20
The CD ROM 20
Source code 22
Coding standards 24Java versions 24
Errors 25
Note on the cover design .... 25
Acknowledgements 26
1: Introduction
to Objects 31
The progress
of abstraction 32
An object
has an interface 34
An object
provides services 37
The hidden
implementation 38
Reusing
the implementation 40
Inheritance: reusing
the interface 41
Is-a vs. is-like-a relationships 45Interchangeable objects
with polymorphism 47
Abstract base classes
and interfaces 51
Object creation,
use & lifetimes 51
Collections and iterators 53 The singly rooted hierarchy 55 Downcasting vs.templates/generics 56 Ensuring proper cleanup 57
Exception handling:
dealing with errors 59
Concurrency 60
Persistence 61
Java and the Internet 61
What is the Web? 61 Client-side programming 64 Server-side programming 71 Applications 72Why Java succeeds 72
Systems are easier to
express and understand 72 Maximal leverage
with libraries 73 Error handling 73 Programming in the large 73
Java vs. C++? 74
Summary 75
2: Everything
is an Object 77
You manipulate objects
You must create
all the objects 79
Where storage lives 79 Special case: primitive types 80 Arrays in Java 82You never need to
destroy an object 83
Scoping 83 Scope of objects 84Creating new
data types: class 85
Fields and methods 85Methods, arguments,
and return values 87
The argument list 89Building a Java program 90
Name visibility go Using other components 91 The static keyword 92Your first Java program 94
Compiling and running 95Comments and embedded
documentation 97
Comment documentation 97 Syntax 98 Embedded HTML 99 Some example tags 100 Documentation example 102
Coding style 103
Summary 104
Exercises 104
3: Controlling
Program Flow 107
Using Java operators 107
Precedence 108 Assignment 108 Mathematical operators ill Auto increment and decrement 115 Relational operators 117 Logical operators 119 Bitwise operators 122 Shift operators 123 Ternary if-else operator 127 The comma operator 128String operator + 128
Common pitfalls when
using operators 129 Casting operators 130 Java has no "sizeof ' 133 Precedence revisited 133 A compendium of operators 134
Execution control 144
true and false 144 if-else 145 return 146 Iteration 147 do-while 148 for 148 break and continue 151 switch 157Summary 162
Exercises 162
4: Initialization
& Cleanup 165
Guaranteed initialization
with the constructor 165
Method overloading 168
Distinguishing
overloaded methods 171 Overloading with primitives 172 Overloading on return values 177 Default constructors 178 The this keyword 179
Cleanup: finalization
and garbage collection 183
What is finalize( ) for? 184 You must perform cleanup 185The termination condition 186 How a garbage collector works 188
Member initialization 191
Specifying initialization 193 Constructor initialization 194Array initialization 202
Multidimensional arrays 208Summary 211
Exercises 212
5: Hiding the
Implementation 215
package: the library unit....216
Creating uniquepackage names 218 A custom tool library 222 Using imports
to change behavior 224 Package caveat 224
Java access specifiers 224
Package access 225public: interface access 226 private:
you can't touch that! 228
protected: inheritance access 229
Interface
and implementation 231
Class access 232
Summary 236
Exercises 237
6: Reusing Classes 241
Composition syntax 241
Inheritance syntax 245
Initializing the base class 248Combining composition
and inheritance 250
Guaranteeing proper cleanup.... 252
Name hiding 256
Choosing composition
vs. inheritance 258
protected 260
Incremental
development 261
Upcasting 262
Why "upcasting"? 263The final keyword 264
Final data 264 Final methods 269 Final classes 271 Final caution 272Initialization
and class loading 273
Initialization with inheritance....274Summary 275
Exercises 276
7: Polymorphism 279
Upcasting revisited 279
Forgetting the object type 282The twist 283
Method-call binding 284 Producing the right behavior 284 Extensibility 288 Pitfall: "overriding" private methods 292Abstract classes
and methods 293
Constructors and
polymorphism 297
Order of constructor calls 298 Inheritance and cleanup 300 Behavior of polymorphicmethods inside constructors 303
Designing
with inheritance 306
Pure inheritanceDowncasting and
run-time type identification 310
Summary 312
Exercises 313
8: Interfaces
& Inner Classes 315
Interfaces 315
"Multiple inheritance" in Java....3ig Extending an interface with inheritance 323 Grouping constants 324 Initializing fields in interfaces 327 Nesting interfaces 328Inner classes 331
Inner classes and upcasting 333 Inner classes in methodsand scopes 335 Anonymous inner classes 338 The link to the outer class 342 Nested classes 344 Referring to the
outer class object 347 Reaching outward from a
multiply-nested class 348 Inheriting from inner classes 349 Can inner classes
be overridden? 350 Local inner classes 352 Inner class identifiers 354
Why inner classes? 354
Closures & Callbacks 357 Inner classes& control frameworks 360
Summary 367
Exercises 367
9: Error Handling
with Exceptions 371
Basic exceptions 372
Exception arguments 373Catching an exception 374
The try block 374 Exception handlers 375Creating your
own exceptions 376
The exception
specification 381
Catching any exception 382
Rethrowing an exception 384 Exception chaining 388Standard
Java exceptions 392
The special case ofRuntimeException 392
Performing cleanup
with finally 394
What's finally for? 396 Pitfall: the lost exception 399Exception restrictions 400
Constructors 404
Exception matching 408
Alternative approaches 409
History 410 Perspectives 412 Passing exceptions to the console 415 Converting checked to unchecked exceptions 416Exception guidelines 418
Summary 419
Exercises 419
10: Detecting Types 423
The need for RTTI 423
The Class object 426 Checking before a cast 429RTTI syntax 441
Reflection: run time
class information 444
A class method extractor 446Summary 450
Exercises 451
11: Collections
of Objects 453
Arrays 453
Arrays are first-class objects 455 Returning an array 458 The Arrays class 460 Filling an array 469 Copying an array 470 Comparing arrays 472 Array element comparisons 473 Sorting an array 476 Searching a sorted array 478 Array summary 480Introduction
to containers 481
Printing containers 482 Filling containers 484Container disadvantage:
unknown type 491
Sometimes it works anyway 493 Making a type-conscious ArrayList 495
Iterators 497
Container taxonomy 501
Collection functionality.. 505
List functionality 509
Making a stack from a LinkedList 513 Making a queue from a LinkedList 514Set functionality 515
SortedSet 519Map functionality 520
SortedMap 525 LinkedHashMap 527Hashing and hash codes 529 Overriding hashCode( ) 540
Holding references 545
The WeakHashMap 547Iterators revisited 549
Choosing
an implementation 550
Choosing between Lists 551 Choosing between Sets 554 Choosing between Maps 557Sorting and
searching Lists 560
Utilities 561
Making a Collection or Map unmodifiable 564 Synchronizing a Collection or Map 566Unsupported operations... 567
Java 1.0/1.1 containers 570
Vector & Enumeration 570 Hashtable 571 Stack 572 BitSet 573Summary 575
Exercises 576
12: The Java
I/O System 583
The File class 584
A directory lister 584 Checking for andcreating directories 588
Input and output 590
Types of InputStream 591 Types of OutputStream 593Adding attributes
Reading from an InputStream with FilterlnputStream 595 Writing to an OutputStream with FilterOutputStream 597
Readers & Writers 598
Sources and sinks of data 599 Modifying stream behavior 600 Unchanged Classes 601Off by itself:
RandomAccessFile 602
Typical uses
of I/O streams 603
Input streams 605 Output streams 608 Piped streams 610File reading
& writing utilities 610
Standard I/O 612
Reading from standard input 612 Changing System.outto a PrintWriter 613 Redirecting standard I/O 613
New I/O 615
Converting data 619 Fetching primitives 623 View buffers 625 Data manipulation with buffers 630 Buffer details 632 Memory-mapped files 636 File locking 640Compression 643
Simple compression with GZIP 644 Multifile storage with Zip 645 Java ARchives (JARs) 648Object serialization 650
Finding the class 654 Controlling serialization 656Using persistence 665
Preferences 673
Regular expressions 675
Creating regular expressions 675 Quantifiers 677 Pattern and Matcher 679 splitO 688 Replace operations 689 reset( ) 691 Regular expressionsand Java I/O 692 Is StringTokenizer needed? 693
Summary 694
Exercises 695
13: Concurrency 699
Motivation 700
Basic threads 701
Yielding 704 Sleeping 705 Priority 708 Daemon threads 710 Joining a thread 713 Coding variations 715 Creating responsive user interfaces 722Sharing
limited resources 723
Improperly accessing resources 723 Colliding over resources 729 Resolving shared resource contention 731 Critical sections 738Thread states 744
Becoming blocked 745Cooperation
between threads 745
Wait and notify 745Using Pipes for I/O
between threads 750 More sophisticated
cooperation 752
Deadlock 752
The proper way to stop 758
Interrupting a
blocked thread 759
Thread groups 760
Summary 761
Exercises 762
14: Creating
Windows & Applets 765
The basic applet 768
Applet restrictions 768 Applet advantages 769 Application frameworks 770 Running applets insidea Web browser 771 Using Appletviewer 773 Testing applets 774
Running applets
from the command line 775
A display framework 777Making a button 779
Capturing an event 780
Text areas 783
Controlling layout 785
BorderLayout 786 FlowLayout 787 GridLayout 788 GridBagLayout 788 Absolute positioning 789 BoxLayout 789 The best approach? 793The Swing event model 793
Event and listener types 794 Tracking multiple events 801A catalog of
Swing components 804
Buttons 805 Icons 808 Tool tips 810 Textfelds 810 Borders 812 JScrollPanes 814 A mini-editor 816 Check boxes 817 Radio buttons 819 Combo boxes (drop-down lists) 820 List boxes 821 Tabbed panes 824 Message boxes 825 Menus 827 Pop-up menus 834 Drawing 835 Dialog Boxes 838 File dialogs 843 HTML on Swing components ....845 Sliders and progress bars 846 Trees 847 Tables 850 Selecting Look & Feel 852 The clipboard 854Packaging an applet
into a JAR file 857
Signing applets 858
JNLP and
Java Web Start 863
Programming
techniques 869
Binding events dynamically 870 Separating business logicfrom UI logic 872 A canonical form 874
Concurrency & Swing 875
Runnable revisited 875 Managing concurrency 878
Visual programming
and JavaBeans 882
What is a JavaBean? 883 Extracting Beanlnfowith the Introspector 886 A more sophisticated Bean 892 JavaBeans
and synchronization 896 Packaging a Bean 901 More complex Bean support 902 More to Beans 903
Summary 904
Exercises 905
15: Discovering
Problems 909
Unit Testing 911
A Simple Testing Framework 913 JUnit 925Improving reliability
with assertions 930
Assertion syntax 931 Using Assertions forDesign by Contract 934
Example: DBC +
white-box unit testing 938
Building with Ant 944
Automate everything 944 Problems with make 945 Ant: the defacto standard 946 Version control with CVS 950 Daily builds 953Logging 954
Logging Levels 956 LogRecords 959 Handlers 961 Filters 966 Formatters 968Example: Sending email
to report log messages 969 Controlling Logging Levels through Namespaces 972 Logging Practices
for Large Projects 974 Summary 978
Debugging 978
Debugging with JDB 978 Graphical debuggers 984Profiling and optimizing... 985
Tracking
memory consumption 985 Tracking CPU usage 986 Coverage testing 986 JVM Profiling Interface 986 Using HPROF 987 Thread performance 989 Optimization guidelines 990
Doclets 991
Summary 993
Exercises 995
16: Analysis
and Design 997
Methodology 997
Phase o: Make a plan 1000
The mission statement 1000Phase 1:
What are we making? 1001
Phase 2:
How will we build it? 1005
Five stages of object design 1007 Guidelines forobject development 1008
Phase 3: Build the core.... 1009
Phase 4:
Iterate the use cases 1010
Phase 5: Evolution 1010
Plans pay off 1012
Extreme Programming ....1013
Write tests first 1013 Pair programming 1015Strategies for transition... 1016
Guidelines 1017 Management obstacles 1018Summary 1020
A: Passing
& Returning Objects 1021
Passing references
around 1022
Aliasing 1022Making local copies 1025
Pass by value 1026 Cloning objects 1026 Adding cloneability to a class 1028 Successful cloning 1030 The effect of Object.clone( ) 1032Cloning a composed object 1035 A deep copy
with ArrayList 1038 Deep copy via serialization 1040 Adding cloneability
farther down a hierarchy 1042 Why this strange design? 1043
Controlling
cloneability 1044
The copy constructor 1049Read-only classes 1054
Creating read-only classes 1056 The drawbackto immutability 1057 Immutable Strings 1060
The String and
StringBuffer classes 1063 Strings are special 1067