Oc. OJ)
S
j6
-tu:
;:t
~ ~()i-<O
~e·o.
3:)coo
lDYf¥()
: It'
r
fo o.
Pro Java 8 Programming
••• Brett Spell
ApreSS
4I
Pro Java 8 Programming Copyright
Š
2015 by Brett Spell
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Exempted from this legal reservation are brief excerpts in connection with reviews or scholarly analysis or material supplied specifically for the purpose of being entered and executed on a computer system, for exclusive use by the purchaser of the work. Duplication of this publication or parts thereof is permitted only under the provisions of the Copyright Law of the Publisher's location, in its current version, and permission for use must always be obtained from Springer. Permissions for use may be obtained through RightsLink at the Copyright Clearance Center. Violations are liable to prosecution under the respective Copyright Law. ISBN-13(pbk): 978-1-4842-0642-3 ISBN-13(electronic): 978-1-4842-0641-6 Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an explfssion of opinion as to whether or not they are subject to proprietary rights. ~4?-, Jof
While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein.
02
Managing Director: Welmoed Spahr Lead Editor: Steve Anglin Technical Reviewer: Chad Darby Editorial Board: Steve Anglin, Louise Corrigan, Jonathan Gennick, Robert Hutchinson, Michelle Lowman, James Markham, Susan McDermott, Matthew Moodie, Jeffrey Pepper, Douglas Pundick, Ben Renew-Clarke, Gwenan Spearing, Steve Weiss Coordinating Editor: Mark Powers Copy Editor: Lori Jacobs ;~ Compositor: SPi Global Indexer: SPi Global Artist: SPi Global Cover Designer: Anna Ishchenko Distributed to the book trade worldwide by Springer Science-Business Media New York,233 Spring Street, 6th Floor,NewYork,NY10013.Phone 1-800-SPRINGER,fax (201) 348-4505,e-mail orders- ny@springer-sbm.com, or visit \Mo>I. springeronline. com.Apress Media, LLCis a California LLCand the sole member (owner) is Springer Science + Business Media Finance Inc (SSBMFinance Inc). SSBMFinance Inc is a Delaware corporation. For information on translations, please e-mail rights@apress.com,
or visit www.apress.com.
Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Special Bulk Sales-eBook Licensing web page at www.apress.com/bulk -sales. Any source code or other supplementary material referenced by the author in this text is available to readers at www.apress.com/9781484206423. For detailed information about how to locate your book's source code, go to www.apress.com/source- code/. .
RIBLIOTECA PARA ISO - UCR
0009635
1111111111111111111111111111111111111111
PA9S35
Contents About the Author About the Technical Reviewer
xxiii
xxv
Acknowledgments
xxvii
Introduction
xxix
IIChapter 1: Going Inside Java
1
Java's Architecture
2
The Java Virtual Machine
3
Different JVM Implementations
4
The JVM As a Runtime Execution Environment
5
The Runtime Data Areas of the JVM
6
The Garbage Collector
7
The JVM: Loading, Linking, and Initializing
8
Bytecode Execution
10
The Java Class File Format
12
The Java Programming Language and APls
14
The Java Programming Language
14
The Java APls
14
Java Utility Tools: Making the Most of the JVM
15
The Java Compiler
15
The Java Interpreter
16
The Java Class Disassembler
17
Summary
18
vii
CONTENTS
.Chapter
2: Designing Libraries, Classes, and Methods •••••••••••••••••••..•••••••••••••••••• 19
Library Design Package Design
Class Design
19 20
20
Loose Coupling
21
Strong Cohesion
35
Encapsulation
38
Immutable Objects
42
Overriding Object Methods
45
Method Design
51
Passing Parameters
53
Method Naming
55
Avoiding Code Duplication
56
Variable Arguments
58
Using Exceptions
59
Assertions
75
Enumerations
77
Summary .Chapter
80 3: Lambdas and Other Java 8 Features ••••.•.•...••••••••••••••••••••••••••••••••••••••• 81
Lambda Expression Concepts
81
Analyzing the Example
84
Functional Interface Methods
86
Default Methods
86
Multiple Inheritance Ambiguity
Streams
88
Optional
91
Parallel Streams
91
Improved DatefTime Handling In Java 8 DatelTime support Before Java 8
viii
87
92 92
¥ill CONTENTS
Date and Time API Basic Classes
:
94
~
94
Converting Date and Time Values
95
Parsing and Formatting
99
Method Naming Conventions
Summary
:
101
104
.Chapter 4: Using Threads in Your Applications .....•...•••••••••••••••••.•..........•.••••..... 105 Threading in Java
106
Creating Threads
107
Disadvantages of Using Threads
109
Slow Initial Startup
109
Resource Utilization
110
Increased Complexity
110
Sharing Resources
110
Thread Management
112
Understanding the Problem
116
Synchronizing the Use of Shared Resources
117
Nested Calls to Synchronized Methods and Code Blocks
120
Synchronized Blocks vs. Methods
120
Deadlocks
121
High-Level SynChronization
122
Lock Ordering
123
Thread Priorities
124
Daemon Threads
125
Adding Threads to an Application
127
Controlling Threads
135
Starting a Thread
138
Making a Thread "Sleep"
138
Suspending a Thread
142
ix
CONTENTS
Resuming a Thread
145
Stopping a Thread
146
Interrupting a Thread
147
Completing DownloadManager
149
Deprecated Methods in Thread
152
DownloadFiles
153
ThreadGroup
156
Uncaught Exceptions
159
Voluntarily Relinquishing the Processor
159
Concurrency Utilities
161
Summary
162
.Chapter
5: Using Stream APls and Collections
The Evolution of Collections
166
Java 2/Java 1.2
166
Java 5/Java 1.5
166
Java 7/Java 1.7
166
Collection Classes and Interfaces
x
163
167
Collection
167
List
172
Listlterator
176
ArrayList
176
LinkedList
178
Vector
178
Stack
179
Set
179
HashSet
183
Constructors
183
LinkedHashSet.
183
TreeSet.
183
l r. CONTENTS EnumSet
:
188
Map
189
HashMap
191
LinkedHashMap
192
TreeMap
192
EnumMap
192
IdentityHashMap
192
WeakHashMap
193
ConcurrentHashMap
194
CopyOnWriteArrayList
and CopyOnWriteArraySet.
195
Queue
195
PriorityQueue
196
PriorityBlockingQueue
196
ArrayBlockingQueue
196
LinkedBlockingQueue
197
ConcurrentLinkedQueue
197
SynchronousQueue
197
DelayQueue
197
Tips on Using Collections
198
Shallow vs. Deep Copies
199
Referencing an Interface Instead of an Implementation
200
Streams APi
201
Anatomy of a Stream
201
Intermediate Operation Pipelining
203
Some Other Intermediate Operation Methods
204
Terminal Operations
204
Parallel Streams
205
Summary
206
xi
CONTENTS
IIChapter 6: Using Layout Managers
207
Layout Managers and GUI Construction
207
CardLayout
210
Constructing a CardLayout
210
Child Component Sizes
211
Child Component Locations
211
Resizing Behavior
211
Container Size
211
FlowLayout Constructing a FlowLayout
212
Constraints
212
Child Component Sizes
212
Child Component Locations
212
Resizing Behavior
214
Container Size
215
GridLayout
216
Constructing a GridLayout
217
Constraints
219
Child Component Sizes
219
Child Component Locations
220
Resizing Behavior
220
Container Size
220
BorderLayout
xii
211
221
Constructing a BorderLayout
222
Constraints
222
Child Component Sizes
223
Child Component Locations
223
Resizing Behavior
224
Container Size
225
CONTENTS
GridBagLayout
~
225
Constructing a GridBagLayout
228
Constraints
228
Child Component Sizes
252
Child Component Locations
254
Resizing Behavior
254
Container Size
255
BoxLayout.
255
Alignment Values, Ascents, and Descents
256
Constructing a BoxLayout.
260
Constraints
261
Child Component Sizes
261
Child Component Locations
262
Resizing Behavior
263
Container Size
263
Swing's Box Class
263
Guidelines for Using Layout Managers
266
Combining Layout Managers
267
Absolute Positioning Without a Layout Manager
269
Invisible Components
270
Specifying an Index When Adding a Component
270
Creating Your Own Layout Manager
272
LayoutManager2 Methods
273
LayoutManager Methods
276
Using a Custom Layout Manager
280
Summary
280
xiii
CONTENTS
_Chapter 7: Using Swing's JTable
281
The Data Model
282
Using JScrollPane with JTable
286
JTable's Column-Oriented Design
289
Table Resizing
289
Column Resizing
290
AUTO_RESllE_OFF
291
AUTO_RESllE_NEXT _COLUMN
291
AUTO_RESllE_SUBSEQUENT_COLUMNS
291
AUTO_RESllE_LAST _COLUMN
292
AUTO_RESllE_ALL_COLUMNS
292
Cell Rendering
292
Creating Custom Renderers
293
JTable's Default Renderers
298
Editing Table Cells Cell Editors
Table Selection Settings
300 301
305
Combining Row, Column, and Cell Selection Modes
306
List Selection Modes
306
Selection Mode Combinations
308
Setting Selections Programmatically
310
Table Headers
311
Multiline Column Headers
312
Adding Table Header Tool Tips
313
Creating Row Headers
315
Sorting Table Rows
320
Adding and Removing Table Rows
321
Displaying a Particular Table Row
324
Summary
325
xiv
CONTENTS
IIChapter 8: Using Swing's JTree
327
JTree Terminology
328
Creating a JTree
329
TreeModel
332
Creating Tree Nodes
334
Nodes Without Children: Leaf or Branch?
336
MutableTreeNode
338
DefaultMutableTreeNode
340
Creating DefaultMutableTreeNode
Instances
340
Using DefaultMutableTreeNode
341
Obtaining a List of Nodes
343
TreePath
347
TreeModelListener
349
treeNodesChanged()
349
treeNodeslnserted()
349
treeNodesRemoved()
349
treeStructureChanged()
349
TreeModeIEvent
349
getTreePath(), getPath()
350
getChildren()
350
getChildlndices()
350
DefaultTreeModel
350
Rendering Tree Nodes
352
Creating a Custom Renderer
Editing Tree Nodes
354
359
DefaultTreeCeliEditor and DefaultCeliEditor
361
DefaultTreeCeliEditor Behavior
362
Creating a Custom Editor
362
Limiting Edits to Certain Nodes
365
xv
CONTENTS
Customizing Branch Node Handles
365
Line Style with the Java/Metal Look and FeeL
367
Node Selection
368
Selection Modes
369
TreeSelectionListener
372
TreeSelectionEvent
372
getPaths(), getPath()
373
isAddedPath()
373
getNewLeadSelectionPath(),
getOldLeadSelectionPath()
Selection Methods in JTree
373 373
Collapsing and Expanding Nodes
375
Detecting Collapses and Expansions
376
TreeExpansionListener
376
TreeWillExpandListener
376
Summary .Chapter
378 9: Adding Cut-and-Paste Functionality .••..•••••.•••••.••••••••••••••••••••••••••••••••••••• 379
Clipboards: Where Cut and Copied Data Is Stored
380
Using the System Clipboard
381
Using Clipboard
381
Using Transferable
381
Using ClipboardOwner
383
Using DataFlavor
384
Storing and Retrieving Serialized Java Objects
385
Transferring Between Java and Native Applications
396
Writing Arbitrary Binary Data
397
Summary
401
xvi
CONTENTS
.Chapter 10: Adding Drag-and-Drop Functionality
403
Introducing Drag-and-Drop Operation Types
404
Using the Predefined Cursors
405
Performing File Selection Drops from Native Applications
405
Adding Drop Support
405
Adding Drag Support
415
Performing Local Transfers
426
Performing Link/Reference Operations
430
Transferring Between Java and Native Applications
431
Transferring Text Data
432
Transferring Text Between Java and Native Applications
432
Creating a New Transferable for Text Data
434
Customizing Standard Component Behavior TransferHandler
Summary _Chapter 11: Printing Locating Print Services
436 436
448 449 450
DocFlavor
451
Choosing the Right Printer
453
AttributeSet
454
Attribute
454
Attribute Roles
455
Interfaces and Implementations
455
Printer Selection via User Interface
458
Creating a Print Job
459
Defining the Document to Print..
460
Initiating Printing
460
Monitoring and Controlling a Print Job
461
Monitoring Attribute Changes
461
Canceling a Print Job
463 xvii
CONTENTS
Introducing Service-Formatted
Printing
463
Support Classes
465
Sample Printing Application
469
Summary
IIChapter 12: Introducing JOBe
477
479
SOL Standards and JDBC Versions
480
JDBC Drivers
481
Driver Types
481
Obtaining a Database Connection
484
JDBC URL Formats
484
Connection
485
Obtaining Connections from a DataSource (2.x Optional Package)
485
DatabaseMetaData
486
Statement
494
ParameterMetaData
500
JDBC Data Types
500
ARRAy
502
BLOB, CLOB
503
DATALINK
503
DATE,TIME, TIMESTAMP
503
DISTINCT
504
STRUCT
504
REF
505
JAVA_OBJECT
505
OTHER
505
ResultSet
505
xviii
Forward-Only vs. Scroll able (Scrollability Type)
505
Read-Only vs. Updatable (Concurrency Mode)
506
Update Sensitivity
506
Holdability
506
Selecting ResultSet Properties
507
CONTENTS Performance Hints
:
507
Using ResultSet
508
ResultSetMetaData
511
RowSet
512
JdbcRowSet
512
CachedRowSet
513
Transactions
514
Savepoints
517
Read-Only Transactions
518
Connection Pooling
520
Pooling Properties
521
Errors and Warnings
522
SOLException
522
SOLWarning
525
Debugging
526
Releasing Resources
527
Summary
528
.Chapter 13: Internationalizing Your Applications ..•••••••..•••••..•••••..•••••••.••••..••••••• 529 Locales
530
Resource Bundles
532
Creating a ResourceBundle
Locale-Sensitive Formatting and Parsing
534
538
Formatting and Parsing Dates
539
Formatting and Parsing Times
542
Formatting and Parsing Numeric Values
543
MessageFormat.
545
Specifying a Locale
548
Specifying a Format Object
549
Choice Format
550
Using Formatter and String's formatO Method
552 xix
11 CONTENTS
Parsing Text Data
556
Breaklterator
556
Text Comparisons and Sorting
563
Collator Strength
564
Decomposition Mode
565
Internationalizing
an Application
566
Changing the Locale at Runtime
577
native2ascii
584
Summary
585
_Chapter 14: Using XML
587
XML vs. HTML
588
Describing the Data
590
Well-Formed Documents
590
When and Why to Use XML
593
Creating an XML Document.
595
Root Elements
596
Components of an XML Document
596
Parsing and Validation Parsing with the DOM Implementation
597 in JAXP
598
Text
610
EntityReference
613
DocumentFragment
613
DocumentType
613
Notation
615
Traversing a Document with DOM
615
Editing Documents with DOM
621
Creating and Adding New Nodes
623
Creating a New Document
625
Transforming XML Documents
xx
627
CONTENTS
Performing an XSL Transformation
628
Introducing XPath
629
Creating and Using Additional Templates
633
Summary IIChapter 15: Adding Annotations Using Annotations
635 637 638
Override
641
Functionallnterface
642
SuppressWarnings
642
Creating Custom Annotations
648
Target.
650
Retention
651
Documented
653
Inherited
655
Repeatable
657
Replacing External Metadata
657
Summary
661
Index
663
xxi
About the Author Brett SpeU has been programming professionally in Java since 1996 and
is a Sun-certified Java programmer, developer, and architect. Brett is the author of numerous articles on Java development and design patterns and he holds a bachelor's degree in Computer Science and a master's degree in Security Engineering. Brett has experience in wide a variety of industries and currently lives in Plano, Texas, with his wife, Shari, and daughters, Ashleigh and Kaitlin.
xxiii
)
About the Technical Reviewer Chad (shod) Darby is an author, instructor, and speaker in the Java
development world. As a recognized authority on Java applications and architectures, he has presented technical sessions at software development conferences worldwide (United States, UK, India, Russia, and Australia). In his 15years as a professional software architect, he's had the opportunity to work for Blue Cross/Blue Shield, Merck, Boeing, Red Hat, and a handful of startup companies. Chad is a contributing author to several Java books, induding Professional Java E-Commerce (Wrox Press), Beginning Java Networking (Wrox Press), andXML and Web Services Unleashed (Sams Publishing). Chad has Java certifications from Sun Microsystems and IBM. He holds a B.S.in Computer Science from Carnegie Mellon University. Visit Chad's blog at www.luv2code.com to view his free video tutorials on Java. You can also follow him on Twitter@darbyluvs2code.
xxv
Acknowledgments Writing or even updating a book is a grueling task, but the other folks involved in this effort did a great job of minimizing the pain involved in updating this title. I'd like to thank everyone involved, especially Mark Powers, Steve Anglin, and Matthew Moodie at Apress along with ChadDarby who did an excellent job of reviewing the material and providing helpful feedback.
xxvii
Introduction It's been a while since I last revised this material and even longer than that since the first edition was published. In that time the technologies that Java programmers use have changed quite a bit and there's no doubt that if I were writing this book for the first time I would do some things differently. For example, I'd place more of an emphasis on technologies related to web development to reflect the dominance that it has in the industry today. Even so, it's a little surprising to find out how relevant most of the original material still is, and I hope that you'll find both the principles and specific technology topics covered here useful in learning how to program in Java.
xxix
CHAPTER 1
••• Going Inside Java Javahas been described as "a simple, robust, object-oriented, platform-independent, multithreaded, dynamic, general-purpose programming environment:' Living up to this definition allowed Java to grow and expand into so many niches that it's almost unrecognizable from its earliest days. Today you can find Javajust about anywhere you can find a microprocessor. It's used in the largest of enterprises to the smallest of devices, and it's used in devices from cell phones to supercooled mainframes. For Java to support such a wide range of environments, an almost bewildering array of application programming interfaces (APIs) and versions have been developed, though they're built around a common set of core classes. In order to become a good Java programmer, it's important to be able to do the basics well. Being able to produce a highly complex user interface is all very well, but if your code is bloated, memory hungry, and inefficient, your users won't be happy. This book isn't about the huge array of development options available to you as a Java developer but about how to do the common tasks that as a Java developer you'll encounter again and again. Over the course of the book, we'll examine some of the core language features, such as threading and memory management, that can really make the difference in a professional-quality Java application. At the core of Iava's adaptability, and hence popularity, is that it's platform-independent. Its "write once, run anywhere" (WORA)capability stems from the way Java itself operates and in particular from the use of an abstract execution environment that allows Java code to be separated from the underlying operating system. Whereas the rest of this book will be about exploring the programming language and APIs of Java,in this chapter we'll look at the foundations of how Java really operates under the hood, with the Java Virtual Machine (NM). Understanding the inner workings of Java will give you as a programmer a better understanding of the language, which should make you a better programmer. In this chapter, we'll cover the following: •
The various components of the Java platform
•
How the NM allows Java to be platform-independent
•
What happens when you run a Java program
•
What a Java class file really contains
•
The key tools needed to work with a NM
First, then, let's look at what Java actually is.