Part III Software Development Using Java28 Java Beans.. 842 Part III Software Development Using Java 28 Java Beans.. Java’s ability to accommodate the fast rate of change in the computin
Trang 2The Complete Reference,
Seventh Edition
Trang 3Herbert Schildtis a leading authority on theJava, C, C++, and C# languages, and is a masterWindows programmer His programming bookshave sold more than 3.5 million copies worldwideand have been translated into all major foreignlanguages He is the author of the best-selling
The Art of Java, Java: A Beginner’s Guide, and Swing: A Beginner’s Guide Among his other bestsellers are C++: The Complete Reference, C++:
A Beginner’s Guide, C#: The Complete Reference, and C#: A Beginner’s Guide Schildt holds both graduate
and undergraduate degrees from the University
of Illinois He can be reached at his consultingoffice at (217) 586-4683 His Web site is
www.HerbSchildt.com
Trang 4Java : The Complete Reference,
Trang 5ISBN: 978-0-07-163177-8
MHID: 0-07-163177-1
The material in this eBook also appears in the print version of this title: ISBN: 978-0-07-226385-5,
MHID: 0-07-226385-7.
All trademarks are trademarks of their respective owners Rather than put a trademark symbol after every occurrence of a trademarked name,
we use names in an editorial fashion only, and to the benefi t of the trademark owner, with no intention of infringement of the trademark Where such designations appear in this book, they have been printed with initial caps.
McGraw-Hill eBooks are available at special quantity discounts to use as premiums and sales promotions, or for use in corporate training programs To contact a representative please e-mail us at bulksales@mcgraw-hill.com.
Information has been obtained by McGraw-Hill from sources believed to be reliable However, because of the possibility of human or mechanical error by our sources, McGraw-Hill, or others, McGraw-Hill does not guarantee the accuracy, adequacy, or completeness of any information and is not responsible for any errors or omissions or the results obtained from the use of such information.
TERMS OF USE
This is a copyrighted work and The McGraw-Hill Companies, Inc (“McGrawHill”) and its licensors reserve all rights in and to the work Use
of this work is subject to these terms Except as permitted under the Copyright Act of 1976 and the right to store and retrieve one copy of the work, you may not decompile, disassemble, reverse engineer, reproduce, modify, create derivative works based upon, transmit, distribute, disseminate, sell, publish or sublicense the work or any part of it without McGraw-Hill’s prior consent You may use the work for your own noncommercial and personal use; any other use of the work is strictly prohibited Your right to use the work may be terminated if you fail to comply with these terms.
THE WORK IS PROVIDED “AS IS.” McGRAW-HILL AND ITS LICENSORS MAKE NO GUARANTEES OR WARRANTIES AS
TO THE ACCURACY, ADEQUACY OR COMPLETENESS OF OR RESULTS TO BE OBTAINED FROM USING THE WORK, INCLUDING ANY INFORMATION THAT CAN BE ACCESSED THROUGH THE WORK VIA HYPERLINK OR OTHERWISE, AND EXPRESSLY DISCLAIM ANY WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE McGraw-Hill and its licensors do not warrant or guarantee that the functions contained in the work will meet your requirements or that its operation will be uninterrupted or error free Neither McGraw-Hill nor its licensors shall be liable to you or anyone else for any inaccuracy, error or omission, regardless of cause, in the work or for any damages resulting therefrom McGraw-Hill has no responsibility for the content of any information accessed through the work Under no circumstances shall McGraw-Hill and/or its licensors be liable for any indirect, incidental, special, punitive, consequential or similar damages that result from the use of or inability to use the work, even if any of them has been advised of the possibility of such damages This limitation of liability shall apply to any claim or cause whatsoever whether such claim or cause arises in contract, tort or otherwise.
Trang 6Part I The Java Language
1 The History and Evolution of Java 3
2 An Overview of Java 15
3 Data Types, Variables, and Arrays 33
4 Operators 57
5 Control Statements 77
6 Introducing Classes 105
7 A Closer Look at Methods and Classes 125
8 Inheritance 157
9 Packages and Interfaces 183
10 Exception Handling 205
11 Multithreaded Programming 223
12 Enumerations, Autoboxing, and Annotations (Metadata) 255
13 I/O, Applets, and Other Topics 285
14 Generics 315
Part II The Java Library 15 String Handling 359
16 Exploring java.lang 385
17 java.util Part 1: The Collections Framework 437
18 java.util Part 2: More Utility Classes 503
19 Input/Output: Exploring java.io 555
20 Networking 599
21 The Applet Class 617
22 Event Handling 637
23 Introducing the AWT: Working with Windows, Graphics, and Text 663
24 Using AWT Controls, Layout Managers, and Menus 701
25 Images 755
26 The Concurrency Utilities 787
27 NIO, Regular Expressions, and Other Packages 813
Trang 7Part III Software Development Using Java
28 Java Beans 847
29 Introducing Swing 859
30 Exploring Swing 879
31 Servlets 907
Part IV Applying Java 32 Financial Applets and Servlets 931
33 Creating a Download Manager in Java 965
A Using Java’s Documentation Comments 991
Index 997
Trang 8Preface xxix
Part I The Java Language 1 The History and Evolution of Java 3
Java’s Lineage 3
The Birth of Modern Programming: C 4
C++: The Next Step 5
The Stage Is Set for Java 6
The Creation of Java 6
The C# Connection 8
How Java Changed the Internet 8
Java Applets 8
Security 9
Portability 9
Java’s Magic: The Bytecode 9
Servlets: Java on the Server Side 10
The Java Buzzwords 10
Simple 11
Object-Oriented 11
Robust 11
Multithreaded 12
Architecture-Neutral 12
Interpreted and High Performance 12
Distributed 12
Dynamic 13
The Evolution of Java 13
Java SE 6 14
A Culture of Innovation 14
2 An Overview of Java 15
Object-Oriented Programming 15
Two Paradigms 15
Abstraction 16
The Three OOP Principles 16
A First Simple Program 21
Entering the Program 21
Compiling the Program 22
A Closer Look at the First Sample Program 22
Trang 9A Second Short Program 24
Two Control Statements 26
The if Statement 26
The for Loop 27
Using Blocks of Code 29
Lexical Issues 30
Whitespace 30
Identifiers 30
Literals 31
Comments 31
Separators 31
The Java Keywords 31
The Java Class Libraries 32
3 Data Types, Variables, and Arrays 33
Java Is a Strongly Typed Language 33
The Primitive Types 33
Integers 34
byte 35
short 35
int 35
long 35
Floating-Point Types 36
float 36
double 36
Characters 37
Booleans 38
A Closer Look at Literals 39
Integer Literals 39
Floating-Point Literals 40
Boolean Literals 40
Character Literals 40
String Literals 40
Variables 41
Declaring a Variable 41
Dynamic Initialization 42
The Scope and Lifetime of Variables 42
Type Conversion and Casting 45
Java’s Automatic Conversions 45
Casting Incompatible Types 45
Automatic Type Promotion in Expressions 47
The Type Promotion Rules 47
Arrays 48
One-Dimensional Arrays 48
Trang 10A Few Words About Strings 55
A Note to C/C++ Programmers About Pointers 56
4 Operators 57
Arithmetic Operators 57
The Basic Arithmetic Operators 58
The Modulus Operator 59
Arithmetic Compound Assignment Operators 59
Increment and Decrement 60
The Bitwise Operators 62
The Bitwise Logical Operators 63
The Left Shift 65
The Right Shift 66
The Unsigned Right Shift 68
Bitwise Operator Compound Assignments 69
Relational Operators 70
Boolean Logical Operators 71
Short-Circuit Logical Operators 72
The Assignment Operator 73
The ? Operator 73
Operator Precedence 74
Using Parentheses 74
5 Control Statements 77
Java’s Selection Statements 77
if 77
switch 80
Iteration Statements 84
while 84
do-while 86
for 88
The For-Each Version of the for Loop 92
Nested Loops 97
Jump Statements 98
Using break 98
Using continue 102
return 103
6 Introducing Classes 105
Class Fundamentals 105
The General Form of a Class 105
A Simple Class 106
Declaring Objects 109
A Closer Look at new 109
Assigning Object Reference Variables 111
Trang 11Returning a Value 114
Adding a Method That Takes Parameters 115
Constructors 117
Parameterized Constructors 119
The this Keyword 120
Instance Variable Hiding 121
Garbage Collection 121
The finalize( ) Method 121
A Stack Class 122
7 A Closer Look at Methods and Classes 125
Overloading Methods 125
Overloading Constructors 128
Using Objects as Parameters 130
A Closer Look at Argument Passing 132
Returning Objects 134
Recursion 135
Introducing Access Control 138
Understanding static 141
Introducing final 143
Arrays Revisited 143
Introducing Nested and Inner Classes 145
Exploring the String Class 148
Using Command-Line Arguments 150
Varargs: Variable-Length Arguments 151
Overloading Vararg Methods 154
Varargs and Ambiguity 155
8 Inheritance 157
Inheritance Basics 157
Member Access and Inheritance 159
A More Practical Example 160
A Superclass Variable Can Reference a Subclass Object 162
Using super 163
Using super to Call Superclass Constructors 163
A Second Use for super 166
Creating a Multilevel Hierarchy 167
When Constructors Are Called 170
Method Overriding 171
Dynamic Method Dispatch 174
Why Overridden Methods? 175
Applying Method Overriding 176
Using Abstract Classes 177
Using final with Inheritance 180
Using final to Prevent Overriding 180
Trang 129 Packages and Interfaces 183
Packages 183
Defining a Package 184
Finding Packages and CLASSPATH 184
A Short Package Example 185
Access Protection 186
An Access Example 187
Importing Packages 190
Interfaces 192
Defining an Interface 193
Implementing Interfaces 194
Nested Interfaces 196
Applying Interfaces 197
Variables in Interfaces 200
Interfaces Can Be Extended 202
10 Exception Handling 205
Exception-Handling Fundamentals 205
Exception Types 206
Uncaught Exceptions 206
Using try and catch 207
Displaying a Description of an Exception 209
Multiple catch Clauses 209
Nested try Statements 211
throw 213
throws 214
finally 216
Java’s Built-in Exceptions 217
Creating Your Own Exception Subclasses 219
Chained Exceptions 221
Using Exceptions 222
11 Multithreaded Programming 223
The Java Thread Model 224
Thread Priorities 224
Synchronization 225
Messaging 225
The Thread Class and the Runnable Interface 226
The Main Thread 226
Creating a Thread 228
Implementing Runnable 228
Extending Thread 230
Choosing an Approach 232
Creating Multiple Threads 232
Trang 13Synchronization 238
Using Synchronized Methods 239
The synchronized Statement 241
Interthread Communication 242
Deadlock 247
Suspending, Resuming, and Stopping Threads 249
Suspending, Resuming, and Stopping Threads Using Java 1.1 and Earlier 249
The Modern Way of Suspending, Resuming, and Stopping Threads 251
Using Multithreading 254
12 Enumerations, Autoboxing, and Annotations (Metadata) 255
Enumerations 255
Enumeration Fundamentals 255
The values( ) and valueOf( ) Methods 258
Java Enumerations Are Class Types 259
Enumerations Inherit Enum 261
Another Enumeration Example 263
Type Wrappers 264
Autoboxing 266
Autoboxing and Methods 267
Autoboxing/Unboxing Occurs in Expressions 268
Autoboxing/Unboxing Boolean and Character Values 270
Autoboxing/Unboxing Helps Prevent Errors 271
A Word of Warning 271
Annotations (Metadata) 272
Annotation Basics 272
Specifying a Retention Policy 273
Obtaining Annotations at Run Time by Use of Reflection 273
The AnnotatedElement Interface 278
Using Default Values 279
Marker Annotations 280
Single-Member Annotations 281
The Built-In Annotations 282
Some Restrictions 284
13 I/O, Applets, and Other Topics 285
I/O Basics 285
Streams 286
Byte Streams and Character Streams 286
The Predefined Streams 288
Reading Console Input 288
Reading Characters 289
Trang 14Writing Console Output 292
The PrintWriter Class 292
Reading and Writing Files 293
Applet Fundamentals 296
The transient and volatile Modifiers 299
Using instanceof 300
strictfp 302
Native Methods 302
Problems with Native Methods 306
Using assert 306
Assertion Enabling and Disabling Options 309
Static Import 309
Invoking Overloaded Constructors Through this( ) 312
14 Generics 315
What Are Generics? 316
A Simple Generics Example 316
Generics Work Only with Objects 320
Generic Types Differ Based on Their Type Arguments 320
How Generics Improve Type Safety 320
A Generic Class with Two Type Parameters 322
The General Form of a Generic Class 324
Bounded Types 324
Using Wildcard Arguments 327
Bounded Wildcards 329
Creating a Generic Method 334
Generic Constructors 336
Generic Interfaces 337
Raw Types and Legacy Code 339
Generic Class Hierarchies 342
Using a Generic Superclass 342
A Generic Subclass 344
Run-Time Type Comparisons Within a Generic Hierarchy 345
Casting 348
Overriding Methods in a Generic Class 348
Erasure 349
Bridge Methods 351
Ambiguity Errors 353
Some Generic Restrictions 354
Type Parameters Can’t Be Instantiated 354
Restrictions on Static Members 354
Generic Array Restrictions 355
Generic Exception Restriction 356
Final Thoughts on Generics 356
Trang 15Part II The Java Library
15 String Handling 359
The String Constructors 359
String Length 362
Special String Operations 362
String Literals 362
String Concatenation 362
String Concatenation with Other Data Types 363
String Conversion and toString( ) 364
Character Extraction 365
charAt( ) 365
getChars( ) 365
getBytes( ) 366
toCharArray( ) 366
String Comparison 366
equals( ) and equalsIgnoreCase( ) 366
regionMatches( ) 367
startsWith( ) and endsWith( ) 368
equals( ) Versus == 368
compareTo( ) 369
Searching Strings 370
Modifying a String 372
substring( ) 372
concat( ) 373
replace( ) 373
trim( ) 373
Data Conversion Using valueOf( ) 374
Changing the Case of Characters Within a String 375
Additional String Methods 376
StringBuffer 377
StringBuffer Constructors 377
length( ) and capacity( ) 378
ensureCapacity( ) 378
setLength( ) 378
charAt( ) and setCharAt( ) 379
getChars( ) 379
append( ) 380
insert( ) 381
reverse( ) 381
delete( ) and deleteCharAt( ) 382
replace( ) 382
substring( ) 383
Additional StringBuffer Methods 383
Trang 1616 Exploring java.lang 385
Primitive Type Wrappers 386
Number 386
Double and Float 386
Byte, Short, Integer, and Long 390
Character 398
Recent Additions to Character for Unicode Code Point Support 401
Boolean 402
Void 403
Process 403
Runtime 404
Memory Management 405
Executing Other Programs 406
ProcessBuilder 407
System 409
Using currentTimeMillis( ) to Time Program Execution 410
Using arraycopy( ) 411
Environment Properties 412
Object 412
Using clone( ) and the Cloneable Interface 413
Class 415
ClassLoader 418
Math 418
Transcendental Functions 418
Exponential Functions 419
Rounding Functions 419
Miscellaneous Math Methods 420
StrictMath 422
Compiler 422
Thread, ThreadGroup, and Runnable 422
The Runnable Interface 422
Thread 422
ThreadGroup 424
ThreadLocal and InheritableThreadLocal 429
Package 429
RuntimePermission 431
Throwable 431
SecurityManager 431
StackTraceElement 431
Enum 432
The CharSequence Interface 433
The Comparable Interface 433
The Appendable Interface 434
Trang 17The Iterable Interface 434
The Readable Interface 434
The java.lang Subpackages 435
java.lang.annotation 435
java.lang.instrument 435
java.lang.management 435
java.lang.ref 435
java.lang.reflect 436
17 java.util Part 1: The Collections Framework 437
Collections Overview 438
Recent Changes to Collections 439
Generics Fundamentally Change the Collections Framework 439
Autoboxing Facilitates the Use of Primitive Types 439
The For-Each Style for Loop 440
The Collection Interfaces 440
The Collection Interface 441
The List Interface 441
The Set Interface 443
The SortedSet Interface 444
The NavigableSet Interface 444
The Queue Interface 445
The Deque Interface 446
The Collection Classes 448
The ArrayList Class 448
The LinkedList Class 451
The HashSet Class 453
The LinkedHashSet Class 454
The TreeSet Class 455
The PriorityQueue Class 456
The ArrayDeque Class 457
The EnumSet Class 458
Accessing a Collection via an Iterator 458
Using an Iterator 459
The For-Each Alternative to Iterators 461
Storing User-Defined Classes in Collections 462
The RandomAccess Interface 463
Working with Maps 464
The Map Interfaces 464
The NavigableMap Interface 466
The Map Classes 468
Comparators 472
Using a Comparator 473
Trang 18Arrays 480
Why Generic Collections? 484
The Legacy Classes and Interfaces 487
The Enumeration Interface 487
Vector 487
Stack 491
Dictionary 493
Hashtable 494
Properties 497
Using store( ) and load( ) 500
Parting Thoughts on Collections 501
18 java.util Part 2: More Utility Classes 503
StringTokenizer 503
BitSet 505
Date 507
Calendar 509
GregorianCalendar 512
TimeZone 513
SimpleTimeZone 514
Locale 515
Random 516
Observable 518
The Observer Interface 519
An Observer Example 519
Timer and TimerTask 522
Currency 524
Formatter 525
The Formatter Constructors 526
The Formatter Methods 526
Formatting Basics 526
Formatting Strings and Characters 529
Formatting Numbers 529
Formatting Time and Date 530
The %n and %% Specifiers 532
Specifying a Minimum Field Width 533
Specifying Precision 534
Using the Format Flags 535
Justifying Output 535
The Space, +, 0, and ( Flags 536
The Comma Flag 537
The # Flag 537
The Uppercase Option 537
Using an Argument Index 538
Trang 19Scanner 540
The Scanner Constructors 540
Scanning Basics 541
Some Scanner Examples 544
Setting Delimiters 547
Other Scanner Features 548
The ResourceBundle, ListResourceBundle, and PropertyResourceBundle Classes 549
Miscellaneous Utility Classes and Interfaces 553
The java.util Subpackages 554
java.util.concurrent, java.util.concurrent.atomic, and java.util.concurrent.locks 554
java.util.jar 554
java.util.logging 554
java.util.prefs 554
java.util.regex 554
java.util.spi 554
java.util.zip 554
19 Input/Output: Exploring java.io 555
The Java I/O Classes and Interfaces 555
File 556
Directories 559
Using FilenameFilter 560
The listFiles( ) Alternative 561
Creating Directories 561
The Closeable and Flushable Interfaces 561
The Stream Classes 562
The Byte Streams 562
InputStream 562
OutputStream 562
FileInputStream 564
FileOutputStream 565
ByteArrayInputStream 567
ByteArrayOutputStream 568
Filtered Byte Streams 569
Buffered Byte Streams 569
SequenceInputStream 573
PrintStream 574
DataOutputStream and DataInputStream 576
RandomAccessFile 578
The Character Streams 578
Reader 579
Writer 579
Trang 20CharArrayReader 582
CharArrayWriter 582
BufferedReader 583
BufferedWriter 585
PushbackReader 585
PrintWriter 586
The Console Class 587
Using Stream I/O 589
Improving wc( ) Using a StreamTokenizer 590
Serialization 592
Serializable 593
Externalizable 593
ObjectOutput 593
ObjectOutputStream 593
ObjectInput 595
ObjectInputStream 595
A Serialization Example 595
Stream Benefits 598
20 Networking 599
Networking Basics 599
The Networking Classes and Interfaces 600
InetAddress 601
Factory Methods 601
Instance Methods 602
Inet4Address and Inet6Address 603
TCP/IP Client Sockets 603
URL 605
URLConnection 607
HttpURLConnection 610
The URI Class 612
Cookies 612
TCP/IP Server Sockets 612
Datagrams 613
DatagramSocket 613
DatagramPacket 614
A Datagram Example 615
21 The Applet Class 617
Two Types of Applets 617
Applet Basics 617
The Applet Class 618
Applet Architecture 620
An Applet Skeleton 621
Trang 21Simple Applet Display Methods 623
Requesting Repainting 625
A Simple Banner Applet 626
Using the Status Window 628
The HTML APPLET Tag 629
Passing Parameters to Applets 630
Improving the Banner Applet 631
getDocumentBase( ) and getCodeBase( ) 633
AppletContext and showDocument( ) 634
The AudioClip Interface 635
The AppletStub Interface 635
Outputting to the Console 636
22 Event Handling 637
Two Event Handling Mechanisms 637
The Delegation Event Model 638
Events 638
Event Sources 638
Event Listeners 639
Event Classes 639
The ActionEvent Class 640
The AdjustmentEvent Class 641
The ComponentEvent Class 642
The ContainerEvent Class 642
The FocusEvent Class 643
The InputEvent Class 643
The ItemEvent Class 644
The KeyEvent Class 645
The MouseEvent Class 646
The MouseWheelEvent Class 647
The TextEvent Class 648
The WindowEvent Class 648
Sources of Events 649
Event Listener Interfaces 650
The ActionListener Interface 650
The AdjustmentListener Interface 651
The ComponentListener Interface 651
The ContainerListener Interface 651
The FocusListener Interface 651
The ItemListener Interface 651
The KeyListener Interface 651
The MouseListener Interface 652
The MouseMotionListener Interface 652
The MouseWheelListener Interface 652
Trang 22The WindowListener Interface 653
Using the Delegation Event Model 653
Handling Mouse Events 653
Handling Keyboard Events 656
Adapter Classes 659
Inner Classes 660
Anonymous Inner Classes 662
23 Introducing the AWT: Working with Windows, Graphics,
Working with Frame Windows 667
Setting the Window’s Dimensions 668
Hiding and Showing a Window 668
Setting a Window’s Title 668
Closing a Frame Window 668
Creating a Frame Window in an Applet 668
Handling Events in a Frame Window 670
Creating a Windowed Program 674
Displaying Information Within a Window 676
Working with Graphics 676
Setting the Current Graphics Color 684
A Color Demonstration Applet 684
Setting the Paint Mode 685
Working with Fonts 686
Determining the Available Fonts 687
Creating and Selecting a Font 689
Obtaining Font Information 690
Managing Text Output Using FontMetrics 691
Trang 23Centering Text 694Multiline Text Alignment 695
24 Using AWT Controls, Layout Managers, and Menus 701
Control Fundamentals 701Adding and Removing Controls 702Responding to Controls 702The HeadlessException 702Labels 702Using Buttons 704Handling Buttons 704Applying Check Boxes 707Handling Check Boxes 707CheckboxGroup 709Choice Controls 711Handling Choice Lists 711Using Lists 713Handling Lists 714Managing Scroll Bars 716Handling Scroll Bars 717Using a TextField 719Handling a TextField 720Using a TextArea 721Understanding Layout Managers 723FlowLayout 724BorderLayout 725Using Insets 727GridLayout 728CardLayout 730GridBagLayout 732Menu Bars and Menus 737Dialog Boxes 742FileDialog 747Handling Events by Extending AWT Components 748Extending Button 749Extending Checkbox 750Extending a Check Box Group 751Extending Choice 752Extending List 752Extending Scrollbar 753
25 Images 755
File Formats 755Image Fundamentals: Creating, Loading, and Displaying 756
Trang 24Additional Imaging Classes 786
26 The Concurrency Utilities 787
The Concurrent API Packages 788
A Simple Executor Example 802
Using Callable and Future 804
The TimeUnit Enumeration 806
The Concurrent Collections 808
Locks 808
Atomic Operations 811
The Concurrency Utilities Versus Java’s Traditional Approach 812
27 NIO, Regular Expressions, and Other Packages 813
The Core Java API Packages 813
NIO 815
NIO Fundamentals 815
Charsets and Selectors 818
Using the NIO System 819
Is NIO the Future of I/O Handling? 825
Regular Expression Processing 825
Pattern 825
Matcher 826
Trang 25Two Pattern-Matching Options 833Exploring Regular Expressions 833Reflection 833Remote Method Invocation (RMI) 837
A Simple Client/Server Application Using RMI 837Text Formatting 840DateFormat Class 840SimpleDateFormat Class 842
Part III Software Development Using Java
28 Java Beans 847
What Is a Java Bean? 847Advantages of Java Beans 848Introspection 848Design Patterns for Properties 848Design Patterns for Events 849Methods and Design Patterns 850Using the BeanInfo Interface 850Bound and Constrained Properties 850Persistence 851Customizers 851The Java Beans API 851Introspector 853PropertyDescriptor 854EventSetDescriptor 854MethodDescriptor 854
A Bean Example 854
29 Introducing Swing 859
The Origins of Swing 859Swing Is Built on the AWT 860Two Key Swing Features 860Swing Components Are Lightweight 860Swing Supports a Pluggable Look and Feel 860The MVC Connection 861Components and Containers 862Components 862Containers 863The Top-Level Container Panes 863The Swing Packages 863
A Simple Swing Application 864Event Handling 868Create a Swing Applet 871
Trang 26The Life Cycle of a Servlet 908
Using Tomcat for Servlet Development 908
A Simple Servlet 910
Create and Compile the Servlet Source Code 910
Start Tomcat 911
Start a Web Browser and Request the Servlet 911
The Servlet API 911
The javax.servlet Package 911
The Servlet Interface 912
The ServletConfig Interface 912
The ServletContext Interface 912
The ServletRequest Interface 913
The ServletResponse Interface 913
The GenericServlet Class 914
The ServletInputStream Class 915
The ServletOutputStream Class 915
The Servlet Exception Classes 915
Reading Servlet Parameters 915
The javax.servlet.http Package 917
The HttpServletRequest Interface 917
The HttpServletResponse Interface 917
The HttpSession Interface 917
Trang 27The HttpServlet Class 921The HttpSessionEvent Class 921The HttpSessionBindingEvent Class 922Handling HTTP Requests and Responses 922Handling HTTP GET Requests 922Handling HTTP POST Requests 924Using Cookies 925Session Tracking 927
Part IV Applying Java
32 Financial Applets and Servlets 931
Finding the Payments for a Loan 932The RegPay Fields 935The init( ) Method 936The makeGUI( ) Method 936The actionPerformed( ) Method 938The compute( ) Method 939Finding the Future Value of an Investment 940Finding the Initial Investment Required to Achieve a Future Value 943Finding the Initial Investment Needed for a Desired Annuity 947Finding the Maximum Annuity for a Given Investment 951Finding the Remaining Balance on a Loan 955Creating Financial Servlets 959Converting the RegPay Applet into a Servlet 960The RegPayS Servlet 960Some Things to Try 963
33 Creating a Download Manager in Java 965
Understanding Internet Downloads 966
An Overview of the Download Manager 966The Download Class 967The Download Variables 971The Download Constructor 971The download( ) Method 971The run( ) Method 971The stateChanged( ) Method 975Action and Accessor Methods 975The ProgressRenderer Class 975The DownloadsTableModel Class 976The addDownload( ) Method 978The clearDownload( ) Method 979The getColumnClass( ) Method 979The getValueAt( ) Method 979
Trang 28The DownloadManager Class 980
The DownloadManager Variables 986
The DownloadManager Constructor 986
The verifyUrl( ) Method 986
The tableSelectionChanged( ) Method 987
The updateButtons( ) Method 988
Handling Action Events 989
Compiling and Running the Download Manager 989
Enhancing the Download Manager 990
A Using Java’s Documentation Comments 991
The javadoc Tags 991
The General Form of a Documentation Comment 995
What javadoc Outputs 995
An Example that Uses Documentation Comments 995
Index 997
Trang 30As I write this, Java is just beginning its second decade Unlike many other computer
languages whose influence begins to wane over the years, Java’s has grown strongerwith the passage of time Java leapt to the forefront of Internet programming withits first release Each subsequent version has solidified that position Today, Java is still thefirst and best choice for developing web-based applications
One reason for Java’s success is its agility Java has rapidly adapted to changes in theprogramming environment and to changes in the way that programmers program Most
importantly, it has not just followed the trends, it has helped create them Unlike some other
languages that have a revision cycle of approximately 10 years, Java’s release cycle averagesabout 1.5 years! Java’s ability to accommodate the fast rate of change in the computingworld is a crucial part of why it has stayed at the forefront of computer language design.With the release of Java SE 6, Java’s leadership remains unchallenged If you are programmingfor the Internet, you have chosen the right language Java has been and continues to be thepreeminent language of the Internet
As many readers will know, this is the seventh edition of the book, which was firstpublished in 1996 This edition has been updated for Java SE 6 It has also been expanded inseveral key areas Here are two examples: it now includes twice as much coverage of Swingand a more detailed discussion of resource bundles Throughout are many other additionsand improvements In all, dozens of pages of new material have been incorporated
A Book for All Programmers
This book is for all programmers, whether you are a novice or an experienced pro Thebeginner will find its carefully paced discussions and many examples especially helpful.Its in-depth coverage of Java’s more advanced features and libraries will appeal to the pro.For both, it offers a lasting resource and handy reference
What’s Inside
This book is a comprehensive guide to the Java language, describing its syntax, keywords,and fundamental programming principles Significant portions of the Java API library arealso examined The book is divided into four parts, each focusing on a different aspect ofthe Java programming environment
Trang 31Part I presents an in-depth tutorial of the Java language It begins with the basics,
including such things as data types, control statements, and classes Part I also discussesJava’s exception-handling mechanism, multithreading subsystem, packages, and interfaces
Of course, Java’s newer features, such as generics, annotations, enumerations, and autoboxingare covered in detail
Part II examines key aspects of Java’s standard API library Topics include strings, I/O,networking, the standard utilities, the Collections Framework, applets, GUI-based controls,imaging, and concurrency
Part III looks at three important Java technologies: Java Beans, Swing, and servlets.Part IV contains two chapters that show examples of Java in action The first chapterdevelops several applets that perform various popular financial calculations, such ascomputing the regular payment on a loan or the minimum investment needed to withdraw
a desired monthly annuity This chapter also shows how to convert those applets into servlets.The second chapter develops a download manager that oversees the downloading of files Itincludes the ability to start, stop, and resume a transfer Both chapters are adapted from my
book The Art of Java, which I co-authored with James Holmes.
Don’t Forget: Code on the Web
Remember, the source code for all of the examples in this book is available free-of-charge on
the Web at www.osborne.com.
Special Thanks
Special thanks to Patrick Naughton Patrick was one of the creators of the Java language He alsohelped write the first edition of this book For example, much of the material in Chapters 19, 20,and 25 was initially provided by Patrick His insights, expertise, and energy contributed greatly
to the success of this book
Thanks also go to Joe O’Neil for providing the initial drafts for Chapters 27, 28, 30, and 31.Joe has helped on several of my books and, as always, his efforts are appreciated
Finally, many thanks to James Holmes for providing Chapter 32 James is an extraordinary
programmer and author He was my co-author on The Art of Java and is the author of Struts: The Complete Reference and a co-author of JSF: The Complete Reference.
HERBERT SCHILDTNovember 8, 2006
Trang 32books Here are some others that you will find of interest.
To learn more about Java programming, we recommend the following:
Java: A Beginner’s Guide
Swing: A Beginner’s Guide
The Art Of Java
To learn about C++, you will find these books especially helpful:
C++: The Complete Reference
C++: A Beginner’s Guide
The Art of C++
C++ From the Ground Up
STL Programming From the Ground Up
To learn about C#, we suggest the following Schildt books:
C#: The Complete Reference
C#: A Beginner’s Guide
To learn about the C language, the following titles will be of interest:
C: The Complete Reference
Teach Yourself C
When you need solid answers, fast, turn to Herbert Schildt,
the recognized authority on programming.
Trang 34The History and Evolution
Trang 36The History and Evolution of Java
To fully understand Java, one must understand the reasons behind its creation, the
forces that shaped it, and the legacy that it inherits Like the successful computerlanguages that came before, Java is a blend of the best elements of its rich heritagecombined with the innovative concepts required by its unique mission While the remainingchapters of this book describe the practical aspects of Java—including its syntax, key libraries,and applications—this chapter explains how and why Java came about, what makes it soimportant, and how it has evolved over the years
Although Java has become inseparably linked with the online environment of theInternet, it is important to remember that Java is first and foremost a programming language.Computer language innovation and development occurs for two fundamental reasons:
• To adapt to changing environments and uses
• To implement refinements and improvements in the art of programming
As you will see, the development of Java was driven by both elements in nearly equalmeasure
Java’s Lineage
Java is related to C++, which is a direct descendant of C Much of the character of Java
is inherited from these two languages From C, Java derives its syntax Many of Java’sobject-oriented features were influenced by C++ In fact, several of Java’s defining
characteristics come from—or are responses to—its predecessors Moreover, the creation ofJava was deeply rooted in the process of refinement and adaptation that has been occurring
in computer programming languages for the past several decades For these reasons, thissection reviews the sequence of events and forces that led to Java As you will see, eachinnovation in language design was driven by the need to solve a fundamental problemthat the preceding languages could not solve Java is no exception
Trang 37The Birth of Modern Programming: C
The C language shook the computer world Its impact should not be underestimated, because
it fundamentally changed the way programming was approached and thought about Thecreation of C was a direct result of the need for a structured, efficient, high-level language thatcould replace assembly code when creating systems programs As you probably know, when
a computer language is designed, trade-offs are often made, such as the following:
• Ease-of-use versus power
• Safety versus efficiency
• Rigidity versus extensibility
Prior to C, programmers usually had to choose between languages that optimized one set oftraits or the other For example, although FORTRAN could be used to write fairly efficientprograms for scientific applications, it was not very good for system code And while BASICwas easy to learn, it wasn’t very powerful, and its lack of structure made its usefulnessquestionable for large programs Assembly language can be used to produce highly efficientprograms, but it is not easy to learn or use effectively Further, debugging assembly codecan be quite difficult
Another compounding problem was that early computer languages such as BASIC,COBOL, and FORTRAN were not designed around structured principles Instead, theyrelied upon the GOTO as a primary means of program control As a result, programswritten using these languages tended to produce “spaghetti code”—a mass of tangledjumps and conditional branches that make a program virtually impossible to understand.While languages like Pascal are structured, they were not designed for efficiency, and failed
to include certain features necessary to make them applicable to a wide range of programs.(Specifically, given the standard dialects of Pascal available at the time, it was not practical
to consider using Pascal for systems-level code.)
So, just prior to the invention of C, no one language had reconciled the conflictingattributes that had dogged earlier efforts Yet the need for such a language was pressing Bythe early 1970s, the computer revolution was beginning to take hold, and the demand forsoftware was rapidly outpacing programmers’ ability to produce it A great deal of effortwas being expended in academic circles in an attempt to create a better computer language.But, and perhaps most importantly, a secondary force was beginning to be felt Computerhardware was finally becoming common enough that a critical mass was being reached
No longer were computers kept behind locked doors For the first time, programmerswere gaining virtually unlimited access to their machines This allowed the freedom toexperiment It also allowed programmers to begin to create their own tools On the eve
of C’s creation, the stage was set for a quantum leap forward in computer languages.Invented and first implemented by Dennis Ritchie on a DEC PDP-11 running the UNIXoperating system, C was the result of a development process that started with an olderlanguage called BCPL, developed by Martin Richards BCPL influenced a language called
B, invented by Ken Thompson, which led to the development of C in the 1970s For manyyears, the de facto standard for C was the one supplied with the UNIX operating system
and described in The C Programming Language by Brian Kernighan and Dennis Ritchie
(Prentice-Hall, 1978) C was formally standardized in December 1989, when the AmericanNational Standards Institute (ANSI) standard for C was adopted
Trang 38The creation of C is considered by many to have marked the beginning of the modern
age of computer languages It successfully synthesized the conflicting attributes that had
so troubled earlier languages The result was a powerful, efficient, structured language thatwas relatively easy to learn It also included one other, nearly intangible aspect: it was a
programmer’s language Prior to the invention of C, computer languages were generally
designed either as academic exercises or by bureaucratic committees C is different It wasdesigned, implemented, and developed by real, working programmers, reflecting the waythat they approached the job of programming Its features were honed, tested, thought
about, and rethought by the people who actually used the language The result was a
language that programmers liked to use Indeed, C quickly attracted many followers
who had a near-religious zeal for it As such, it found wide and rapid acceptance in the
programmer community In short, C is a language designed by and for programmers
As you will see, Java inherited this legacy
C++: The Next Step
During the late 1970s and early 1980s, C became the dominant computer programming
language, and it is still widely used today Since C is a successful and useful language, you
might ask why a need for something else existed The answer is complexity Throughout the
history of programming, the increasing complexity of programs has driven the need for betterways to manage that complexity C++ is a response to that need To better understand why
managing program complexity is fundamental to the creation of C++, consider the following.Approaches to programming have changed dramatically since the invention of the
computer For example, when computers were first invented, programming was done by
manually toggling in the binary machine instructions by use of the front panel As long asprograms were just a few hundred instructions long, this approach worked As programs grew,assembly language was invented so that a programmer could deal with larger, increasingly
complex programs by using symbolic representations of the machine instructions As programscontinued to grow, high-level languages were introduced that gave the programmer more toolswith which to handle complexity
The first widespread language was, of course, FORTRAN While FORTRAN was an
impressive first step, it is hardly a language that encourages clear and easy-to-understand
programs The 1960s gave birth to structured programming This is the method of programming
championed by languages such as C The use of structured languages enabled programmers
to write, for the first time, moderately complex programs fairly easily However, even with
structured programming methods, once a project reaches a certain size, its complexity exceedswhat a programmer can manage By the early 1980s, many projects were pushing the structuredapproach past its limits To solve this problem, a new way to program was invented, called
object-oriented programming (OOP) Object-oriented programming is discussed in detail later in
this book, but here is a brief definition: OOP is a programming methodology that helps organizecomplex programs through the use of inheritance, encapsulation, and polymorphism
In the final analysis, although C is one of the world’s great programming languages,
there is a limit to its ability to handle complexity Once the size of a program exceeds a
certain point, it becomes so complex that it is difficult to grasp as a totality While the
precise size at which this occurs differs, depending upon both the nature of the program
and the programmer, there is always a threshold at which a program becomes
unmanageable C++ added features that enabled this threshold to be broken, allowing
Trang 39C++ was invented by Bjarne Stroustrup in 1979, while he was working at Bell Laboratories
in Murray Hill, New Jersey Stroustrup initially called the new language “C with Classes.”However, in 1983, the name was changed to C++ C++ extends C by adding object-orientedfeatures Because C++ is built on the foundation of C, it includes all of C’s features, attributes,and benefits This is a crucial reason for the success of C++ as a language The invention of C++was not an attempt to create a completely new programming language Instead, it was anenhancement to an already highly successful one
The Stage Is Set for Java
By the end of the 1980s and the early 1990s, object-oriented programming using C++ tookhold Indeed, for a brief moment it seemed as if programmers had finally found the perfectlanguage Because C++ blended the high efficiency and stylistic elements of C with theobject-oriented paradigm, it was a language that could be used to create a wide range ofprograms However, just as in the past, forces were brewing that would, once again, drivecomputer language evolution forward Within a few years, the World Wide Web and theInternet would reach critical mass This event would precipitate another revolution inprogramming
The Creation of Java
Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and MikeSheridan at Sun Microsystems, Inc in 1991 It took 18 months to develop the first workingversion This language was initially called “Oak,” but was renamed “Java” in 1995 Betweenthe initial implementation of Oak in the fall of 1992 and the public announcement of Java inthe spring of 1995, many more people contributed to the design and evolution of the language.Bill Joy, Arthur van Hoff, Jonathan Payne, Frank Yellin, and Tim Lindholm were keycontributors to the maturing of the original prototype
Somewhat surprisingly, the original impetus for Java was not the Internet! Instead, theprimary motivation was the need for a platform-independent (that is, architecture-neutral)language that could be used to create software to be embedded in various consumer electronicdevices, such as microwave ovens and remote controls As you can probably guess, manydifferent types of CPUs are used as controllers The trouble with C and C++ (and most otherlanguages) is that they are designed to be compiled for a specific target Although it is possible
to compile a C++ program for just about any type of CPU, to do so requires a full C++ compilertargeted for that CPU The problem is that compilers are expensive and time-consuming tocreate An easier—and more cost-efficient—solution was needed In an attempt to find such asolution, Gosling and others began work on a portable, platform-independent language thatcould be used to produce code that would run on a variety of CPUs under differing
environments This effort ultimately led to the creation of Java
About the time that the details of Java were being worked out, a second, and ultimatelymore important, factor was emerging that would play a crucial role in the future of Java.This second force was, of course, the World Wide Web Had the Web not taken shape atabout the same time that Java was being implemented, Java might have remained a usefulbut obscure language for programming consumer electronics However, with the emergence
of the World Wide Web, Java was propelled to the forefront of computer language design,because the Web, too, demanded portable programs
Trang 40Most programmers learn early in their careers that portable programs are as elusive as theyare desirable While the quest for a way to create efficient, portable (platform-independent)
programs is nearly as old as the discipline of programming itself, it had taken a back seat toother, more pressing problems Further, because (at that time) much of the computer worldhad divided itself into the three competing camps of Intel, Macintosh, and UNIX, most
programmers stayed within their fortified boundaries, and the urgent need for portable
code was reduced However, with the advent of the Internet and the Web, the old problem
of portability returned with a vengeance After all, the Internet consists of a diverse,
distributed universe populated with various types of computers, operating systems, and
CPUs Even though many kinds of platforms are attached to the Internet, users would likethem all to be able to run the same program What was once an irritating but low-priority
problem had become a high-profile necessity
By 1993, it became obvious to members of the Java design team that the problems of
portability frequently encountered when creating code for embedded controllers are also
found when attempting to create code for the Internet In fact, the same problem that Java
was initially designed to solve on a small scale could also be applied to the Internet on a
large scale This realization caused the focus of Java to switch from consumer electronics
to Internet programming So, while the desire for an architecture-neutral programming
language provided the initial spark, the Internet ultimately led to Java’s large-scale success
As mentioned earlier, Java derives much of its character from C and C++ This is by
intent The Java designers knew that using the familiar syntax of C and echoing the
object-oriented features of C++ would make their language appealing to the legions of
experienced C/C++ programmers In addition to the surface similarities, Java shares some
of the other attributes that helped make C and C++ successful First, Java was designed,
tested, and refined by real, working programmers It is a language grounded in the needs
and experiences of the people who devised it Thus, Java is a programmer’s language
Second, Java is cohesive and logically consistent Third, except for those constraints
imposed by the Internet environment, Java gives you, the programmer, full control If youprogram well, your programs reflect it If you program poorly, your programs reflect that,too Put differently, Java is not a language with training wheels It is a language for
professional programmers
Because of the similarities between Java and C++, it is tempting to think of Java as simplythe “Internet version of C++.” However, to do so would be a large mistake Java has significantpractical and philosophical differences While it is true that Java was influenced by C++, it isnot an enhanced version of C++ For example, Java is neither upwardly nor downwardly
compatible with C++ Of course, the similarities with C++ are significant, and if you are a
C++ programmer, then you will feel right at home with Java One other point: Java was not
designed to replace C++ Java was designed to solve a certain set of problems C++ was
designed to solve a different set of problems Both will coexist for many years to come
As mentioned at the start of this chapter, computer languages evolve for two reasons:
to adapt to changes in environment and to implement advances in the art of programming.The environmental change that prompted Java was the need for platform-independent
programs destined for distribution on the Internet However, Java also embodies changes
in the way that people approach the writing of programs For example, Java enhanced
and refined the object-oriented paradigm used by C++, added integrated support for
multithreading, and provided a library that simplified Internet access In the final analysis,