Thinking in Java, 3
rd
ed. Revision 2.0
[
Viewing Hints
] [
Book Home Page
] [
Free Newsletter
]
[
Seminars
] [
Seminars on CD ROM
] [
Consulting
]
Thinking in Java, 3rd ed. Revision 2.0 - Contents
Thinking in Java, 3rd ed. Revision 2.0 - Title Page
Bruce Eckels Hands-On Java Seminar Multimedia CD Its like coming to the seminar! Available at www.BruceEckel.com
Preface
Preface to the 2nd edition
Java 2
The CD ROM
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
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 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. Dont 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
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 cant 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 revisited
Forgetting the object type
The twist
Method-call binding
Producing the right behavior
Extensibility
Overriding vs. overloading
Pitfall: overriding private methods
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
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: 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
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
Creating your own exceptions
The exception specification
Catching any exception
Rethrowing an exception
Standard Java exceptions
The special case of RuntimeException
Performing cleanup with finally
Whats finally for?
Pitfall: the lost exception
Exception restrictions
Constructors
Exception matching
Exception guidelines
Summary
Exercises
11: 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
Standard I/O
Reading from standard input
Changing System.out to a PrintWriter
Redirecting standard I/O
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
Tokenizing input
StreamTokenizer
StringTokenizer
Checking capitalization style
Summary
Exercises
12: 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
13: Concurrency
Motivation
Basic threads
Yeilding
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
Synchronized efficiency
Blocking
Becoming blocked
Wait and notify
Blocking on I/O
Deadlock
The deprecation of stop( ), suspend( ), resume( ), and destroy( ) in Java 2
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
Using the Windows Explorer
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
Programming techniques
Binding events dynamically
Separating business logic from UI logic
A canonical form
Runnable revisited
Visual programming and Beans
What is a Bean?
Extracting BeanInfo with the Introspector
A more sophisticated Bean
JavaBean 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
Part II: J2EE
16: 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
Using URLs from within an applet
Reading a file from the server
More to networking
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 example
RMI (Remote Method Invocation)
Remote interfaces
Implementing the remote interface
Setting up the registry
Creating stubs and skeletons
Using the remote object
Summary
Exercises
17: Servlets, JSPs & Tags
Servlets
The basic servlet
Servlets and multithreading
Handling sessions with servlets
The Cookie class
The Session class
Running the servlet examples
JavaServer Pages
Implicit objects
JSP directives
JSP scripting elements
Extracting fields and values
JSP page attributes and scope
Manipulating sessions in JSP
Creating and modifying cookies
JSP summary
Exercises
18: Enterprise JavaBeans
JavaBeans vs. EJBs
The EJB specification
EJB components
EJB Container & Server
Java Naming and Directory Interface (JNDI)
Java Transaction API/Java Transaction Service (JTA/JTS)
CORBA and RMI/IIOP
The pieces of an EJB component
Enterprise Bean
Home interface
Remote interface
Deployment descriptor
EJB-Jar file
EJB operation
Types of EJBs
Session Beans
Entity Beans
Developing an EJB
EJB summary
19: XML
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: Java Programming Guidelines
Design
Implementation
C: Resources
Software
Books
Analysis & design
Python
My own list of books
Index
Bruce Eckels Hands-On Java Seminar Multimedia CD Its like coming to the seminar! Available at www.BruceEckel.com