Tải bản đầy đủ (.pdf) (1,010 trang)

learning java, 4th edition

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (24.55 MB, 1,010 trang )

www.it-ebooks.info
www.it-ebooks.info
Patrick Niemeyer and Daniel Leuck
FOURTH EDITION
Learning Java
www.it-ebooks.info
Learning Java, Fourth Edition
by Patrick Niemeyer and Daniel Leuck
Copyright © 2013 Patrick Niemeyer, Daniel Leuck. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are
also available for most titles (). For more information, contact our corporate/
institutional sales department: 800-998-9938 or
Editors: Mike Loukides and Meghan Blanchette
Production Editor: Rachel Steely
Copyeditor: Gillian McGarvey
Proofreader: Rachel Monaghan
Indexer: BIM Publishing Services, Inc.
Cover Designer: Randy Comer
Interior Designer: David Futato
Illustrators: Robert Romano and Rebecca Demarest
June 2013:
Fourth Edition
Revision History for the Fourth Edition:
2013-06-06: First release
See for release details.
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly
Media, Inc. Learning Java, Fourth Edition, the image of a Bengal tigress and her cubs, and related trade dress
are trademarks of O’Reilly Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as


trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trade‐
mark claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and authors assume
no responsibility for errors or omissions, or for damages resulting from the use of the information contained
herein.
ISBN: 978-1-449-31924-3
[LSI]
www.it-ebooks.info
Table of Contents
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxi
1.
A Modern Language. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Enter Java 2
Java’s Origins 2
Growing Up 3
A Virtual Machine 4
Java Compared with Other Languages 7
Safety of Design 10
Simplify, Simplify, Simplify 10
Type Safety and Method Binding 11
Incremental Development 12
Dynamic Memory Management 13
Error Handling 14
Threads 14
Scalability 15
Safety of Implementation 15
The Verifier 17
Class Loaders 18
Security Managers 19
Application and User-Level Security 19

A Java Road Map 20
The Past: Java 1.0–Java 1.6 20
The Present: Java 7 21
The Future 23
Availability 23
2. A First Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Java Tools and Environment 25
iii
www.it-ebooks.info
Configuring Eclipse and Creating a Project 26
Importing the Learning Java Examples 28
HelloJava 29
Classes 32
The main() Method 33
Classes and Objects 34
Variables and Class Types 34
HelloComponent 35
Inheritance 36
The JComponent Class 37
Relationships and Finger Pointing 38
Package and Imports 39
The paintComponent() Method 40
HelloJava2: The Sequel 41
Instance Variables 43
Constructors 44
Events 45
The repaint() Method 47
Interfaces 48
HelloJava3: The Button Strikes! 49
Method Overloading 51

Components 52
Containers 52
Layout 53
Subclassing and Subtypes 54
More Events and Interfaces 54
Color Commentary 55
Static Members 55
Arrays 56
Our Color Methods 56
HelloJava4: Netscape’s Revenge 58
Threads 60
The Thread Class 61
The Runnable Interface 61
Starting the Thread 62
Running Code in the Thread 62
Exceptions 63
Synchronization 64
3.
Tools of the Trade. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
JDK Environment 67
The Java VM 68
iv | Table of Contents
www.it-ebooks.info
Running Java Applications 68
System Properties 70
The Classpath 70
javap 72
The Java Compiler 72
JAR Files 74
File Compression 74

The jar Utility 75
The pack200 Utility 78
Policy Files 78
The Default Security Manager 79
The policytool Utility 79
Using a Policy File with the Default Security Manager 81
4.
The Java Language. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
Text Encoding 83
Comments 84
Javadoc Comments 85
Types 86
Primitive Types 87
Reference Types 91
A Word About Strings 93
Statements and Expressions 93
Statements 94
Expressions 100
Exceptions 104
Exceptions and Error Classes 105
Exception Handling 107
Bubbling Up 109
Stack Traces 110
Checked and Unchecked Exceptions 111
Throwing Exceptions 112
try Creep 115
The finally Clause 116
Try with Resources 117
Performance Issues 119
Assertions 119

Enabling and Disabling Assertions 120
Using Assertions 121
Arrays 122
Array Types 123
Array Creation and Initialization 123
Table of Contents | v
www.it-ebooks.info
Using Arrays 125
Anonymous Arrays 127
Multidimensional Arrays 127
Inside Arrays 129
5. Objects in Java. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
Classes 132
Accessing Fields and Methods 133
Static Members 135
Methods 138
Local Variables 139
Shadowing 139
Static Methods 140
Initializing Local Variables 141
Argument Passing and References 142
Wrappers for Primitive Types 144
Autoboxing and Unboxing of Primitives 146
Variable-Length Argument Lists 147
Method Overloading 148
Object Creation 149
Constructors 150
Working with Overloaded Constructors 151
Static and Nonstatic Initializer Blocks 153
Object Destruction 154

Garbage Collection 154
Finalization 155
Weak and Soft References 155
Enumerations 156
Enum Values 158
Customizing Enumerations 158
6.
Relationships Among Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
Subclassing and Inheritance 161
Shadowed Variables 163
Overriding Methods 165
Special References: this and super 172
Casting 172
Using Superclass Constructors 174
Full Disclosure: Constructors and Initialization 175
Abstract Methods and Classes 176
Interfaces 177
Interfaces as Callbacks 179
vi | Table of Contents
www.it-ebooks.info
Interface Variables 180
Subinterfaces 181
Packages and Compilation Units 182
Compilation Units 182
Package Names 183
Class Visibility 183
Importing Classes 184
Visibility of Variables and Methods 186
Basic Access Modifiers 186
Subclasses and Visibility 188

Interfaces and Visibility 189
Arrays and the Class Hierarchy 189
ArrayStoreException 190
Inner Classes 190
Inner Classes as Adapters 192
Inner Classes Within Methods 194
7. Working with Objects and Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
The Object Class 201
Equality and Equivalence 202
Hashcodes 203
Cloning Objects 203
The Class Class 206
Reflection 208
Modifiers and Security 211
Accessing Fields 212
Accessing Methods 213
Accessing Constructors 215
What About Arrays? 216
Accessing Generic Type Information 216
Accessing Annotation Data 217
Dynamic Interface Adapters 217
What Is Reflection Good For? 218
Annotations 219
Using Annotations 220
Standard Annotations 221
The apt Tool 222
8.
Generics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
Containers: Building a Better Mousetrap 224
Can Containers Be Fixed? 224

Enter Generics 225
Table of Contents | vii
www.it-ebooks.info
Talking About Types 228
“There Is No Spoon” 229
Erasure 230
Raw Types 231
Parameterized Type Relationships 232
Why Isn’t a List<Date> a List<Object>? 234
Casts 235
Writing Generic Classes 236
The Type Variable 236
Subclassing Generics 237
Exceptions and Generics 238
Parameter Type Limitations 239
Bounds 240
Erasure and Bounds (Working with Legacy Code) 241
Wildcards 242
A Supertype of All Instantiations 243
Bounded Wildcards 243
Thinking Outside the Container 243
Lower Bounds 244
Reading, Writing, and Arithmetic 245
<?>, <Object>, and the Raw Type 247
Wildcard Type Relationships 247
Generic Methods 248
Generic Methods Introduced 249
Type Inference from Arguments 250
Type Inference from Assignment Context 251
Explicit Type Invocation 252

Wildcard Capture 252
Wildcard Types Versus Generic Methods 253
Arrays of Parameterized Types 253
Using Array Types 254
What Good Are Arrays of Generic Types? 255
Wildcards in Array Types 255
Case Study: The Enum Class 256
Case Study: The sort() Method 257
Conclusion 258
9.
Threads. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
Introducing Threads 260
The Thread Class and the Runnable Interface 261
Controlling Threads 265
Death of a Thread 267
viii | Table of Contents
www.it-ebooks.info
Threading an Applet 268
Issues Lurking 270
Synchronization 271
Serializing Access to Methods 272
Accessing class and instance Variables from Multiple Threads 274
The wait() and notify() Methods 275
Passing Messages 277
ThreadLocal Objects 281
Scheduling and Priority 282
Thread State 283
Time-Slicing 284
Priorities 285
Yielding 285

Thread Groups 286
Working with ThreadGroups 287
Uncaught Exceptions 287
Thread Performance 288
The Cost of Synchronization 288
Thread Resource Consumption 289
Concurrency Utilities 289
Executors 291
Locks 303
Synchronization Constructs 306
Atomic Operations 311
Conclusion 313
10.
Working with Text. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
Text-Related APIs 316
Strings 316
Constructing Strings 317
Strings from Things 318
Comparing Strings 319
Searching 321
Editing 322
String Method Summary 322
StringBuilder and StringBuffer 323
Internationalization 325
The java.util.Locale Class 325
Resource Bundles 326
Parsing and Formatting Text 328
Parsing Primitive Numbers 328
Tokenizing Text 330
Table of Contents | ix

www.it-ebooks.info
Printf-Style Formatting 332
Formatter 333
The Format String 333
String Conversions 334
Primitive and Numeric Conversions 336
Flags 337
Miscellaneous 338
Formatting with the java.text Package 338
MessageFormat 340
Regular Expressions 342
Regex Notation 342
The java.util.regex API 352
11. Core Utilities. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
Math Utilities 359
The java.lang.Math Class 360
Big/Precise Numbers 361
Floating-Point Components 362
Random Numbers 363
Dates and Times 364
Working with Calendars 365
Time Zones 366
Parsing and Formatting with DateFormat 368
Printf-Style Date and Time Formatting 370
Timers 371
Collections 373
The Collection Interface 374
Iterator 376
Collection Types 378
The Map Interface 380

Collection Implementations 382
Hash Codes and Key Values 387
Synchronized and Unsynchronized Collections 388
Read-Only and Read-Mostly Collections 390
WeakHashMap 390
EnumSet and EnumMap 390
Sorting Collections 391
A Thrilling Example 392
Properties 393
Loading and Storing 394
System Properties 395
The Preferences API 396
x | Table of Contents
www.it-ebooks.info
Preferences for Classes 397
Preferences Storage
398
Change Notification 398
The Logging API 399
Overview 399
Logging Levels 401
A Simple Example 402
Logging Setup Properties 403
The Logger 405
Performance 406
Observers and Observables 406
12. Input/Output Facilities. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
Streams
409
Basic I/O 412

Character Streams 415
Stream Wrappers 416
Pipes 420
Streams from Strings and Back 422
Implementing a Filter Stream 423
File I/O 425
The java.io.File Class 425
File Streams 430
RandomAccessFile 433
Resource Paths 434
The NIO File API 436
FileSystem and Path 436
NIO File Operations 438
Directory Operations 441
Watching Paths 443
Serialization 444
Initialization with readObject() 446
SerialVersionUID 447
Data Compression 448
Archives and Compressed Data 448
Decompressing Data 450
Zip Archive As a Filesystem 452
The NIO Package 453
Asynchronous I/O 453
Performance 454
Mapped and Locked Files 454
Channels 454
Table of Contents | xi
www.it-ebooks.info
Buffers 455

Character Encoders and Decoders 459
FileChannel 461
Scalable I/O with NIO 467
13. Network Programming. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469
Sockets 471
Clients and Servers 472
The DateAtHost Client 477
The TinyHttpd Server 478
Socket Options 482
Proxies and Firewalls 484
Datagram Sockets 486
The HeartBeat Applet 487
InetAddress 491
Simple Serialized Object Protocols 491
A Simple Object-Based Server 492
Remote Method Invocation 496
Real-World Usage 497
Remote and Nonremote Objects 497
An RMI Example 500
RMI and CORBA 508
Scalable I/O with NIO 509
Selectable Channels 509
Using Select 510
LargerHttpd 512
Nonblocking Client-Side Operations 517
14.
Programming for the Web. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519
Uniform Resource Locators (URLs) 519
The URL Class 520
Stream Data 521

Getting the Content as an Object 522
Managing Connections 523
Handlers in Practice 524
Useful Handler Frameworks 524
Talking to Web Applications 525
Using the GET Method 526
Using the POST Method 527
The HttpURLConnection 530
SSL and Secure Web Communications 530
URLs, URNs, and URIs 530
xii | Table of Contents
www.it-ebooks.info
Web Services 531
XML-RPC 532
WSDL 532
The Tools 532
The Weather Service Client 533
15. Web Applications and Web Services. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535
Web Application Technologies 536
Page-Oriented Versus “Single Page” Applications 536
JSPs 537
XML and XSL 538
Web Application Frameworks 538
Google Web Toolkit 539
HTML5, AJAX, and More 539
Java Web Applications 539
The Servlet Lifecycle 540
Servlets 541
The HelloClient Servlet 542
The Servlet Response 544

Servlet Parameters 545
The ShowParameters Servlet 546
User Session Management 548
The ShowSession Servlet 548
The ShoppingCart Servlet 550
Cookies 553
The ServletContext API 554
Asynchronous Servlets 555
WAR Files and Deployment 559
Configuration with web.xml and Annotations 560
URL Pattern Mappings 562
Deploying HelloClient 563
Error and Index Pages 564
Security and Authentication 566
Protecting Resources with Roles 566
Secure Data Transport 568
Authenticating Users 569
Procedural Authorization 570
Servlet Filters 571
A Simple Filter 572
A Test Servlet 573
Declaring and Mapping Filters 574
Filtering the Servlet Request 575
Table of Contents | xiii
www.it-ebooks.info
Filtering the Servlet Response 577
Building WAR Files with Ant 580
A Development-Oriented Directory Layout 581
Deploying and Redeploying WARs with Ant 582
Implementing Web Services 582

Defining the Service 583
Our Echo Service 584
Using the Service 585
Data Types 587
Conclusion 588
16.
Swing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589
Components 592
Peers and Look-and-Feel 594
The MVC Framework 595
Painting 596
Enabling and Disabling Components 597
Focus, Please 598
Other Component Methods 598
Layout Managers 600
Insets 601
Z-Ordering (Stacking Components) 601
The revalidate() and doLayout() Methods 601
Managing Components 602
Listening for Components 602
Windows, Frames and Splash Screens 602
Other Methods for Controlling Frames 604
Content Panes 605
Desktop Integration 605
Events 607
Event Receivers and Listener Interfaces 608
Event Sources 610
Event Delivery 611
Event Types 612
The java.awt.event.InputEvent Class 613

Mouse and Key Modifiers on InputEvents 613
Focus Events 614
Event Summary 616
Adapter Classes 619
Dummy Adapters 622
The AWT Robot! 623
xiv | Table of Contents
www.it-ebooks.info
Multithreading in Swing 623
17. Using Swing Components. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 627
Buttons and Labels 627
HTML Text in Buttons and Labels 630
Checkboxes and Radio Buttons 631
Lists and Combo Boxes 634
The Spinner 637
Borders 639
Menus 642
Pop-Up Menus 646
Component-Managed Pop Ups 648
The JScrollPane Class 650
The JSplitPane Class 652
The JTabbedPane Class 653
Scrollbars and Sliders 657
Dialogs 659
File Selection Dialog 662
The Color Chooser 664
18.
More Swing Components. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667
Text Components 667
The TextEntryBox Application 668

Formatted Text 670
Filtering Input 671
Validating Data 673
Say the Magic Word 674
Sharing a Data Model 675
HTML and RTF for Free 677
Managing Text Yourself 680
Focus Navigation 682
Trees 684
Nodes and Models 684
Save a Tree 685
Tree Events 685
A Complete Example 686
Tables 688
A First Stab: Freeloading 688
Round Two: Creating a Table Model 690
Round Three: A Simple Spreadsheet 693
Sorting and Filtering 697
Printing JTables 699
Table of Contents | xv
www.it-ebooks.info
Desktops 699
Pluggable Look-and-Feel 701
Creating Custom Components 704
Generating Events 704
A Dial Component 704
Model and View Separation 708
19.
Layout Managers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 709
FlowLayout 711

GridLayout 712
BorderLayout 713
BoxLayout 716
CardLayout 717
GridBagLayout 719
The GridBagConstraints Class 719
Grid Coordinates 721
The fill Constraint 722
Spanning Rows and Columns 724
Weighting 725
Anchoring 728
Padding and Insets 728
Relative Positioning 730
Composite Layouts 731
Other Layout Managers 734
Absolute Positioning 735
20.
Drawing with the 2D API. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 737
The Big Picture 737
The Rendering Pipeline 739
A Quick Tour of Java 2D 742
Filling Shapes 742
Drawing Shape Outlines 742
Convenience Methods 743
Drawing Text 744
Drawing Images 744
The Whole Iguana 745
Filling Shapes 748
Solid Colors 748
Color Gradients 749

Textures 749
Desktop Colors 749
Stroking Shape Outlines 750
xvi | Table of Contents
www.it-ebooks.info
Using Fonts 751
Font Metrics 752
Displaying Images 756
The Image Class 756
Image Observers 758
Scaling and Size 759
Drawing Techniques 760
Double Buffering 763
Limiting Drawing with Clipping 764
Offscreen Drawing 766
Printing 769
21. Working with Images and Other Media. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 771
Loading Images 772
ImageObserver 773
MediaTracker 775
ImageIcon 777
ImageIO 777
Producing Image Data 778
Drawing Animations 779
BufferedImage Anatomy 782
Color Models 783
Creating an Image 784
Updating a BufferedImage 786
Filtering Image Data 790
How ImageProcessor Works 792

Converting an Image to a BufferedImage 793
Using the RescaleOp Class 793
Using the AffineTransformOp Class 793
Saving Image Data 794
Simple Audio 795
Java Media Framework 796
22.
JavaBeans. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 799
What’s a Bean? 799
What Constitutes a Bean? 801
The NetBeans IDE 801
Installing and Running NetBeans 802
Properties and Customizers 805
Event Hookups and Adapters 807
Taming the Juggler 808
Molecular Motion 810
Table of Contents | xvii
www.it-ebooks.info
Binding Properties 811
Constraining Properties 812
Building Beans 813
The Dial Bean 813
Design Patterns for Properties 816
Limitations of Visual Design 817
Serialization Versus Code Generation 818
Customizing with BeanInfo 819
Getting Properties Information 819
Handcoding with Beans 822
Bean Instantiation and Type Management 823
Working with Serialized Beans 823

Runtime Event Hookups with Reflection 825
BeanContext and BeanContextServices 827
The Java Activation Framework 828
Enterprise JavaBeans and POJO-Based Enterprise Frameworks 828
23. Applets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 831
The Politics of Browser-Based Applications 831
Applet Support and the Java Plug-in 833
The JApplet Class 833
Applet Lifecycle 834
The Applet Security Sandbox 837
Getting Applet Resources 838
The <applet> Tag 842
Attributes 843
Parameters 843
¿Habla Applet? 844
The Complete <applet> Tag 844
Loading Class Files 846
Packages 846
appletviewer 847
Java Web Start 847
Conclusion 848
24.
XML. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 849
The Butler Did It 849
A Bit of Background 850
Text Versus Binary 851
A Universal Parser 851
The State of XML 851
The XML APIs 852
xviii | Table of Contents

www.it-ebooks.info
XML and Web Browsers 852
XML Basics 852
Attributes 853
XML Documents 854
Encoding 854
Namespaces 855
Validation 856
HTML to XHTML 856
SAX 856
The SAX API 857
Building a Model Using SAX 858
XMLEncoder/Decoder 864
DOM 865
The DOM API 865
Test-Driving DOM 866
Generating XML with DOM 868
JDOM 869
XPath 869
Nodes 870
Predicates 871
Functions 871
The XPath API 872
XMLGrep 873
XInclude 874
Enabling XInclude 875
Validating Documents 876
Using Document Validation 876
DTDs 877
XML Schema 879

The Validation API 883
JAXB Code Binding and Generation 885
Annotating Our Model 885
Generating a Java Model from an XML Schema 890
Generating an XML Schema from a Java Model 891
Transforming Documents with XSL/XSLT 891
XSL Basics 892
Transforming the Zoo Inventory 894
XSLTransform 896
XSL in the Browser 897
Web Services 897
Table of Contents | xix
www.it-ebooks.info
The End of the Book 898
A. The Eclipse IDE. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 899
B. BeanShell: Java Scripting. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 911
Glossary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 917
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 931
xx | Table of Contents
www.it-ebooks.info
Preface
This book is about the J
ava programming language and environment. Whether you are
a software developer or just someone who uses the Internet in your daily life, you’ve
undoubtedly heard about Java. Its introduction was one of the most exciting develop‐
ments in the history of the Web and Java applications have powered much of the growth
of business on the Internet in the past 15 years. Java is, arguably, the most popular
programming language in the world, used by millions of developers on almost every
kind of computer imaginable. In the past decade, Java has surpassed languages such as
C++ and Visual Basic in terms of developer demand and has become the de facto lan‐

guage for certain kinds of development—especially for web-based services. Most uni‐
versities are now using Java in their introductory courses alongside the other important
modern languages. Perhaps you are using this text in one of your classes right now!
This book gives you a thorough grounding in Java fundamentals and APIs. Learning
Java, Fourth Edition, attempts to live up to its name by mapping out the Java language
and its class libraries, programming techniques, and idioms. We’ll dig deep into inter‐
esting areas and at least scratch the surface of the rest. Other titles from O’Reilly pick
up where we leave off and provide more comprehensive information on specific areas
and applications of Java.
Whenever possible, we provide compelling, realistic, and fun examples and avoid mere‐
ly cataloging features. The examples are simple, but hint at what can be done. We won’t
be developing the next great “killer app” in these pages, but we hope to give you a starting
point for many hours of experimentation and inspired tinkering that will lead you to
develop one yourself.
Who Should Read This Book
This book is for computer professionals, students, technical people, and Finnish hack‐
ers. It’s for everyone who has a need for hands-on experience with the Java language
with an eye toward building real applications. This book could also be considered a
xxi
www.it-ebooks.info
crash course in object-oriented programming, networking, GUIs, and XML. As you
learn about Java, you’ll also learn a powerful and practical approach to software devel‐
opment, beginning with a deep understanding of the fundamentals of Java and its APIs.
Superficially, Java looks like C or C++, so you’ll have a tiny head start in using this book
if you have some experience with one of these languages. If you do not, don’t worry.
Don’t make too much of the syntactic similarities between Java and C or C++. In many
respects, Java acts like more dynamic languages such as Smalltalk and Lisp. Knowledge
of another object-oriented programming language should certainly help, although you
may have to change some ideas and unlearn a few habits. Java is considerably simpler
than languages such as C++ and Smalltalk. If you learn well from concise examples and

personal experimentation, we think you’ll like this book.
The last part of this book branches out to discuss Java in the context of web applications,
web services, and XML processing, so you should be familiar with the basic ideas behind
web browsers, servers, and documents.
New Developments
This edition of Learning Java is actually the sixth edition—updated and retitled—of our
original, popular Exploring Java. With each edition, we’ve taken great care not only to
add new material covering additional features, but to thoroughly revise and update the
existing content to synthesize the coverage and add years of real-world perspective and
experience to these pages.
One noticeable change in recent editions is that we’ve deemphasized the use of applets,
reflecting their diminished role in recent years in creating interactive web pages. In
contrast, we’ve greatly expanded our coverage of Java web applications, web services,
and XML, which are now mature technologies.
We cover all of the important features of the latest release of Java, officially called Java
Standard Edition (SE) 7, JDK 1.7. Sun (Java’s keeper before Oracle) has changed the
naming scheme many times over the years. Sun coined the term Java 2 to cover the
major new features introduced in Java version 1.2 and dropped the term JDK in favor
of SDK. With the sixth release, Sun skipped from Java version 1.4 to Java 5.0, but re‐
prieved the term JDK and kept its numbering convention there. After that, we had Java
6 and now we reach Java 7.
This release of Java reflects a mature language with relatively few syntactic changes but
significant updates to APIs and libraries. We’ve tried to capture these new features and
update every example in this book to reflect not only the current Java practice, but style
as well.
xxii | Preface
www.it-ebooks.info
New in This Edition (Java 6 and 7)
This edition of the book has been significantly reworked to be as complete and up-to-
date as possible. It incorporates changes from both the Java 6 and Java 7 releases that

occurred since the last edition of this book. New topics in this edition include:

New language features, including type inference in generics and improved excep‐
tion handling and automatic resource management syntax

New concurrency utilities including the Fork-Join framework

The new NIO Files API, which allows new types of filesystem access to be imple‐
mented in Java
• New versions of the Java Servlets (3.0) and web services APIs, including use of the
new annotations-based deployment and built-in web service container
• New version of JAXB (2.2) Java XML Binding, including use of the new annotations
for binding Java to XML
• Improved Swing desktop integration and enhancements to key Swing components
such as JTable
• Updated examples and analysis throughout the book
Using This Book
This book is organized roughly as follows:

Chapters 1 and 2 provide a basic introduction to Java concepts and a tutorial to give
you a jump start on Java programming.

Chapter 3 discusses fundamental tools for developing with Java (the compiler, the
interpreter, and the JAR file package).

Chapters 4 through 7 describe the Java language itself, beginning with the basic
syntax and then covering classes and objects, exceptions, arrays, enumerations,
annotations, and much more.

Chapter 8 covers generics and parameterized types in Java.


Chapter 9 covers the language’s built-in thread facilities and the Java Concurrency
package, which should be of particular interest to advanced programmers.

Chapter 10 covers text processing, formatting, scanning, string utilities, and the
powerful regular expressions API.

Chapter 11 covers much of the core API including utilities and collections.

Chapter 12 covers Java I/O, streams, files, and the NIO package.
Preface | xxiii
www.it-ebooks.info

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×