+ All Categories
Home > Documents > 41 Java 2: The Complete Reference, Third Edition

41 Java 2: The Complete Reference, Third Edition

Date post: 04-Oct-2021
Category:
Upload: others
View: 6 times
Download: 0 times
Share this document with a friend
18
41 Java 2: The Complete Reference, Third Edition Patrick Naughton Herbert Schildt Osborne / McGraw-Hill Berkeley New York St. Louis San Francisco Auckland Bogota Hamburg London Madrid Mexico City Milan Montreal New Delhi Panama City Paris Säo Paulo Singapore Sydney Tokyo Toronto
Transcript
Page 1: 41 Java 2: The Complete Reference, Third Edition

• ™ 41

Java 2: The Complete Reference,

Third Edition

Patrick Naughton Herbert Schildt

Osborne / McGraw-Hill Berkeley New York St. Louis San Francisco

Auckland Bogota Hamburg London Madrid Mexico City Milan Montreal New Delhi Panama City

Paris Säo Paulo Singapore Sydney Tokyo Toronto

Page 2: 41 Java 2: The Complete Reference, Third Edition

Contents

Preface xxv Acknowledgments xxvii

The Java Language

1 The Genesis of Java 3 Java's Lineage 4

The Birth of Modern Programming: C 4 The Need for C++ 6 The Stage Is Set for Java 7

The Creation of Java 7 Why Java Is Important to the Internet 9

Java Applets and Applications 10 Security 10 Portability 10

Java's Magic: The Bytecode 11 The Java Buzzwords 12

Simple 12

»

vii

Page 3: 41 Java 2: The Complete Reference, Third Edition

viii J a v a ™ 2 : The C o m p l e t e R e f e r e n c e

Object-Oriented 13 Robust 13 Multithreaded 14 Architecrure-Neutral 14 Interpreted and High Performance 14 Distributed 14 Dynamic 15

The Continuing Revolution 15 Features Added by 1.1 15 Features Deprecated by 1.1 16 Features Added by 2 16 Features Deprecated by 2 17

Java Is Not an Enhanced HTML 17

2 An Overview of Java 19 Object-Oriented Programming 20

Two Paradigms 20 Abstraction 20 The Three OOP Principles 21

A First Simple Program 27 Entering the Program 27 Compiling the Program 28 A Closer Look at the First Sample Program 29

A Second Short Program 31 Two Control Statements 33

The if Statement 33 The for Loop 35

Using Blocks of Code 37 Lexical Issues 39

Whitespace 39 Identifiers 39 Literais 39 Comments 40 Separators 40 The Java Keywords 40

The Java Class Libraries 41

U l i 3 Data Types, Variables, and Arrays 43 Java Is a Strongly Typed Language 44 The Simple Types 44 Integers 45

byte 46 short 46 int 46 long 47

Floating-Point Types 47 float 48 double 48

Page 4: 41 Java 2: The Complete Reference, Third Edition

Con ten t s ix

Characters 49 Booleans 50 A Closer Look at Literais 52

Integer Literais 52 Floating-Point Literais 52 Boolean Literais 53 Character Literais 53 String Literais 54

Variables 54 Declaring a Variable 54 Dynamic Initialization 55 The Scope and Lifetime of Variables 56

Type Conversion and Casting 59 Java's Automatic Conversions 59 Casting Incompatible Types 59

Automatic Type Promotion in Expressions 61 The Type Promotion Rules 62

Arrays 63 One-Dimensional Arrays 63 Multidimensional Arrays 66 Alternative Array Declaration Syntax 72

A Few Words About Strings 72 A Note to C/C++ Programmers About Pointers 73

4 Operators 75 Arithmetic Operators 76

The Basic Arithmetic Operators 76 The Modulus Operator 78 Arithmetic Assignment Operators 78 Increment and Decrement 80

The Bitwise Operators 82 The Bitwise Logical Operators 84 The Left Shirt 86 The Right Shift 88 The Unsigned Right Shift 89 Bitwise Operator Assignments 91

Relational Operators 92 Boolean Logical Operators 94

Short-Circuit Logical Operators 95 The Assignment Operator 96 The ? Operator 97 Operator Precedence 98 Using Parentheses 98

5 Control Statements 101 Java's Selection Statements 102

if 102 switch 106

*

Page 5: 41 Java 2: The Complete Reference, Third Edition

2: The C o m p l e t e R e f e r e n c e

Iteration Statements 111 while 111 do-while 113 for 116 Some for Loop Variations 119 Nested Loops 121

Jump Statements 121 Using break 122 Using continue 126 return 128

6 Introducing Classes 131 Class Fundamentals 132

The General Form of a Class 132 A Simple Class 133

Declaring Objects 136 A Closer Look at new 138

Assigning Object Reference Variables 139 Introducing Methods 140

Adding a Method to the Box Class 140 Returning a Value 142 Adding a Method That Takes Parameters 144

Constructors 147 Parameterized Constructors 149

The this Keyword 151 Instance Variable Hiding 151

Garbage Collection 152 The finalize() Method 152

A Stack Class 153

7 A Closer Look at Methods and Classes 157 Overloading Methods 158

Overloading Constructors 161 Using Objects as Parameters 164 A Closer Look at Argument Passing 167 Returning Objects 170 Recursion 171 Introducing Access Control 174 Understanding stark 178 Introducing final 180 Arrays Revisited 181 Introducing Nested and Inner Classes 183 Exploring the String Class 187 Using Command-Line Arguments 190

8 Inheritance 191 Inheritance Basics 192

Member Access and Inheritance 194 A More Practical Example 195 A Superclass Variable Can Reference a Subclass Object 198

Page 6: 41 Java 2: The Complete Reference, Third Edition

C o n t e n t s

Using super 199 Using super to Call Superclass Constructors 199 A Second Use for super 204

Creating a Multilevel Hierarchy 205 When Constructors Are Called 209 Method Overriding 210 Dynamic Method Dispatch 213

Why Overridden Methods? 215 Applying Method Overriding 216

Using Abstract Classes 218 Using final with Inheritance 221

Using final to Prevent Overriding 221 Using final to Prevent Inheritance 222

The Object Class 222

9 Packages and Interfaces 225 Packages 226

Defining a Package 227 Understanding CLASSPATH 228 A Short Package Example 229

Access Protection 230 An Access Example 231

Importing Packages 235 Interfaces 238

Defining an Interface 238 Implementing Interfaces 239 Applying Interfaces 243 Variables in Interfaces 247 Interfaces Can Be Extended 249

10 Exception Handling 251 Exception-Handling Fundamentals 252 Exception Types 253 Uncaught Exceptions 253 Using try and catch 255

Displaying a Description of an Exception 256 Multiple catch Clauses 257 Nested try Statements 259 throw 262 throws 263 finally 265 Java's Built-in Exceptions 267 Creating Your Own Exception Subclasses 269 Using Exceptions 271

1 1 Multithreaded Programming 273 The Java Thread Model 275

Thread Priorities 275 Synchronization 276 Messaging 276 The Thread Class and the Runnable Interface 277

Page 7: 41 Java 2: The Complete Reference, Third Edition

2 : The C o m p l e t e R e f e r e n c e

The Main Thread 277 Creating a Thread 280

Implementing Runnable 280 Extending Thread 282 Choosing an Approach 284

Creating Multiple Threads 284 Using isAlive() and join() 286 Thread Priorities 289 Synchronization 292

Using Synchronized Methods 293 The synchronized Statement 295

Interthread Communication 297 Deadlock 303

Suspending, Resuming, and Stopping Threads 305 Suspending, Resuming, and Stopping Threads

Using Java 1.1 and Earlier 306 Suspending, Resuming, and Stopping Threads

Using Java 2 308 Using Multithreading 312

12 I/O, Applets, and Other Topics 313 I /O Basics 314

Streams 314 Byte Streams and Character Streams 315 The Predefined Streams 318

Reading Console Input 318 Reading Characters 319 Reading Strings 320

Writing Console Output 322 The PrintWriter Class 323 Reading and Writing Files 324 Applet Fundamentals 328 The transient and volatile Modifiers 332 Using instanceof 332 strictfp 335 Native Methods 336

Problems with Native Methods 340

The Java Library

13 String Handl ing 343 The String Constructors 344 String Length 347 Special String Operations 347

String Literais 347 String Concatenation 348 String Concatenation with Other Data Types 348 String Conversion and toString() 349

Page 8: 41 Java 2: The Complete Reference, Third Edition

Conten ts xtii

Character Extraction 351 charAt() 351 getChars() 351 getBytes() 352 toCharArray() 352

String Comparison 352 equals() and equalsIgnoreCase() 353 regionMatches() 354 StartsWith() and endsWith() 354 equals() Versus == 355 compareTo() 355

Searching Strings 357 Modifying a String 359

substring() 359 concat() 360 replace() 361 trim() 361

Data Conversion Using valueOf() 362 Changing the Case of Characters Within a String 363 StringBuffer 364

StringBuffer Constructors 364 length() and capacity() 364 ensureCapacity() 365 setLength() 365 charAt() and setCharAt() 366 getChars() 366 append() 367 insert() 368 reverse() 368 delete() and deleteCharAt() 369 replace() 370 substring() 370

14 Exploring java.lang 371 Simple Type Wrappers 372

Number 373 Double and Float 373 Byte, Short, Integer, and Long 379 Character 389 Boolean 393

Void 394 Process 394 Runtime 395

Memory Management 397 Executing Other Programs 398

System 399 Using currentTimeMillis() to Time Program Execution 402 Using arraycopy() 403 Environment Properties 404

»

Page 9: 41 Java 2: The Complete Reference, Third Edition

J a v a ™ 2 : The C o m p l e t e R e f e r e n c e

Object 404 Using clone() and the Cloneable Interface 404 Class 408 ClassLoader 411 Math 412

Transcendental Functions 412 Exponential Functions 412 Rounding Functions 413 Miscellaneous Math Methods 414

Compiler 414 Thread, ThreadGroup, and Runnable 415

The Runnable Interface 415 Thread 415 ThreadGroup 418

ThreadLocal and InheritableThreadLocal 424 Package 424 RuntimePermission 426 Throwable 426 SecurityManager 426 The Comparable Interface 427 The java.lang.ref and java.lang.reflect Packages 427

java.lang.ref 427 java.lang.reflect 428

15 java.util Part 1: The CoUections Framework 429 CoUections Overview 431 The Collection Interfaces 432

The Collection Interface 433 The List Interface 435 The Set Interface 437 The SortedSet Interface 437

The Collection Classes 438 The ArrayList Class 439 The LinkedList Class 443 The HashSet Class 445 The TreeSet Class 446

Accessing a Collection via an Iterator 447 Using an Iterator 449

Storing User-Defined Classes in CoUections 450 Working with Maps 452

The Map Interfaces 452 The Map Classes 456

Comparators 460 Using a Comparator 461

The Collection Algorithms 465 Arrays 469 The Legacy Classes and Interfaces 473

The Enumeration Interface 473 Vector 474

Page 10: 41 Java 2: The Complete Reference, Third Edition

C o n t e n t s XV

Stack 479 Dictionary 481 Hashtable 482 Properties 487 Using store() and load() 491

Collections Summary 493

16 java.util Part 2: More Utility Classes 495 StringTokenizer 496 BitSet 498 Date 501

Date Comparison 503 Calendar 503 GregorianCalendar 508 TimeZone 510 SimpleTimeZone 511 Locale 512 Random 513 Observable 516

The Observer Interface 517 An Observer Example 517

The java.util.zip Package 520 The java.util.jar Package 520

17 Input/Output: Exploring java.io 521 The Java I / O Classes and Interfaces 522 File 523

Directories 526 Using FilenameFilter 527 The listFiles() Alternative 528 Creating Directories 529

The Stream Classes 529 The Byte Streams 530

InputStream 530 OutputStream 531 FilelnputStream 532 FileOutputStream 534 ByteArraylnputStream 536 ByteArrayOutputStream 537 Filtered Byte Streams 539 Buffered Byte Streams 539 SequencelnputStream 543 PrintStream 545 RandomAccessFile 545

The Character Streams 546 Reader 546 Writer 548 FileReader 548

»

Page 11: 41 Java 2: The Complete Reference, Third Edition

XVI J a v a ™ 2 : The C o m p l e t e R e f e r e n c e

FileWriter 549 CharArrayReader 550 CharArrayWriter 551 BufferedReader 553 BufferedWriter 554 PushbackReader 555 PrintWriter 556

Using Stream I / O 556 Improving wc() Using a StreamTokenizer 558

Serialization 561 Serializable 561 Externalizable 562 ObjectOutput 562 ObjectOutputStream 563 Objectlnput 564 ObjectlnputStream 565 A Serialization Example 567

Stream Benefits 569

18 Networking 571 Networking Basics 572

Socket Overview 572 Client/Server 573 Reserved Sockets 573 Proxy Servers 574 Internet Addressing 574

Java and the Net 575 The Networking Classes and Interfaces 575

InetAddress 576 Factory Methods 576 Instance Methods 577

TCP/IP Client Sockets 578 Whois 579

URL 581 Format 581

URLConnection 583 TCP/IP Server Sockets 585 A Caching Proxy HTTP Server 585

Source Code 586 Datagrams 607

DatagramPacket 608 Datagram Server and Client 609

Net Worth 610

19 The Applet Class 611 Applet Basics 612

The Applet Class 613

Page 12: 41 Java 2: The Complete Reference, Third Edition

Conten ts xvii

Applet Architecture 616 An Applet Skeleton 616

Applet Initialization and Termination 618 Overriding update() 619

Simple Applet Display Methods 620 Requesting Repainting 622

A Simple Banner Applet 623 Using the Status Window 626 The HTML APPLET Tag 627 Passing Parameters to Applets 628

Improving the Banner Applet 631 getDocumentBase() and getCodeBase() 632 AppletContext and showDocument() 633 The AudioClip Interface 635 The AppletStub Interface 636 Outputting to the Console 636

20 Event Handling 637 Two Event Handling Mechanisms 638 The Delegation Event Model 638

Events 639 Event Sources 639 Event Listeners 640

Event Classes 640 The ActionEvent Class 642 The AdjustmentEvent Class 643 The ComponentEvent Class 644 The ContainerEvent Class 644 The FocusEvent Class 645 The InputEvent Class 645 The ItemEvent Class 646 The KeyEvent Class 647 The MouseEvent Class 648 The TextEvent Class 649 The WindowEvent Class 649

Sources of Events 650 Event Listener Interfaces 651

The ActionListener Interface 652 The AdjustmentListener Interface 652 The ComponentListener Interface 652 The ContainerListener Interface 652 The FocusListener Interface 653 The ItemListener Interface 653 The KeyListener Interface 653 The MouseListener Interface 653 The MouseMotionListener Interface 654 The TextListener Interface 654 The WindowListener Interface 654

»

Page 13: 41 Java 2: The Complete Reference, Third Edition

xviii J a v a ™ 2 : The C o m p l e t e R e f e r e n c e

Using the Delegation Event Model 654 Handling Mouse Events 655 Handling Keyboard Events 658

Adapter Classes 662 Inner Classes 664

Anonymous Inner Classes 666

21 Introducing the AWT: Working with Windows, Graphics, and Text 669

AWT Classes 670 Window Fundamentals 673

Component 673 Container 674 Panel 674 Window 675 Frame 675 Canvas 675

Working with Frame Windows 675 Setting the Window's Dimensions 676 Hiding and Showing a Window 676 Setting a Window's Title 676 Closing a Frame Window 676

Creating a Frame Window in an Applet 677 Handling Events in a Frame Window 679

Creating a Windowed Program 684 Displaying Information Within a Window 687 Working with Graphics 687

Drawing Lines 687 Drawing Rectangles 688 Drawing Ellipses and Circles 690 Drawing Ares 691 Drawing Polygons 692 Sizing Graphics 693

Working with Color 694 Color Methods 695 Setting the Current Graphics Color 696 A Color Demonstration Applet 696

Setting the Paint Mode 698 Working with Fonts 700

Determining the Available Fonts 701 Creating and Selecting a Font 703 Obtaining Font Information 705

Managing Text Output Using FontMetrics 706 Displaying Multiple Lines of Text 708 Centering Text 710 Multiline Text Alignment 711

Exploring Text and Graphics 716

Page 14: 41 Java 2: The Complete Reference, Third Edition

C o n t e n t s xix

22 Using AWT Controls, Layout Managers, and Menüs 717

Control Fundamentals 718 Adding and Removing Controls 718 Responding to Controls 719

Labels 719 Using Buttons 721

Handling Buttons 721 Applying Check Boxes 725

Handling Check Boxes 725 CheckboxGroup 727 Choice Controls 730

Handling Choice Lists 730 Using Lists 733

Handling Lists 734 Managing Scroll Bars 736

Handling Scroll Bars 738 Using a TextField 740

Handling a TextField 741 Using a TextArea 743 Understanding Layout Managers 745

FlowLayout 746 BorderLayout 748 Using Insets 750 GridLayout 752 CardLayout 754

Menü Bars and Menüs 757 Dialog Boxes 764 FileDialog 770 Handling Events by Extending AWT Components 772

Extending Button 774 Extending Checkbox 775 Extending a Check Box Group 776 Extending Choice 777 Extending List 777 Extending Scrollbar 779

Exploring the Controls, Menüs, and Layout Managers 780

23 Images 781 File Formats 782 Image Fundamentals: Creating, Loading, and Displaying 783

Creating an Image Object 783 Loading an Image 783 Displaying an Image 784

ImageObserver 785 ImageObserver Example 787

Double Buffering 789 MediaTracker 793

»

Page 15: 41 Java 2: The Complete Reference, Third Edition

X X J a v a ™ 2 : The C o m p l e t e R e f e r e n c e

*

ImageProducer 797 MemorylmageSource 797

ImageConsumer 799 PixelGrabber 800

ImageFilter 803 CropImageFilter 803 RGBImageFilter 805

Cell Animation 819 Additional Java 2 Imaging Classes 822

24 Additional Packages 825 The Core Java API Packages 826 Reflection 826 Remote Method Invocation (RMI) 833

A Simple Client/Server Application Using RMI 834 Text Formatting 838

DateFormat Class 838 SimpleDateFormat Class 840

Software D ava

25 Java Beans 845 What Is a Java Bean? 846 Advantages of Java Beans 847 Application Builder Tools 847 The Bean Developer Kit (BDK) 848

Installing the BDK 848 Starting the BDK 848 Using the BDK 848

JAR Files 851 Manifest Files 851 The JAR Utility 852

Introspection 853 Design Patterns for Properties 854 Design Patterns for Events 856 Methods 857

Developing a Simple Bean 857 Create a New Bean 858

Using Bound Properties 861 Steps 861

Using the Beanlnfo Interface 863 Constrained Properties 865 Persistence 865 Customizers 865 The Java Beans API 866 Beans Are the Future 869

Page 16: 41 Java 2: The Complete Reference, Third Edition

Contents xxi

26 A Tour of Swing 871 JApplet 873 kons and Labels 873 Text Fields 875 Buttons 877

The JButton Class 877 Check Boxes 880 Radio Buttons 882

Combo Boxes 884 Tabbed Panes 886 Scroll Panes 889 Trees 891 Tables 896 Exploring Swing 898

27 Servlets 899 Background 900 The Life Cycle of a Servlet 901 The Java Servlet Development Kit 901 A Simple Servlet 902

Create and Compile the Servlet Source Code 902 Start the servletrunner Utility 903 Start a Web Browser and Request the Servlet 903

The Servlet API 903 The javax.servlet Package 904

The Servlet Interface 905 The ServletConfig Interface 906 The ServletContext Interface 906 The ServletRequest Interface 907 The ServletResponse Interface 908 The SingleThreadModel Interface 909 The GenericServlet Class 909 The ServletlnputStream Class 910 The ServletOutputStream Class 910 The ServletException Class 910 The UnavailableException Class 910

Reading Servlet Parameters 911 Reading Initialization Parameters 912 The javax.servlet.http Package 914

The HttpServletRequest Interface 915 The HttpServletResponse Interface 917 The HttpSession Interface 918 The HttpSessionBindingListener Interface 919 The HttpSessionContext Interface 920 The Cookie Class 920 The HttpServlet Class 921 The HttpSessionBindingEvent Class 923 The HttpUtils Class 923

»

Page 17: 41 Java 2: The Complete Reference, Third Edition

*

xxil J a v a ™ 2: The C o m p l e t e R e f e r e n c e

Handling HTTP Requests and Responses 924 Handling HTTP GET Requests 924 Handling HTTP POST Requests 925

Using Cookies 927 Session Tracking 930 Security Issues 931 Exploring Servlets 931

28 Migrating from C++ to Java 933 The Differences Between C++ and Java 934

What Java Has Removed from C++ 934 New Features Added by Java 936 Features That Differ 937

Eliminating Pointers 937 Converting Pointer Parameters 938 Converting Pointers that Operate on Arrays 940

C++ Reference Parameters Versus Java Reference Parameters 943 Converting C++ Abstract Classes into Java Interfaces 947 Converting Default Arguments 951 Converting C++ Multiple-Inheritance Hierarchies 953 Destructors Versus Finalization 955

HZEEH Applylng Java

29 The DynamicBillboard Applet 963 The APPLET Tag 964 Source Code Overview 966

DynamicBillboard.java 966 BillData.java 974 BillTransition.java 976 ColumnTransition.java 978 FadeTransition.java 981 SmashTransition.java 985 TearTransition.java 988 UnrollTransition.java 992

Dynamic Code 996

30 ImageMenu: An Image-Based Web Menü 999 The Source Image 1001 The APPLET Tags 1002 The Methods 1003

init() 1003 update() 1004 latelnit() 1004 paint() 1004 mouseExited() 1004 mouseDragged() 1005 mouseMoved() 1005

Page 18: 41 Java 2: The Complete Reference, Third Edition

Conten ts xxffi

mouseReleased() 1005 The Code 1005

Summary 1008

31 The Lavatron Applet: A Sports Arena Display 1009 How Lavatron Works 1011 The Source Code 1012

The APPLET Tag 1012 Lavatron.java 1012 IntHash() 1017

Hot Lava 1019

32 Scrabblet: A Multiplayer Word Game 1021 Network Security Concerns 1022 The Game 1023

Scoring 1026 The Source Code 1028

The APPLET Tag 1028 Scrabblet.java 1029 IntroCanvas.java 1042 Board.java 1043 Bag.java 1061 Letter.java 1063 ServerConnection.java 1069

The Server Code 1075 Server.java 1075 ClientConnection.java 1079

Enhancing Scrabblet 1083

A Using Java's Documentation Comments 1085 The javadoc Tags 1086

©author 1087 ©deprecated 1087 ©exception 1087 {©link) 1087 ©param 1088 ©return 1088 ©see 1088 ©serial 1088 ©serialData 1088 ©serialField 1089 ©since 1089 ©throws 1089 ©version 1089

The General Form of a Documentation Comment 1089 What javadoc Outputs 1090 An Example that Uses Documentation Comments 1090

Index 1093


Recommended