Log In
Or create an account ->
Imperial Library
Home
About
News
Upload
Forum
Help
Login/SignUp
Index
Learning Java
Patrick Niemeyer
Daniel Leuck
Special Upgrade Offer
Preface
Who Should Read This Book
New Developments
New in This Edition (Java 6 and 7)
Using This Book
Online Resources
Conventions Used in This Book
Tip
Warning
Using Code Examples
Safari® Books Online
Note
How to Contact Us
Acknowledgments
Chapter 1. A Modern Language
Enter Java
Java’s Origins
Growing Up
A Virtual Machine
Java Compared with Other Languages
Safety of Design
Simplify, Simplify, Simplify...
Type Safety and Method Binding
Incremental Development
Dynamic Memory Management
Error Handling
Threads
Scalability
Safety of Implementation
The Verifier
Class Loaders
Security Managers
Application and User-Level Security
A Java Road Map
The Past: Java 1.0–Java 1.6
The Present: Java 7
The Future
Availability
Chapter 2. A First Application
Java Tools and Environment
Configuring Eclipse and Creating a Project
Importing the Learning Java Examples
HelloJava
Classes
The main() Method
Classes and Objects
Variables and Class Types
HelloComponent
Inheritance
The JComponent Class
Relationships and Finger Pointing
Package and Imports
The paintComponent() Method
HelloJava2: The Sequel
Instance Variables
Constructors
Events
The repaint() Method
Interfaces
HelloJava3: The Button Strikes!
Method Overloading
Components
Containers
Layout
Subclassing and Subtypes
More Events and Interfaces
Tip
Color Commentary
Static Members
Arrays
Our Color Methods
HelloJava4: Netscape’s Revenge
Threads
The Thread Class
The Runnable Interface
Starting the Thread
Running Code in the Thread
Exceptions
Synchronization
Chapter 3. Tools of the Trade
JDK Environment
The Java VM
Running Java Applications
System Properties
The Classpath
javap
The Java Compiler
JAR Files
File Compression
The jar Utility
JAR manifests
Making a JAR file runnable
The pack200 Utility
Policy Files
The Default Security Manager
The policytool Utility
Using a Policy File with the Default Security Manager
Chapter 4. The Java Language
Text Encoding
Comments
Javadoc Comments
Javadoc as metadata
Types
Primitive Types
Note
Floating-point precision
Variable declaration and initialization
Integer literals
Floating-point literals
Binary literals
Character literals
Reference Types
A Word About Strings
Statements and Expressions
Statements
if/else conditionals
do/while loops
The for loop
The enhanced for loop
switch statements
Enumerations and switch statements
break/continue
Unreachable statements
Expressions
Operators
Assignment
The null value
Variable access
Method invocation
Object creation
The instanceof operator
Exceptions
Exceptions and Error Classes
Exception Handling
Bubbling Up
Stack Traces
Checked and Unchecked Exceptions
Throwing Exceptions
Chaining and rethrowing exceptions
Narrowed rethrow
try Creep
The finally Clause
Try with Resources
Performance Issues
Assertions
Enabling and Disabling Assertions
Using Assertions
Arrays
Array Types
Array Creation and Initialization
Using Arrays
Anonymous Arrays
Multidimensional Arrays
Inside Arrays
Chapter 5. Objects in Java
Classes
Accessing Fields and Methods
Static Members
Constants versus enumerations
Methods
Local Variables
Shadowing
The “this” reference
Static Methods
Initializing Local Variables
Argument Passing and References
Wrappers for Primitive Types
Autoboxing and Unboxing of Primitives
Performance implications of boxing
Variable-Length Argument Lists
Method Overloading
Object Creation
Constructors
Working with Overloaded Constructors
Static and Nonstatic Initializer Blocks
Object Destruction
Garbage Collection
Finalization
Weak and Soft References
Enumerations
Enum Values
Customizing Enumerations
Chapter 6. Relationships Among Classes
Subclassing and Inheritance
Shadowed Variables
Overriding Methods
@Override
Overridden methods and dynamic binding
Static method binding
final methods and performance
Compiler optimizations
Method selection revisited
Exceptions and overridden methods
Return types and overridden methods
Special References: this and super
Casting
Casting aspersions
Using Superclass Constructors
Full Disclosure: Constructors and Initialization
Abstract Methods and Classes
Interfaces
Interfaces as Callbacks
Interface Variables
Flag interfaces
Subinterfaces
Overlapping and conflicting methods
Packages and Compilation Units
Compilation Units
Package Names
Class Visibility
Importing Classes
Note
The unnamed package
Static imports
Visibility of Variables and Methods
Basic Access Modifiers
Subclasses and Visibility
Interfaces and Visibility
Arrays and the Class Hierarchy
ArrayStoreException
Inner Classes
Inner Classes as Adapters
Inner Classes Within Methods
Limitations on inner classes in methods
Static inner classes
Anonymous inner classes
Scoping of the “this” reference
How do inner classes really work?
Security implications
Chapter 7. Working with Objects and Classes
The Object Class
Equality and Equivalence
Hashcodes
Cloning Objects
The Class Class
Reflection
Modifiers and Security
Accessing Fields
Accessing Methods
Accessing Constructors
What About Arrays?
Accessing Generic Type Information
Accessing Annotation Data
Dynamic Interface Adapters
What Is Reflection Good For?
The BeanShell Java scripting language
Annotations
Using Annotations
Package annotations
Standard Annotations
The apt Tool
Chapter 8. Generics
Containers: Building a Better Mousetrap
Can Containers Be Fixed?
Enter Generics
Talking About Types
“There Is No Spoon”
Erasure
Raw Types
Parameterized Type Relationships
Why Isn’t a List<Date> a List<Object>?
Casts
Writing Generic Classes
The Type Variable
Subclassing Generics
Exceptions and Generics
No generic throwables
Parameter Type Limitations
Using Class<T>
Bounds
Erasure and Bounds (Working with Legacy Code)
Wildcards
A Supertype of All Instantiations
Bounded Wildcards
Thinking Outside the Container
Lower Bounds
Reading, Writing, and Arithmetic
<?>, <Object>, and the Raw Type
Wildcard Type Relationships
Generic Methods
Generic Methods Introduced
Type Inference from Arguments
Type Inference from Assignment Context
Explicit Type Invocation
Wildcard Capture
Wildcard Types Versus Generic Methods
Arrays of Parameterized Types
Using Array Types
What Good Are Arrays of Generic Types?
Wildcards in Array Types
Case Study: The Enum Class
Case Study: The sort() Method
Conclusion
Chapter 9. Threads
Introducing Threads
The Thread Class and the Runnable Interface
Creating and starting threads
A natural-born thread
Using an adapter
Controlling Threads
Deprecated methods
The sleep() method
The join() method
The interrupt() method
Death of a Thread
Threading an Applet
Issues Lurking
Synchronization
Serializing Access to Methods
Accessing class and instance Variables from Multiple Threads
Reentrant locking
The wait() and notify() Methods
Wait conditions
Passing Messages
Food for thought
ThreadLocal Objects
Scheduling and Priority
Thread State
Time-Slicing
Priorities
Yielding
Thread Groups
Working with ThreadGroups
Uncaught Exceptions
Thread Performance
The Cost of Synchronization
Thread Resource Consumption
Concurrency Utilities
Executors
Tasks with results: Callable and Future
ExecutorService
Collective tasks
Scheduled tasks
CompletionService
The ThreadPoolExecutor implementation
Thread production
The Fork/Join framework
Locks
Read and write locks
Conditions
Synchronization Constructs
CountDownLatch
Semaphore
CyclicBarrier
Phaser
Exchanger
Atomic Operations
Weak implementations
Field updaters
Conclusion
Chapter 10. Working with Text
Text-Related APIs
Strings
Constructing Strings
Strings from Things
Comparing Strings
The Collator class
Searching
Editing
String Method Summary
StringBuilder and StringBuffer
Internationalization
The java.util.Locale Class
Resource Bundles
Parsing and Formatting Text
Parsing Primitive Numbers
Working with alternate bases
Number formats
Tokenizing Text
StringTokenizer
Printf-Style Formatting
Formatter
The Format String
String Conversions
Width, precision, and justification
Uppercase
Numbered arguments
Primitive and Numeric Conversions
Flags
Miscellaneous
Formatting with the java.text Package
MessageFormat
Regular Expressions
Regex Notation
Write once, run away
Escaped characters
Characters and character classes
Custom character classes
Position markers
Iteration (multiplicity)
Grouping
Capture groups
Numbering
Alternation
Special options
Greediness
Lookaheads and lookbehinds
The java.util.regex API
Pattern
The Matcher
Splitting and tokenizing strings
Another look at Scanner
Replacing text
Using captured text in a replacement
Controlling the substitution
Our simple template engine
Chapter 11. Core Utilities
Math Utilities
The java.lang.Math Class
Big/Precise Numbers
Floating-Point Components
Random Numbers
Dates and Times
Working with Calendars
Time Zones
Locale
Parsing and Formatting with DateFormat
Printf-Style Date and Time Formatting
Timers
Collections
The Collection Interface
Generics and collections
Legacy code and runtime type safety
Converting between collections and arrays
Iterator
For loop over collections
java.util.Enumeration
Collection Types
Set
List
Queue
BlockingQueue
The Map Interface
ConcurrentMap
Collection Implementations
Arrays
Linked lists
Trees
Hash maps
Java Collections implementations
Hash Codes and Key Values
Synchronized and Unsynchronized Collections
Synchronizing iterators
ConcurrentHashMap and ConcurrentLinkedQueue
Read-Only and Read-Mostly Collections
Copy-on-write (“read-mostly”) collections
WeakHashMap
EnumSet and EnumMap
Sorting Collections
A Thrilling Example
Properties
Loading and Storing
System Properties
The Preferences API
Preferences for Classes
Preferences Storage
Change Notification
The Logging API
Overview
Loggers
Handlers
Filters
Formatters
Logging Levels
A Simple Example
Logging Setup Properties
The Logger
Performance
Observers and Observables
Chapter 12. Input/Output Facilities
Streams
Basic I/O
Character Streams
Stream Wrappers
Data streams
Buffered streams
PrintWriter and PrintStream
Pipes
Streams from Strings and Back
Implementing a Filter Stream
File I/O
The java.io.File Class
File constructors
Path localization
Note
File operations
File Streams
RandomAccessFile
Resource Paths
The NIO File API
FileSystem and Path
Path to classic file and back
NIO File Operations
Directory Operations
Watching Paths
Serialization
Initialization with readObject()
SerialVersionUID
Data Compression
Archives and Compressed Data
Zip archives
Decompressing Data
Zip Archive As a Filesystem
The NIO Package
Asynchronous I/O
Performance
Mapped and Locked Files
Channels
Buffers
Buffer operations
Buffer types
Byte order
Allocating buffers
Character Encoders and Decoders
CharsetEncoder and CharsetDecoder
FileChannel
Concurrent access
File locking
Memory-mapped files
Direct transfer
AsynchronousFileChannel
Scalable I/O with NIO
Chapter 13. Network Programming
Sockets
Clients and Servers
Clients
Servers
Sockets and security
The DateAtHost Client
The TinyHttpd Server
Warning
Do French web servers speak French?
Taming the daemon
Room for improvement
Socket Options
SO_TIMEOUT
TCP_NODELAY
SO_LINGER
TCP_KEEPALIVE
Half-close
Proxies and Firewalls
ProxySelector
Datagram Sockets
The HeartBeat Applet
The HeartBeat applet code
The Pulse server code
InetAddress
Simple Serialized Object Protocols
A Simple Object-Based Server
Limitations
Remote Method Invocation
Real-World Usage
Remote and Nonremote Objects
Remote interfaces
Exporting remote objects
The RMI registry
An RMI Example
Running the example
Dynamic class loading
Passing remote object references
RMI and CORBA
Scalable I/O with NIO
Selectable Channels
Using Select
LargerHttpd
Nonblocking Client-Side Operations
Chapter 14. Programming for the Web
Uniform Resource Locators (URLs)
The URL Class
Stream Data
Getting the Content as an Object
Managing Connections
Handlers in Practice
Useful Handler Frameworks
Talking to Web Applications
Using the GET Method
Using the POST Method
The HttpURLConnection
SSL and Secure Web Communications
URLs, URNs, and URIs
Web Services
XML-RPC
WSDL
The Tools
The Weather Service Client
Chapter 15. Web Applications and Web Services
Web Application Technologies
Page-Oriented Versus “Single Page” Applications
JSPs
XML and XSL
Web Application Frameworks
Google Web Toolkit
HTML5, AJAX, and More...
Java Web Applications
The Servlet Lifecycle
Servlets
The HelloClient Servlet
ServletExceptions
Content type
The Servlet Response
Servlet Parameters
GET, POST, and “extra path”
GET or POST: Which one to use?
The ShowParameters Servlet
User Session Management
The ShowSession Servlet
The ShoppingCart Servlet
Cookies
The ServletContext API
Asynchronous Servlets
WAR Files and Deployment
Configuration with web.xml and Annotations
URL Pattern Mappings
Deploying HelloClient
Reloading web apps
Error and Index Pages
Security and Authentication
Protecting Resources with Roles
Secure Data Transport
Authenticating Users
Procedural Authorization
Servlet Filters
A Simple Filter
A Test Servlet
Declaring and Mapping Filters
Filtering the Servlet Request
Filtering the Servlet Response
Building WAR Files with Ant
A Development-Oriented Directory Layout
Deploying and Redeploying WARs with Ant
Implementing Web Services
Defining the Service
Our Echo Service
Using the Service
Data Types
Standard types
Value data objects
Conclusion
Chapter 16. Swing
Components
Peers and Look-and-Feel
The MVC Framework
Painting
Enabling and Disabling Components
Focus, Please
Other Component Methods
Containers
Layout Managers
Insets
Z-Ordering (Stacking Components)
The revalidate() and doLayout() Methods
Managing Components
Listening for Components
Windows, Frames and Splash Screens
Other Methods for Controlling Frames
Content Panes
Desktop Integration
Events
Event Receivers and Listener Interfaces
Event Sources
Event Delivery
Event Types
The java.awt.event.InputEvent Class
Mouse and Key Modifiers on InputEvents
Mouse-wheel events
Focus Events
Event Summary
Adapter Classes
Dummy Adapters
The AWT Robot!
Multithreading in Swing
Chapter 17. Using Swing Components
Buttons and Labels
HTML Text in Buttons and Labels
Checkboxes and Radio Buttons
Lists and Combo Boxes
The Spinner
Borders
Menus
Pop-Up Menus
Component-Managed Pop Ups
The JScrollPane Class
The JSplitPane Class
The JTabbedPane Class
Scrollbars and Sliders
Dialogs
File Selection Dialog
The Color Chooser
Chapter 18. More Swing Components
Text Components
The TextEntryBox Application
Formatted Text
Filtering Input
DocumentFilter
Validating Data
Say the Magic Word
Sharing a Data Model
HTML and RTF for Free
Managing Text Yourself
Focus Navigation
Trees
Nodes and Models
Save a Tree
Tree Events
A Complete Example
Tables
A First Stab: Freeloading
Round Two: Creating a Table Model
Round Three: A Simple Spreadsheet
Sorting and Filtering
Printing JTables
Desktops
Pluggable Look-and-Feel
Creating Custom Components
Generating Events
A Dial Component
Model and View Separation
Chapter 19. Layout Managers
FlowLayout
GridLayout
BorderLayout
BoxLayout
CardLayout
GridBagLayout
The GridBagConstraints Class
Grid Coordinates
The fill Constraint
Spanning Rows and Columns
Weighting
Calculating the weights of rows and columns
Anchoring
Padding and Insets
Relative Positioning
Composite Layouts
Other Layout Managers
Absolute Positioning
Chapter 20. Drawing with the 2D API
The Big Picture
The Rendering Pipeline
A Quick Tour of Java 2D
Filling Shapes
Drawing Shape Outlines
Convenience Methods
Drawing Text
Drawing Images
Transformations and rendering
The Whole Iguana
Filling Shapes
Solid Colors
Tip
Color Gradients
Textures
Desktop Colors
Stroking Shape Outlines
Using Fonts
Font Metrics
Displaying Images
The Image Class
Image Observers
Preloading images
Scaling and Size
Drawing Techniques
Double Buffering
Limiting Drawing with Clipping
Offscreen Drawing
Printing
Chapter 21. Working with Images and Other Media
Loading Images
ImageObserver
MediaTracker
ImageIcon
ImageIO
Producing Image Data
Drawing Animations
BufferedImage Anatomy
Color Models
Creating an Image
Updating a BufferedImage
Filtering Image Data
How ImageProcessor Works
Converting an Image to a BufferedImage
Using the RescaleOp Class
Using the AffineTransformOp Class
Saving Image Data
Simple Audio
Java Media Framework
Chapter 22. JavaBeans
What’s a Bean?
What Constitutes a Bean?
The NetBeans IDE
Installing and Running NetBeans
Installing our example beans
Creating a project and file
The NetBeans workspace
Properties and Customizers
Event Hookups and Adapters
Taming the Juggler
Running the example
Molecular Motion
Binding Properties
Constraining Properties
Building Beans
The Dial Bean
Design Patterns for Properties
Generating bean patterns in NetBeans
Limitations of Visual Design
Serialization Versus Code Generation
Customizing with BeanInfo
Getting Properties Information
Getting events information
Supplying icons
Creating customizers and property editors
Handcoding with Beans
Bean Instantiation and Type Management
Working with Serialized Beans
Runtime Event Hookups with Reflection
How it works
BeanContext and BeanContextServices
The Java Activation Framework
Enterprise JavaBeans and POJO-Based Enterprise Frameworks
Chapter 23. Applets
The Politics of Browser-Based Applications
Applet Support and the Java Plug-in
The JApplet Class
Applet Lifecycle
The Applet Security Sandbox
Trusted applets
Getting Applet Resources
Applet parameters
Applet resources
Driving the browser
Inter-applet communication
Applet persistence and navigation
The <applet> Tag
Attributes
Parameters
¿Habla Applet?
The Complete <applet> Tag
Loading Class Files
Packages
appletviewer
Java Web Start
Conclusion
Chapter 24. XML
The Butler Did It
A Bit of Background
Text Versus Binary
A Universal Parser
The State of XML
The XML APIs
XML and Web Browsers
XML Basics
Attributes
XML Documents
Encoding
Namespaces
Validation
HTML to XHTML
SAX
The SAX API
JAXP
SAX’s strengths and weaknesses
Building a Model Using SAX
Creating the XML file
The model
The SAXModelBuilder
Test drive
Limitations and possibilities
XMLEncoder/Decoder
DOM
The DOM API
Test-Driving DOM
Generating XML with DOM
JDOM
XPath
Nodes
Predicates
Functions
The XPath API
XMLGrep
XInclude
Enabling XInclude
Validating Documents
Using Document Validation
DTDs
XML Schema
Simple types
Complex types
Generating Schema from XML samples
The Validation API
Alternative schema languages
JAXB Code Binding and Generation
Annotating Our Model
Unmarshalling from XML
Generating a Java Model from an XML Schema
Generating an XML Schema from a Java Model
Transforming Documents with XSL/XSLT
XSL Basics
Transforming the Zoo Inventory
XSLTransform
XSL in the Browser
Web Services
The End of the Book
Appendix A. The Eclipse IDE
The IDE Wars
Getting Started with Eclipse
Importing the Learning Java Examples
Using Eclipse
Getting at the Source
The Lay of the Land
Running the Examples
Building the Ant-Based Examples
Loner Examples
Eclipse Features
Coding Shortcuts
Autocorrection
Refactoring
Diffing Files
Organizing Imports
Formatting Source Code
Conclusion
Appendix B. BeanShell: Java Scripting
Running BeanShell
Java Statements and Expressions
Imports
BeanShell Commands
Scripted Methods and Objects
Scripting Interfaces and Adapters
Changing the Classpath
Learning More . . .
Glossary
Index
A note on the digital index
Symbols
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
About the Authors
Colophon
Special Upgrade Offer
Learning Java
Patrick Niemeyer
Daniel Leuck
Editor
Mike Loukides
Editor
Meghan Blanchette
← Prev
Back
Next →
← Prev
Back
Next →