java 2: the complete reference, fourth edition

17
Java 2: The Complete Reference, Fourth Edition 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

Upload: others

Post on 10-Nov-2021

12 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Java 2: The Complete Reference, Fourth Edition

Java 2: The Complete Reference,

Fourth Edition

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: Java 2: The Complete Reference, Fourth Edition

Contents

Preface xxiii

MBU! _____ 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 Object-Oriented 13 Robust 13

v/7

Page 3: Java 2: The Complete Reference, Fourth Edition

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

Multithreaded 14 Architecture-Neutral 14 Interpreted and High Performance 14 Distributed 14 Dynamic 15

The Continuing Revolution 15 Java Is Not an Enhanced HTML 16

2 An Overview of Java 17 Object-Oriented Programming 18

Two Paradigms 18 Abstraction 18 The Three OOP Principles 19

A First Simple Program 25 Entering the Program 25 Compiling the Program 26 A Closer Look at the First Sample Program 27

A Second Short Program 29 Two Control Statements 31

The if Statement 31 The for Loop 33

Using Blocks of Code 35 Lexical Issues 37

Whitespace 37 Identifiers 37 Literais 37 Comments 38 Separators 38 The Java Keywords 38

The Java Class Libraries 39

3 Data Types, Variables, and Arrays 41 Java Is a Strongly Typed Language 42 The Simple Types 42 Integers 43

byte 44 short 44 int 44 long 45

Floating-Point Types 45 float 46 double 46

Characters 47 Booleans 48 A Closer Look at Literais 50

Integer Literais 50 Floating-Point Literais 50 Boolean Literais 51

Page 4: Java 2: The Complete Reference, Fourth Edition

C o n t e n t s

Character Literais 51 String Literais 52

Variables 52 Declaring a Variable 52 Dynamic Initialization 53 The Scope and Lifetime of Variables 54

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

Automatic Type Promotion in Expressions 59 The Type Promotion Rules 60

Arrays 61 One-Dimensional Arrays 61 Multidimensional Arrays 64 Alternative Array Declaration Syntax 70

A Few Words About Strings 70 A Note to C/C++ Programmers About Pointers 71

4 Operators 73 Arithmetic Operators 74

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

The Bitwise Operators 80 The Bitwise Logical Operators 82 The Left Shift 84 The Right Shift 86 The Unsigned Right Shift 87 Bitwise Operator Assignments 89

Relational Operators 90 Boolean Logical Operators 92

Short-Circuit Logical Operators 93 The Assignment Operator 94 The ? Operator 95 Operator Precedence 96 Using Parentheses 96

5 Control Statements 99 Java's Selection Statements 100

if 100 switch 104

Iteration Statements 109 while 109 do-while 111 for 114 Some for Loop Variations 117 Nested Loops 119

Page 5: Java 2: The Complete Reference, Fourth Edition

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

Jump Statements 119 Using break 120 Using continue 124 return 126

6 Introducing Classes 129 Class Fundamentals 130

The General Form of a Class 130 A Simple Class 131

Declaring Objects 134 A Closer Look at new 136

Assigning Object Reference Variables 137 Introducing Methods 138

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

Constructors 145 Parameterized Constructors 147

The this Keyword 149 Instance Variable Hiding 149

Garbage Collection 150 The finalize() Method 150 A Stack Class 151

7 A Closer Look at Methods and Classes 155 Overloading Methods 156

Overloading Constructors 159 Using Objects as Parameters 162 A Closer Look at Argument Passing 165 Returning Objects 168 Recursion 169 Introducing Access Control 172 Understanding static 176 Introducing final 178 Arrays Revisited 179 Introducing Nested and Inner Classes 181 Exploring the String Class 185 Using Command-Line Arguments 188

8 Inheritance 189 Inheritance Basics 190

Member Access and Inheritance 192 A More Practical Example 193 A Superclass Variable Can Reference a Subclass Object 196

Using super 197 Using super to Call Superclass Constructors 197 A Second Use for super 202

Creating a Multilevel Hierarchy 203 When Constructors Are Called 207 Method Overriding 208

Page 6: Java 2: The Complete Reference, Fourth Edition

Dynamic Method Dispatch 211 Why Overridden Methods? 213 Applying Method Overriding 214

Using Abstract Classes 216 Using final with Inheritance 219

Using final to Prevent Overriding 219 Using final to Prevent Inheritance 220

The Object Class 220

9 Packages and Interfaces 223 Packages 224

Defining a Package 225 Understanding CLASSPATH 226 A Short Package Example 227

Access Protection 228 An Access Example 229

Importing Packages 233 Interfaces 236

Defining an Interface 236 Implementing Interfaces 237 Applying Interfaces 241 Variables in Interfaces 245 Interfaces Can Be Extended 247

10 Exception Handling 249 Exception-Handling Fundamentals 250 Exception Types 251 Uncaught Exceptions 251 Using try and catch 253

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

1 1 Multithreaded Programming 271 The Java Thread Model 273

Thread Priorities 273 Synchronization 274 Messaging 274 The Thread Class and the Runnable Interface 275

The Main Thread 275 Creating a Thread 278

Implementing Runnable 278 Extending Thread 280 Choosing an Approach 282

*

Page 7: Java 2: The Complete Reference, Fourth Edition

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

Creating Multiple Threads 282 Using isAlive() and join() 284 Thread Priorities 287 Synchronization 290

Using Synchronized Methods 291 The synchronized Statement 293

Interthread Communication 295 Deadlock 301

Suspending, Resuming, and Stopping Threads 303 Suspending, Resuming, and Stopping Threads Using Java 1.1

and Earlier 304 Suspending, Resuming, and Stopping Threads Using Java 2 . . . 306

Using Multithreading 310

12 I/O, Applets, and Other Topics 311 I /O Basics 312

Streams 312 Byte Streams and Character Streams 313 The Predefined Streams 316

Reading Console Input 316 Reading Characters 317 Reading Strings 318

Writing Console Output 320 The PrintWriter Class 321 Reading and Writing Files 322 Applet Fundamentals 326 The transient and volatile Modifiers 330 Using instanceof 330 strictfp 333 Native Methods 334 Problems with Native Methods 338

UJT,i\M The Java Library

13 String Handling 341 The String Constructors 342 String Length 345 Special String Operations 345

String Literais 345 String Concatenation 346 String Concatenation with Other Data Types 346 String Conversion and toString() 347

Character Extraction 349 charAt() 349 getChars() 349 getBytes() 350 toCharArray() 350

Page 8: Java 2: The Complete Reference, Fourth Edition

Conten ts xiii

String Comparison 350 equals() and equalsIgnoreCase() 351 regionMatches() 352 StartsWith() and endsWith() 352 equals() Versus == 353 compareTo() 353

Searching Strings 355 Modifying a String 357

substring() 357 concat() 358 replace() 359 trim() 359

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

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

14 Exploring java.lang 369 Simple Type Wrappers 370

Number 371 Double and Float 371 Byte, Short, Integer, and Long 377 Character 387 Boolean 391

Void 392 Process 392 Runtime 393

Memory Management 395 Executing Other Programs 396

System 397 Using currentTimeMillis() to Time Program Execution 400 Using arraycopy() 401 Environment Properties 402

Object 402 Using clone() and the Cloneable Interface 402 Class 406 ClassLoader 409

Page 9: Java 2: The Complete Reference, Fourth Edition

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

*

Math 410 Transcendental Functions 410 Exponential Functions 410 Rounding Functions 411 Miscellaneous Math Methods 412

StrictMath 412 Compiler 413 Thread, ThreadGroup, and Runnable 413

The Runnable Interface 413 Thread 413 ThreadGroup 416

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

java.lang.ref 425 java.lang.reflect 426

15 java.util Part 1: The CoUections Framework 427 CoUections Overview 429 The Collection Interfaces 430

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

The Collection Classes 436 The ArrayList Class 437 The LinkedList Class 441 The HashSet Class 443 The TreeSet Class 444

Accessing a Collection via an Iterator 445 Using an Iterator 447

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

The Map Interfaces 450 The Map Classes 454

Comparators 458 Using a Comparator 459

The Collection Algorithms 463 Arrays 467 The Legacy Classes and Interfaces 471

The Enumeration Interface 471 Vector 472 Stack 477 Dictionary 479 Hashtable 480

Page 10: Java 2: The Complete Reference, Fourth Edition

C o n t e n t s

Properties 485 Using store() and load() 489

Collections Summary 491

16 java.util Part 2: More Utility Classes 493 StringTokenizer 494 BitSet 496 Date 499

Date Comparison 501 Calendar 501 GregorianCalendar 506 TimeZone 508 SimpleTimeZone 509 Locale 510 Random 511 Observable 514

The Observer Interface 515 An Observer Example 515

Timer and TimerTask 518 The java.util.zip Package 521 The java.util.jar Package 521

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

Directories 528 Using FilenameFilter 529 The listFiles() Alternative 530 Creating Directories 531

The Stream Classes 531 The Byte Streams 532

InputStream 532 OutputStream 533 FilelnputStream 534 FileOutputStream 536 ByteArraylnputStream 538 ByteArrayOutputStream 539 Filtered Byte Streams 541 Buffered Byte Streams 541 SequencelnputStream 545 PrintStream 547 RandomAccessFile 547

The Character Streams 548 Reader 548 Writer 548 FileReader 548 FileWriter 551 CharArrayReader 552 CharArrayWriter 553

Page 11: Java 2: The Complete Reference, Fourth 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

BufferedReader 555 BufferedWriter 556 PushbackReader 557 PrintWriter 558

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

Serialization 563 Serializable 563 Externalizable 564 ObjectOutput 564 ObjectOutputStream 565 Objectlnput 566 ObjectlnputStream 567 A Serialization Example 569 Stream Benefits 571

18 Networking 573 Networking Basics 574

Socket Overview 574 Client/Server 575 Reserved Sockets 575 Proxy Servers 576 Internet Addressing 576

Java and the Net 577 The Networking Classes and Interfaces 577

InetAddress 578 Factory Methods 578 Instance Methods 579

TCP/IP Client Sockets 580 Whois 581

URL 583 Format 583

URLConnection 585 TCP/IP Server Sockets 586 A Caching Proxy HTTP Server 587

Source Code 587 Datagrams 608

DatagramPacket 609 Datagram Server and Client 609

Net Worth 611

19 The Applet Class 613 Applet Basics 614

The Applet Class 615 Applet Architecture 618 An Applet Skeleton 618

Applet Initialization and Termination 620 Overriding update() 621

Simple Applet Display Methods 622

Page 12: Java 2: The Complete Reference, Fourth Edition

C o n t e n t s

Requesting Repainting 624 A Simple Banner Applet 625

Using the Status Window 628 The HTML APPLET Tag 629 Passing Parameters to Applets 630

Improving the Banner Applet 633 getDocumentBase() and getCodeBase() 634 AppletContext and showDocument() 635 The AudioClip Interface 637 The AppletStub Interface 638 Outputting to the Console 638

20 Event Handling 639 Two Event Handling Mechanisms 640 The Delegation Event Model 640

Events 641 Event Sources 641 Event Listeners 642

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

Sources of Events 652 Event Listener Interfaces 653

The ActionListener Interface 654 The AdjustmentListener Interface 654 The ComponentListener Interface 654 The ContainerListener Interface 654 The FocusListener Interface 655 The ItemListener Interface 655 The Key Listener Interface 655 The MouseListener Interface 655 The MouseMotionListener Interface 656 The TextListener Interface 656 The WindowListener Interface 656

Using the Delegation Event Model 656 Handling Mouse Events 657 Handling Keyboard Events 660

Adapter Classes 664 Inner Classes 666

Anonymous Inner Classes 668

Page 13: Java 2: The Complete Reference, Fourth 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 »MSjuailil!«:«

2 1 Introducing the AWT: Working with Windows, Graphics, and Text 671

AWT Classes 672 Window Fundamentals 675

Component 675 Container 676 Panel 676 Window 677 Frame 677 Canvas 677

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

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

Creating a Windowed Program 686 Displaying Information Within a Window 689 Working with Graphics 689

Drawing Lines 689 Drawing Rectangles 690 Drawing Ellipses and Circles 692 Drawing Ares 693 Drawing Polygons 694 Sizing Graphics 695

Working with Color 696 Color Methods 697 Setting the Current Graphics Color 698 A Color Demonstration Applet 698

Setting the Paint Mode 700 Working with Fonts 702

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

Managing Text Output Using FontMetrics 708 Displaying Multiple Lines of Text 710 Centering Text 712 Multiline Text Alignment 713

Exploring Text and Graphics 718

22 Using AWT Controls, Layout Managers, and Menüs 719 Control Fundamentals 720

Adding and Removing Controls 720 Responding to Controls 721

Labels 721 Using Buttons 723

Handling Buttons 723

Page 14: Java 2: The Complete Reference, Fourth Edition

C o n t e n t s

Applying Check Boxes 727 Handling Check Boxes 727

CheckboxGroup 729 Choice Controls 732

Handling Choice Lists 732 Using Lists 735

Handling Lists 736 Managing Scroll Bars 738

Handling Scroll Bars 740 Using a TextField 742

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

FlowLayout 748 BorderLayout 750 Using Insets 752 GridLayout 754 CardLayout 756

Menü Bars and Menüs 759 Dialog Boxes 766 FileDialog 772 Handling Events by Extending AWT Components 774

Extending Button 776 Extending Checkbox 777 Extending a Check Box Group 778 Extending Choice 779 Extending List 779 Extending Scrollbar 781

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

I 23 Images 783 File Formats 784 Image Fundamentais: Creating, Loading, and Displaying 785

Creating an Image Object 785 Loading an Image 785 Displaying an Image 786

ImageObserver 787 ImageObserver Example 789

Double Buffering 791 MediaTracker 795 ImageProducer 799

MemorylmageSource 799 ImageConsumer 801

PixelGrabber 802 ImageFilter 805

CropImageFilter 805 RGBImageFilter 807

Cell Animation 821 Additional Java 2 Imaging Classes 824

Page 15: Java 2: The Complete Reference, Fourth Edition

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

24 Additional Packages 827 The Core Java API Packages 828 Reflection 828 Remote Method Invocation (RMI) 835

A Simple Client/Server Application Using RMI 835 Text Formatting 839

DateFormat Class 839 SimpleDateFormat Class 841

• ifBIIIB Software Development Using Java

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

Installing the BDK 850 Starting the BDK 850 Using the BDK 850

JAR Files 853 Manifest Files 853 The JAR Utility 854

Introspection 855 Design Patterns for Properties 856 Design Patterns for Events 858 Methods 859

Developing a Simple Bean 859 Create a New Bean 860

Using Bound Properties 863 Steps 863

Using the Beanlnfo Interface 865 Constrained Properties 867 Persistence 867 Customizers 867 The Java Beans API 868

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

The JButton Class 879 Check Boxes 882 Radio Buttons 884

Combo Boxes 886 Tabbed Panes 888 Scroll Panes 891

Page 16: Java 2: The Complete Reference, Fourth Edition

C o n t e n t

Trees 893 Tables 898 Exploring Swing 900

27 Migrating from C++ to Java 901 The Differences Between C++ and Java 902

What Java Has Removed from C++ 902 New Features Added by Java 904 Features That Differ 905

Eliminating Pointers 905 Converting Pointer Parameters 906 Converting Pointers that Operate on Arrays 908

C++ Reference Parameters Versus Java Reference Parameters 911 Converting C++ Abstract Classes into Java Interfaces 915 Converting Default Arguments 919 Converting C++ Multiple-Inheritance Hierarchies 921 Destructors Versus Finalization 923

B3EH Äppiying Java

28 The DynamicBillboard Applet 931 The APPLET Tag 932 Source Code Overview 934

DynamicBillboard .ja va 934 BillData.java 942 BillTransition.java 944 ColumnTransition.java 946 FadeTransition.java 949 SmashTransition.java 953 TearTransition.java 956 UnrollTransition.java 960

Dynamic Code 964

29 ImageMenu: An Image-Based Web Menü 967 The Source Image 969 The APPLET Tag 970 The Methods 971

init() 971 update() 971 latelnit() 971 paint() 971 mouseExited() 972 mouseDragged() 972 mouseMoved() 972 mouseReleased() 973 The Code 973

Summary 976

Page 17: Java 2: The Complete Reference, Fourth Edition

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

30 The Lavatron Applet: A Sports Arena Display 977 How Lavatron Works 979 The Source Code 980

The APPLET Tag 980 Lavatron.java 980 IntHash() 985

Hot Lava 987

3 1 Scrabblet: A Multiplayer Word Game 989 Network Security Concerns 990 The Game 991

Scoring 994 The Source Code 996

The APPLET Tag 996 Scrabblet.java 997 IntroCanvas.java 1010 Board.java 1011 Bag.java 1029 Letter.java 1031 ServerConnection.java 1037

The Server Code 1043 Server.java 1043 ClientConnection.java 1047

Enhancing Scrabblet 1051

A Using Java's Documentation Comments 1053 The javadoc Tags 1054

©author 1055 ©deprecated 1055 {©docRootj 1055 @exception 1055 {©link} 1056 ©param 1056 ©return 1056 ©see 1056 ©serial 1057 ©serialData 1057 ©serialField 1057 ©since 1057 ©throws 1057 ©version 1057

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

Index 1061