Thinking in Java, 1st edition - Contents
Thinking in Java, 1st edition - Title Page
Foreword
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
1: Introduction to objects
The progress of abstraction
An object has an interface
The hidden implementation
Reusing the implementation
Inheritance: reusing the interface
Overriding base-class functionality
Is-a vs. is-like-a relationships
Interchangeable objects with polymorphism
Dynamic binding
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
Staying on course
Phase 0: Let’s make a plan
Phase 1: What are we making?
Phase 2: How will we build it?
Phase 3: Let’s build it!
Phase 4: Iteration
Plans pay off
Java vs. C++?
2: Everything is an object
You manipulate objects with handles
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
Comments and embedded documentation
Comment documentation
Syntax
Embedded HTML
@see: referring to other classes
Class documentation tags
@version
@author
Variable documentation tags
Method documentation tags
@param
@return
@exception
@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 and 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
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
Automatic compilation
Collisions
A custom tool library
Classpath pitfall
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 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
Interfaces
“Multiple inheritance” in Java
Extending an interface with inheritance
Grouping constants
Initializing fields in interfaces
Inner classes
Inner classes and upcasting
Inner classes in methods and scopes
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: control frameworks
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: Holding your objects
Arrays
Arrays are first-class objects
Collections of primitives
Returning an array
Collections
Disadvantage: unknown type
Sometimes it works right anyway
Making a type-conscious Vector
Parameterized types
Enumerators (iterators)
Types of collections
Vector
Crashing Java
BitSet
Stack
Hashtable
Creating “key” classes
Properties: a type of Hashtable
Enumerators revisited
Sorting
The generic collection library
The new collections
Using Collections
Using Lists
Using Sets
Using Maps
Choosing an implementation
Choosing between Lists
Choosing between Sets
Choosing between Maps
Unsupported operations
Sorting and searching
Arrays
Comparable and Comparator
Lists
Utilities
Making a Collection or Map unmodifiable
Synchronizing a Collection or Map
Summary
Exercises
9: 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
10: 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
A sorted directory listing
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
Summary
Exercises
11: Run-time type identification
The need for RTTI
The Class object
Class literals
Checking before a cast
Using class literals
A dynamic instanceof
RTTI syntax
Reflection: run-time class information
A class method extractor
Summary
Exercises
12: Passing and returning objects
Passing handles 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 Vector
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
13: Creating windows and applets
Why use the AWT?
The basic applet
Testing applets
A more graphical example
Demonstrating the framework methods
Making a button
Capturing an event
Text fields
Text areas
Labels
Check boxes
Radio buttons
Drop-down lists
List boxes
handleEvent( )
Controlling layout
FlowLayout
BorderLayout
GridLayout
CardLayout
Combining layouts
GridBagLayout
Alternatives to action
Applet restrictions
Applet advantages
Windowed applications
Menus
Dialog boxes
File dialogs
The new AWT
The new event model
Event and listener types
Using listener adapters for simplicity
Making windows and applets with the Java 1.1 AWT
Making the window listener an anonymous class
Packaging the applet into a JAR file
Revisiting the earlier examples
Text fields
Text areas
Check boxes and radio buttons
Drop-down lists
Lists
Menus
Dialog boxes
File dialogs
Binding events dynamically
Separating business logic from UI logic
Recommended coding approaches
Baseline: the good way to do it
Implementing the main class as a listener
Mixing the approaches
Inheriting a component
Ugly component inheritance
Java 1.1 UI APIs
Desktop colors
Printing
Printing text
Printing graphics
Running Frames within applets
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
A display framework
Tool tips
Borders
Buttons
Button groups
Icons
Menus
Popup menus
List boxes and combo boxes
Sliders and progress bars
Trees
Tables
Tabbed Panes
The Swing message box
More to Swing
Summary
Exercises
14: Multiple threads
Responsive user interfaces
Inheriting from Thread
Threading for a responsive interface
Improving the code with an inner class
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 1.2
Priorities
Thread groups
Controlling thread groups
Runnable revisited
Too many threads
Summary
Exercises
15: 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
A Web application
The server application
The C program
The Java program
The NameSender applet
The Web page
Problems with this approach
Connecting Java to CGI
Encoding data for CGI
The applet
Displaying a Web page from within an applet
The CGI program in C++
What about POST?
Connecting to databases with 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
Remote methods
Remote interfaces
Implementing the remote interface
Setting up the registry
Creating stubs and skeletons
Using the remote object
Alternatives to RMI
Summary
Exercises
16: Design patterns
The pattern concept
The singleton
Classifying patterns
The observer pattern
Simulating the trash recycler
Improving the design
“Make more objects”
A pattern for prototyping creation
Trash subclasses
Parsing Trash from an external file
Recycling with prototyping
Abstracting usage
Multiple dispatching
Implementing the double dispatch
The “visitor” pattern
More coupling?
RTTI considered harmful?
Summary
Exercises
17: Projects
Text processing
Extracting code listings
Building a packed file
Extracting from a packed file
Accessing and writing the listings
Containing the entire collection of listings
The main program
Checking capitalization style
A method lookup tool
Complexity theory
Summary
Exercises
A: Using non-Java code
The Java Native Interface
Calling a native method
The C 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 pre-existing code base
The Microsoft way
J/Direct
The @dll.import directive
Aliasing and linking by ordinal
Applying @dll.import to the entire class
The com.ms.win32 package
Marshaling
Writing callback functions
Other J/Direct features
Raw Native Interface (RNI)
RNI Summary
Java/COM integration
COM Fundamentals
GUIDs and the Registry
Type Libraries
Function return codes in COM: HRESULT
MS Java/COM Integration
Developing COM servers in Java
Developing COM clients in Java
The com.ms.com package
ActiveX/Beans integration
A note about native methods and applets
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
Summary
B: Comparing C++ and Java
C: Java programming guidelines
D: Performance
Basic approach
Locating the bottleneck
1. Install your own instrumentation
2. JDK profiling [2]
3. Special tools
Tips for measuring performance
Speedup techniques
Generic approaches
Language dependent approaches
General modifications
Specific situations
Other suggestions
References
Performance tools
Web sites
Articles
Java specific books
General books
E: A bit about garbage collection
F: Recommended reading
Index