Thinking in Java, Second Edition - Table of Contents
Preface
Introduction
Prerequisites
Learning Java
Goals
Online documentation
Chapters
Exercises
Multimedia CD ROM
Source code
Coding standards
Java versions
Seminars and mentoring
Errors
Note on the cover design
Acknowledgements
Internet contributors
1: Introduction to Objects
The progress of abstraction
An object has an interface
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 landscapes and lifetimes
Collections and iterators
The singly rooted hierarchy
Collection libraries and support for easy collection use
Downcasting vs. templates/generics
The housekeeping dilemma: who should clean up?
Garbage collectors vs. efficiency and flexibility
Exception handling: dealing with errors
Multithreading
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
ActiveX
Security
Internet vs. intranet
Server-side programming
A separate arena: applications
Analysis and design
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
Why Java succeeds
Systems are easier to express and understand
Maximal leverage with libraries
Error handling
Programming in the large
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
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
@see: referring to other classes
Class documentation tags
@version
@author
@since
Variable documentation tags
Method documentation tags
@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
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 death 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
“Friendly”
public: interface access
The default package
private: you can’t touch that!
protected: “sort of friendly”
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
Order of garbage collection
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
Why upcast?
The twist
Method call binding
Producing the right behavior
Extensibility
Overriding vs. overloading
Abstract classes and methods
Constructors and polymorphism
Order of constructor calls
Inheritance and finalize( )
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
Inner classes
Inner classes and upcasting
Inner classes in methods and scopes
Anonymous inner classes
The link to the outer class
static inner classes
Referring to the outer class object
Inheriting from inner classes
Can inner classes be overridden?
Inner class identifiers
Why inner classes?
Closures & Callbacks
Inner classes & control frameworks
Summary
Exercises
9: Holding Your 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
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
10: Error Handling with Exceptions
Basic exceptions
Exception arguments
Catching an exception
The try block
Exception handlers
Termination vs. resumption
The exception specification
Catching any exception
Rethrowing an exception
Standard Java exceptions
The special case of RuntimeException
Creating your own exceptions
Exception restrictions
Performing cleanup with finally
What’s finally for?
Pitfall: the lost exception
Constructors
Exception matching
Exception guidelines
Summary
Exercises
11: The Java IO System
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
Off by itself: RandomAccessFile
The File class
A directory lister
Anonymous inner classes
Checking for and creating directories
Typical uses of IO streams
Input streams
1. Buffered input file
2. Input from memory
3. Formatted memory input
4. Line numbering and file output
Output streams
5. Storing and recovering data
6. Reading and writing random access files
Shorthand for file manipulation
7. File input shorthand
8. Formatted file output shorthand
9. Data file output shorthand
Reading from standard input
Piped streams
StreamTokenizer
StringTokenizer
Java 1.1 IO streams
Sources and sinks of data
Modifying stream behavior
Unchanged Classes
An example
Redirecting standard IO
Compression
Simple compression with GZIP
Multi-file storage with Zip
The Java archive (jar) utility
Object serialization
Finding the class
Controlling serialization
The transient keyword
An alternative to Externalizable
Versioning
Using persistence
Checking capitalization style
Summary
Exercises
12: Run-time Type Identification
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
13: Creating Windows & Applets
The basic applet
Running applets inside a Web browser
Using Appletviewer
Testing applets
Making windows and applets
A display framework
Closing the window
Using the Windows Explorer
Making a button
Capturing an event
Text fields
Text areas
Labels
HTML text on Swing components
Check boxes
Radio buttons
Drop-down lists
List boxes
Tabbed panes
Message boxes
Menus
Dialog Boxes
Controlling layout
FlowLayout
BorderLayout
GridLayout
GridBagLayout
BoxLayout
Absolute positioning
Alternatives to action
Applet restrictions
Applet advantages
Windowed applications
Menus
Dialog boxes
File dialogs
The event model
Event and listener types
Using listener adapters for simplicity
Packaging the applet into a JAR file
Revisiting the earlier examples
Demonstrating the framework methods
Text fields
Text areas
Check boxes and radio buttons
Drop-down lists
Lists
Menus
Dialog boxes
Selecting Look & Feel
Binding events dynamically
Separating business logic from UI logic
Recommended coding approaches
Baseline: the good way to do it
JFC APIs
Desktop colors
The clipboard
Visual programming and Beans
What is a Bean?
Extracting BeanInfo with the Introspector
A more sophisticated Bean
Packaging a Bean
More complex Bean support
More to Beans
Introduction to Swing
Benefits of Swing
Easy conversion
Tool tips
Borders
Buttons
Button groups
Icons
Menus
Popup menus
List boxes and combo boxes
Sliders and progress bars
Trees
Tables
More to Swing
Using URLs from within an applet
Reading a file from the server
A method lookup tool
Summary
Exercises
14: Multiple Threads
Responsive user interfaces
Inheriting from Thread
Threading for a responsive interface
Combining the thread with the main class
Making many threads
Daemon threads
Sharing limited resources
Improperly accessing resources
How Java shares resources
Synchronizing the counters
Synchronized efficiency
Java Beans revisited
Blocking
Becoming blocked
Sleeping
Suspending and resuming
Wait and notify
Blocking on IO
Testing
Deadlock
The deprecation of stop( ), suspend( ), resume( ), and destroy( ) in Java 2
Priorities
Thread groups
Controlling thread groups
Runnable revisited
Too many threads
Summary
Exercises
15: Distributed Computing
Network programming
Identifying a machine
Servers and clients
Testing programs without a network
Port: a unique place within the machine
Sockets
A simple server and client
Serving multiple clients
Datagrams
Enterprise programming concepts
Java Database Connectivity (JDBC)
Getting the example to work
Step 1: Find the JDBC Driver
Step 2: Configure the database
Step 3: Test the configuration
Step 4: Generate your SQL query
Step 5: Modify and paste in your query
A GUI version of the lookup program
Why the JDBC API seems so complex
A more sophisticated JDBC Example
Servlets
The basic servlet
Servlets and Multithreading
Handling Sessions with Servlets
The Cookie Class
The Session Class
Getting the Servlet examples to work
Java Server Pages
Basic operations
Implicit Objects
JSP Scripting Elements
Extracting fields and values
JSP Page Attributes and Scope
Scope: 1
Scope: 2
Scope: 3
Scope: 4
End of list
Manipulating sessions in JSP
Creating and modifying Cookies
RMI (Remote Method Invocation)
Remote interfaces
Implementing the remote interface
Setting up the registry
Creating stubs and skeletons
Using the remote object
Introduction to CORBA
CORBA Fundamentals
CORBA Interface Definition Language (IDL)
The naming service
An example
Writing the IDL source
Creating stubs and skeletons
Implementing the server and the client
Some CORBA services
Activating the name service process
Activating the server and the client
Java Applets and CORBA
CORBA vs. RMI
Enterprise Java Beans
What’s defined in the EJB specification?
Roles
Components of EJB
EJB Container
EJB Server
Java Naming and Directory Interface (JNDI)
Java Transaction API / Java Transaction Service (JTA/JTS)
CORBA and RMI/IIOP
What makes up an EJB component?
Enterprise Bean
Home Interface
Remote Interface
Deployment Descriptor
EJB-Jar File
How does EJB work?
Who implements the Home and Remote Interfaces?
Types of EJB’s
Session Beans
Stateless Session Beans
Stateful Session Beans
Entity Beans
Container Managed Persistence (CMP)
Bean Managed Persistence (BMP)
How do I put the ‘E’ in my existing JavaBeans?
Developing an Enterprise Java Bean
In Summary
Jini: distributed services
Jini in context
What is Jini?
How Jini works
The discovery process
The join process
The lookup process
Separation of interface and implementation
Abstracting distributed systems
JavaSpaces
Summary
Exercises
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 further 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: The Java Native Interface (JNI)
The Java Native Interface
Calling a native method
The header file generator: javah
Name mangling and function signatures
Implementing your DLL
Accessing JNI functions: The JNIEnv argument
Accessing Java Strings
Passing and using Java objects
JNI and Java exceptions
JNI and threading
Using a preexisting code base
Additional information
C: Java Programming Guidelines
Design
Implementation
D: Resources
Software
Books
Analysis & design
My own list of books
Index