On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com
How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy
Thinking in Java
Contents
/
Index
Next
Thinking in Java, 3rd ed. Revision 4.0 - Contents
Preface
Preface to the 3rd edition
Java 2, JDK 1.4
Introduction
Prerequisites
Learning Java
Goals
JDK HTML documentation
Chapters
Exercises
The CD ROM
Source code
Coding standards
Java versions
Errors
Note on the cover design
Acknowledgements
1: Introduction to Objects
The progress of abstraction
An object has an interface
An object provides services
The hidden implementation
Reusing the implementation
Inheritance: reusing the interface
Is-a vs. is-like-a relationships
Interchangeable objects with polymorphism
Abstract base classes and interfaces
Object creation, use & lifetimes
Collections and iterators
The singly rooted hierarchy
Downcasting vs. templates/generics
Ensuring proper cleanup
Garbage collectors vs. efficiency and flexibility
Exception handling: dealing with errors
Concurrency
Persistence
Java and the Internet
What is the Web?
Client/Server computing
The Web as a giant server
Client-side programming
Plug-ins
Scripting languages
Java
.NET and C#
Security
Internet vs. intranet
Server-side programming
Applications
Why Java succeeds
Systems are easier to express and understand
Maximal leverage with libraries
Error handling
Programming in the large
Java vs. C++?
Summary
2: Everything is an Object
You manipulate objects with references
You must create all the objects
Where storage lives
Special case: primitive types
High-precision numbers
Arrays in Java
You never need to destroy an object
Scoping
Scope of objects
Creating new data types: class
Fields and methods
Default values for primitive members
Methods, arguments, and return values
The argument list
Building a Java program
Name visibility
Using other components
The static keyword
Your first Java program
Compiling and running
Comments and embedded documentation
Comment documentation
Syntax
Embedded HTML
Some example tags
@see: referring to other classes
{@link package.class#member label}
{@docRoot}
{@inheritDoc}
@version
@author
@since
@param
@return
@throws
@deprecated
Documentation example
Coding style
Summary
Exercises
3: Controlling Program Flow
Using Java operators
Precedence
Assignment
Aliasing during method calls
Mathematical operators
Regular expressions
Unary minus and plus operators
Auto increment and decrement
Relational operators
Testing object equivalence
Logical operators
Short-circuiting
Bitwise operators
Shift operators
Ternary if-else operator
The comma operator
String operator +
Common pitfalls when using operators
Casting operators
Literals
Promotion
Java has no “sizeof”
Precedence revisited
A compendium of operators
Execution control
true and false
if-else
return
Iteration
do-while
for
The comma operator
break and continue
The infamous “goto”
switch
Calculation details
Summary
Exercises
4: Initialization & Cleanup
Guaranteed initialization with the constructor
Method overloading
Distinguishing overloaded methods
Overloading with primitives
Overloading on return values
Default constructors
The this keyword
Calling constructors from constructors
The meaning of static
Cleanup: finalization and garbage collection
What is finalize( ) for?
You must perform cleanup
The termination condition
How a garbage collector works
Member initialization
Specifying initialization
Constructor initialization
Order of initialization
Static data initialization
Explicit static initialization
Non-static instance initialization
Array initialization
Multidimensional arrays
Summary
Exercises
5: Hiding the Implementation
package: the library unit
Creating unique package names
Collisions
A custom tool library
Using imports to change behavior
Package caveat
Java access specifiers
Package access
public: interface access
The default package
private: you can’t touch that!
protected: inheritance access
Interface and implementation
Class access
Summary
Exercises
6: Reusing Classes
Composition syntax
Inheritance syntax
Initializing the base class
Constructors with arguments
Catching base constructor exceptions
Combining composition and inheritance
Guaranteeing proper cleanup
Name hiding
Choosing composition vs. inheritance
protected
Incremental development
Upcasting
Why “upcasting”?
Composition vs. inheritance revisited
The final keyword
Final data
Blank finals
Final arguments
Final methods
final and private
Final classes
Final caution
Initialization and class loading
Initialization with inheritance
Summary
Exercises
7: Polymorphism
Upcasting revisited
Forgetting the object type
The twist
Method-call binding
Producing the right behavior
Extensibility
Pitfall: “overriding” private methods
Abstract classes and methods
Constructors and polymorphism
Order of constructor calls
Inheritance and cleanup
Behavior of polymorphic methods inside constructors
Designing with inheritance
Pure inheritance vs. extension
Downcasting and run-time type identification
Summary
Exercises
8: Interfaces & Inner Classes
Interfaces
“Multiple inheritance” in Java
Name collisions when combining interfaces
Extending an interface with inheritance
Grouping constants
Initializing fields in interfaces
Nesting interfaces
Inner classes
Inner classes and upcasting
Inner classes in methods and scopes
Anonymous inner classes
The link to the outer class
Nested classes
Referring to the outer class object
Reaching outward from a multiply-nested class
Inheriting from inner classes
Can inner classes be overridden?
Local inner classes
Inner class identifiers
Why inner classes?
Closures & Callbacks
Inner classes & control frameworks
Summary
Exercises
9: Error Handling with Exceptions
Basic exceptions
Exception arguments
Catching an exception
The try block
Exception handlers
Termination vs. resumption
Creating your own exceptions
The exception specification
Catching any exception
Rethrowing an exception
Exception chaining
Standard Java exceptions
The special case of RuntimeException
Performing cleanup with finally
What’s finally for?
Pitfall: the lost exception
Exception restrictions
Constructors
Exception matching
Alternative approaches
History
Perspectives
Passing exceptions to the console
Converting checked to unchecked exceptions
Exception guidelines
Summary
Exercises
10: Detecting Types
The need for RTTI
The Class object
Class literals
Checking before a cast
Using class literals
A dynamic instanceof
instanceof vs. Class equivalence
RTTI syntax
Reflection: run time class information
A class method extractor
Summary
Exercises
11: Collections of Objects
Arrays
Arrays are first-class objects
Containers of primitives
Returning an array
The Arrays class
Filling an array
Copying an array
Comparing arrays
Array element comparisons
Sorting an array
Searching a sorted array
Array summary
Introduction to containers
Printing containers
Filling containers
Container disadvantage: unknown type
Sometimes it works anyway
Making a type-conscious ArrayList
Parameterized types
Iterators
Unintended recursion
Container taxonomy
Collection functionality
List functionality
Making a stack from a LinkedList
Making a queue from a LinkedList
Set functionality
SortedSet
Map functionality
SortedMap
LinkedHashMap
Hashing and hash codes
Understanding hashCode( )
HashMap performance factors
Overriding hashCode( )
Holding references
The WeakHashMap
Iterators revisited
Choosing an implementation
Choosing between Lists
Choosing between Sets
Choosing between Maps
Sorting and searching Lists
Utilities
Making a Collection or Map unmodifiable
Synchronizing a Collection or Map
Fail fast
Unsupported operations
Java 1.0/1.1 containers
Vector & Enumeration
Hashtable
Stack
BitSet
Summary
Exercises
12: The Java I/O System
The File class
A directory lister
Anonymous inner classes
Checking for and creating directories
Input and output
Types of InputStream
Types of OutputStream
Adding attributes and useful interfaces
Reading from an InputStream with FilterInputStream
Writing to an OutputStream with FilterOutputStream
Readers & Writers
Sources and sinks of data
Modifying stream behavior
Unchanged Classes
Off by itself: RandomAccessFile
Typical uses of I/O streams
Input streams
1. Buffered input file
2. Input from memory
3. Formatted memory input
4. File output
Output streams
5. Storing and recovering data
6. Reading and writing random access files
Piped streams
File reading & writing utilities
Standard I/O
Reading from standard input
Changing System.out to a PrintWriter
Redirecting standard I/O
New I/O
Converting data
Fetching primitives
View buffers
Endians
Data manipulation with buffers
Buffer details
Memory-mapped files
Performance
File locking
Locking portions of a mapped file
Compression
Simple compression with GZIP
Multifile storage with Zip
Java ARchives (JARs)
Object serialization
Finding the class
Controlling serialization
The transient keyword
An alternative to Externalizable
Versioning
Using persistence
Preferences
Regular expressions
Creating regular expressions
Quantifiers
CharSequence
Pattern and Matcher
find( )
Groups
start( ) and end( )
Pattern flags
split( )
Replace operations
reset( )
Regular expressions and Java I/O
Is StringTokenizer needed?
Summary
Exercises
13: Concurrency
Motivation
Basic threads
Yielding
Sleeping
Priority
Daemon threads
Joining a thread
Coding variations
Creating responsive user interfaces
Sharing limited resources
Improperly accessing resources
A resource testing framework
Colliding over resources
Resolving shared resource contention
Synchronizing the EvenGenerator
Atomic operations
Fixing Semaphore
Critical sections
Thread states
Becoming blocked
Cooperation between threads
Wait and notify
Using Pipes for I/O between threads
More sophisticated cooperation
Deadlock
The proper way to stop
Interrupting a blocked thread
Thread groups
Summary
Exercises
14: Creating Windows & Applets
The basic applet
Applet restrictions
Applet advantages
Application frameworks
Running applets inside a Web browser
Using Appletviewer
Testing applets
Running applets from the command line
A display framework
Making a button
Capturing an event
Text areas
Controlling layout
BorderLayout
FlowLayout
GridLayout
GridBagLayout
Absolute positioning
BoxLayout
The best approach?
The Swing event model
Event and listener types
Using listener adapters for simplicity
Tracking multiple events
A catalog of Swing components
Buttons
Button groups
Icons
Tool tips
Text fields
Borders
JScrollPanes
A mini-editor
Check boxes
Radio buttons
Combo boxes (drop-down lists)
List boxes
Tabbed panes
Message boxes
Menus
Pop-up menus
Drawing
Dialog Boxes
File dialogs
HTML on Swing components
Sliders and progress bars
Trees
Tables
Selecting Look & Feel
The clipboard
Packaging an applet into a JAR file
Signing applets
JNLP and Java Web Start
Programming techniques
Binding events dynamically
Separating business logic from UI logic
A canonical form
Concurrency & Swing
Runnable revisited
Managing concurrency
Visual programming and JavaBeans
What is a JavaBean?
Extracting BeanInfo with the Introspector
A more sophisticated Bean
JavaBeans and synchronization
Packaging a Bean
More complex Bean support
More to Beans
Summary
Exercises
15: Discovering Problems
Unit Testing
A Simple Testing Framework
JUnit
Improving reliability with assertions
Assertion syntax
Using Assertions for Design by Contract
Check instructions
Preconditions
Postconditions
Invariants
Relaxing DBC
Example: DBC + white-box unit testing
Building with Ant
Automate everything
Problems with make
Ant: the defacto standard
Ant extensions
Version control with CVS
Daily builds
Logging
Logging Levels
LogRecords
Handlers
Multiple Handlers
Writing your own Handlers
Filters
Formatters
Example: Sending email to report log messages
Controlling Logging Levels through Namespaces
Logging Practices for Large Projects
Configuration files
Rotating log files
Suggested practices
Summary
Debugging
Debugging with JDB
Graphical debuggers
Profiling and optimizing
Tracking memory consumption
Tracking CPU usage
Coverage testing
JVM Profiling Interface
Using HPROF
Thread performance
Optimization guidelines
Doclets
Summary
Exercises
16: Analysis and Design
Methodology
Phase 0: Make a plan
The mission statement
Phase 1: What are we making?
Phase 2: How will we build it?
Five stages of object design
Guidelines for object development
Phase 3: Build the core
Phase 4: Iterate the use cases
Phase 5: Evolution
Plans pay off
Extreme Programming
Write tests first
Pair programming
Strategies for transition
Guidelines
1. Training
2. Low-risk project
3. Model from success
4. Use existing class libraries
5. Don’t rewrite existing code in Java
Management obstacles
Startup costs
Performance issues
Common design errors
Summary
A: Passing & Returning Objects
Passing references around
Aliasing
Making local copies
Pass by value
Cloning objects
Adding cloneability to a class
Using a trick with protected
Implementing the Cloneable interface
Successful cloning
The effect of Object.clone( )
Cloning a composed object
A deep copy with ArrayList
Deep copy via serialization
Adding cloneability farther down a hierarchy
Why this strange design?
Controlling cloneability
The copy constructor
Why does it work in C++ and not Java?
Read-only classes
Creating read-only classes
The drawback to immutability
Immutable Strings
Implicit constants
Overloading ‘+’ and the StringBuffer
The String and StringBuffer classes
Strings are special
Summary
Exercises
B: Java Programming Guidelines
Design
Implementation
C: Supplements
Foundations for Java seminar-on-CD
Thinking in Java seminar
Hands-On Java seminar-on-CD 3rd edition
Designing Objects & Systems seminar
Thinking in Enterprise Java
The J2EE seminar
Thinking in Patterns (with Java)
Thinking in Patterns seminar
Design consulting and reviews
D: Resources
Software
Books
Analysis & design
Python
My own list of books
Index
Thinking in Java
Contents
/
Index
Next
Reproduced courtesy of Bruce Eckel, MindView, Inc.
Design by Interspire
x