Java Programming: A Comprehensive Introduction is designed for an introductory programming course using Java. This text takes a logical approach to the presentation of core topics, moving step by step from the basics to more advanced material, with objects being introduced at the appropriate time. The book is divided into three parts:
Part One covers the elements of the Java language and the fundamentals of programming. An introduction to object-oriented design is also included.
Part Two introduces GUI (Graphical User Interface) programming using Swing.
Part Three explores key aspects of Java’s API (Application Programming Interface) library, including the Collections Framework and the concurrency API.
Hallmark Features Presents topics in a clear and logical order. This “straight ahead” approach introduces each new feature in a cohesive, logical sequence.
Introduces objects after the basics. Objects are introduced in Chapter 4, after key elements of the language are covered.
Separates the teaching of the GUI from the teaching of the language elements. The instructor has fl exibility in choosing when to introduce GUI programming.
Includes coverage of Java 7 (JDK 7). Students can learn a modern version of the language.
Provides numerous examples and exercises. Examples given throughout make the purpose and use of program elements clear, while the exercises test the student’s grasp of material. Answers to selected exercises are given in the back of the book.
Pedagogical Highlights Progress Checks reinforce core concepts and provide immediate feedback to the student that key concepts have been learned.
Ask the Expert sections supply additional information or interesting commentary related to the topic at hand.
Try This elements provide step-by-step examples that show core programming topics in action.
Learn more about Java Programming at the book’s web site: www.mhhe.com/schildt1e
TM
Herbert Schildt | Dale Skrien
Java Programming A Comprehensive Introduction
College Programming Series
Java P rogram
m ing
A C
o m p re h e n sive
In tro
d u c tio
n S childt S krien
M D
D A
L IM
#1174731 11/18/11 C Y
A N
M A
G Y
E L
O B
L K
Java Programming
sch2207X_fm_p0i-xxxvi.indd 1 23/12/11 4:29 PM
sch2207X_fm_p0i-xxxvi.indd 2 23/12/11 4:29 PM
Java Programming A Comprehensive Introduction
Herbert Schildt
Dale Skrien Colby College
sch2207X_fm_p0i-xxxvi.indd 3 23/12/11 4:29 PM
JAVA PROGRAMMING: A COMPREHENSIVE INTRODUCTION
Published by McGraw-Hill, a business unit of The McGraw-Hill Companies, Inc., 1221 Avenue of the Americas, New York, NY 10020. Copyright © 2013 by The McGraw-Hill Companies, Inc. All rights reserved. Printed in the United States of America. No part of this publication may be reproduced or distributed in any form or by any means, or stored in a database or retrieval system, without the prior written consent of The McGraw-Hill Companies, Inc., including, but not limited to, in any network or other electronic storage or transmission, or broadcast for distance learning.
Oracle and Java are registered trademarks of Oracle Corporation and/or its affiliates. All other trademarks are the property of their respective owners, and McGraw-Hill makes no claim of ownership by the mention of products that contain these marks.
Some ancillaries, including electronic and print components, may not be available to customers outside the United States.
This book is printed on acid-free paper.
1 2 3 4 5 6 7 8 9 0 DOC/DOC 1 0 9 8 7 6 5 4 3 2 ISBN: 978-0-07-802207-4 MHID 0-07-802207-X
Vice President & Editor-in-Chief: Marty Lange Vice President & Director Specialized Publishing: Janice M. Roerig-Blong Editorial Director: Michael Lange Global Publisher: Raghothaman Srinivasan Senior Marketing Manager: Curt Reynolds Developmental Editor: Robin A. Reed Senior Project Manager: Lisa A. Bruflodt Buyer: Sandy Ludovissy Design Coordinator: Brenda A. Rolwes Media Project Manager: Prashanthi Nadipalli Cover Design by Studio Montage, St. Louis, Missouri Cover Image: © Iconotec/Alamy Compositor: RPK Editorial Services Typeface: 10.5/12 Times Roman Printer: R. R. Donnelley Crawfordsville, IN
Library of Congress Cataloging-in-Publication Data Schildt, Herbert. Java programming : a comprehensive introduction / Herbert Schildt, Dale Skrien. -- 1st ed. p. cm. Includes bibliographical references and index. ISBN 978-0-07-802207-4 1. Java (Computer program language) I. Skrien, Dale John. II. Title. QA76.73.J38S332 2013 005.13’3–dc23 2011047187 www.mhhe.com
sch2207X_fm_p0i-xxxvi.indd 4 23/12/11 4:29 PM
B R I E F C O N T E N T S
PART I ThE JAvA LANguAgE 1 ChAPTER 1 Java Programming Fundamentals 3 ChAPTER 2 Introducing Data Types and Operators 43 ChAPTER 3 Program Control Statements 77 ChAPTER 4 Introducing Classes, Objects, and Methods 119 ChAPTER 5 More Data Types and Operators 155 ChAPTER 6 A Closer Look at Methods and Classes 205 ChAPTER 7 Inheritance 257 ChAPTER 8 Interfaces 303 ChAPTER 9 Packages 327 ChAPTER 10 Exception handling 347 ChAPTER 11 using I/O 383 ChAPTER 12 Multithreaded Programming 435 ChPATER 13 Enumerations, Autoboxing, and Annotations 475 ChAPTER 14 generics 505 ChAPTER 15 Applets and the Remaining Java Keywords 549 ChAPTER 16 Introduction to Object-Oriented Design 569
PART II INTRODuCINg guI PROgRAMMINg WITh SWINg 617
ChAPTER 17 Swing Fundamentals 619 ChAPTER 18 Exploring Swing Controls 659 ChAPTER 19 Working with Menus 711 ChAPTER 20 Dialogs 737 ChAPTER 21 Threading, Applets, and Painting 779
PART III ExPLORINg ThE JAvA API LIBRARy 811 ChAPTER 22 String handling 813 ChAPTER 23 Exploring java.lang 843 ChAPTER 24 Exploring java.util 879 ChAPTER 25 using the Data Structures in the Collections Framework 929 ChAPTER 26 Networking with java.net 985 ChAPTER 27 The Concurrency utilities 1009
APPENDIx A using Java’s Documentation Comments 1059 APPENDIx B An Introduction to Regular Expressions 1067 APPENDIx C Answers to Selected Exercises 1075
INDEx 1129
sch2207X_fm_p0i-xxxvi.indd 5 23/12/11 4:29 PM
sch2207X_fm_p0i-xxxvi.indd 6 23/12/11 4:29 PM
C O N T E N T S
PREFACE xxv
PART I ThE JAvA LANguAgE 1
ChAPTER 1 Java Programming Fundamentals 3 Computing Basics 4 The Hardware Components of a Computer 4 Bits, Bytes, and Binary 5 The Operating System 6
The Program 7
Programming Languages 8 The Java Language 9 The Origins of Java 9 Java’s Contribution to the Internet 11 Java Applets 11 Security 11 Portability 12 Java’s Solution: The Bytecode 12 The Evolution of Java 13
The Key Attributes of Object-Oriented Programming 14
Encapsulation 15 Polymorphism 16 Inheritance 16
The Java Development Kit 17 A First Simple Program 18 Entering the Program 18 Compiling the Program 19 Running the Program 19 The First Sample Program Line by Line 19
Handling Syntax Errors 22 A Second Simple Program 23 Another Data Type 25
sch2207X_fm_p0i-xxxvi.indd 7 23/12/11 4:29 PM
viii contents
Two Control Statements 28 The if Statement 28 The for Loop 30
Create Blocks of Code 32 Semicolons and Positioning 33 Indentation Practices 34 Indentation Practices 34 The Java Keywords 36 Identifiers in Java 37 The Java Class Libraries 38 Exercises 39
ChAPTER 2 Introducing Data Types and Operators 43 Why Data Types are Important 43 Java’s Primitive Types 44 Integers 44 Floating-Point Types 46 Characters 47 The Boolean Type 48
Literals 50 Hexadecimal, Octal, and Binary Literals 51 Character Escape Sequences 52 String Literals 52
A Closer Look at Variables 53 Initializing a Variable 54 Dynamic Initialization 54
The Scope and Lifetime of Variables 55 Operators 58 Arithmetic Operators 58 Increment and Decrement 59
Relational and Logical Operators 60 Short-Circuit Logical Operators 62 The Assignment Operator 64 Shorthand Assignments 64 Type Conversion in Assignments 65 Using a Cast 66 Operator Precedence 68 Expressions 70 Type Conversion in Expressions 70 Spacing and Parentheses 72
Exercises 73
sch2207X_fm_p0i-xxxvi.indd 8 23/12/11 4:29 PM
ixContents
ChAPTER 3 Program Control Statements 77 Input Characters from the Keyboard 78 The i f Statement 79 Nested i f s 81 The i f -e lse - i f Ladder 82 The switch Statement 83 Nested switch Statements 86 The for Loop 90 Some Variations on the for Loop 91 Missing Pieces 92 The Infinite Loop 93 Loops with No Body 93
Declaring Loop Control Variables Inside the for Statement 94 The Enhanced for Loop 95 The while Loop 95 The do-while Loop 97 Use break to Exit a Loop 102 Use break as a Form of goto 104 Use continue 108 Nested Loops 113 Exercises 114
ChAPTER 4 Introducing Classes, Objects, and Methods 119 Class Fundamentals 119 The General Form of a Class 120 Defining a Class 121
How Objects are Created 124 Reference Variables and Assignment 124 Methods 126 Adding a Method to the Vehicle Class 126
Returning from a Method 128 Returning a Value 129 Using Parameters 131 Adding a Parameterized Method to Vehicle 133
Constructors 141 Parameterized Constructors 142 Adding a Constructor to the Vehicle Class 143
The new Operator Revisited 145
sch2207X_fm_p0i-xxxvi.indd 9 23/12/11 4:29 PM
x contents
Garbage Collection and Finalizers 145 The finalize( ) Method 146
The this Keyword 149 Exercises 151
ChAPTER 5 More Data Types and Operators 155 Arrays 155 One-Dimensional Arrays 156
Multidimensional Arrays 161 Two-Dimensional Arrays 161 Irregular Arrays 163 Arrays of Three or More Dimensions 164 Initializing Multidimensional Arrays 164
Alternative Array Declaration Syntax 166 Assigning Array References 166 Using the length Member 168 The For-Each Style for Loop 176 Iterating Over Multidimensional Arrays 179 Applying the Enhanced for 180
Strings 181 Constructing Strings 182 Operating on Strings 182 Arrays of Strings 184 Strings are Immutable 185 Using a String to Control a switch Statement 186
Using Command-Line Arguments 187 The Bitwise Operators 189 The Bitwise AND, OR, XOR, and NOT Operators 189 The Shift Operators 194 Bitwise Shorthand Assignments 196
The ? Operator 200 Exercises 201
ChAPTER 6 A Closer Look at Methods and Classes 205 Controlling Access to Class Members 205 Java’s Access Modifiers 206
Pass Objects to Methods 211 How Arguments are Passed 212 Returning Objects 215 Method Overloading 217
sch2207X_fm_p0i-xxxvi.indd 10 23/12/11 4:29 PM
xiContents
Overloading Constructors 222 Recursion 228 Understanding stat ic 232 Static Variables 233 Static Methods 235 Static Blocks 236
Introducing Nested and Inner Classes 240 Varargs: Variable-Length Arguments 244 Varargs Basics 245 Overloading Varargs Methods 247 Varargs and Ambiguity 249
Exercises 250
ChAPTER 7 Inheritance 257 Inheritance Basics 257 Member Access and Inheritance 260 Constructors and Inheritance 263 Using super to Call Superclass
Constructors 265 Using super to Access Superclass Members 269 Creating a Multilevel Hierarchy 273 When are Constructors Executed? 276 Superclass References
and Subclass Objects 277 Method Overriding 282 Overridden Methods Support
Polymorphism 285 Why Overridden Methods? 287 Applying Method Overriding to TwoDShape 287
Using Abstract Classes 291 Using f inal 296 final Prevents Overriding 296 final Prevents Inheritance 296 Using final with Data Members 297
The Object Class 298 Exercises 299
ChAPTER 8 Interfaces 303 Interface Fundamentals 303 Creating an Interface 304
sch2207X_fm_p0i-xxxvi.indd 11 23/12/11 4:29 PM
xii contents
Implementing an Interface 305 Using Interface References 309 Implementing Multiple Interfaces 311 Constants in Interfaces 319 Interfaces can be Extended 321 Nested Interfaces 322 Final Thoughts on Interfaces 323 Exercises 323
ChAPTER 9 Packages 327 Package Fundamentals 327 Defining a Package 328 Finding Packages and CLASSPATH 329 A Short Package Example 329
Packages and Member Access 331 A Package Access Example 332 Understanding Protected Members 334
Importing Packages 336 Importing Java’s Standard Packages 337
Static Import 341 Exercises 344
ChAPTER 10 Exception handling 347 The Exception Hierarchy 348
Exception Handling Fundamentals 348 Using try and catch 349 A Simple Exception Example 349
The Consequences of an Uncaught Exception 352
Exceptions Enable You to Handle Errors Gracefully 353
Using Multiple catch Clauses 355
Catching Subclass Exceptions 356
try Blocks can be Nested 357
Throwing an Exception 359 Rethrowing an Exception 360
sch2207X_fm_p0i-xxxvi.indd 12 23/12/11 4:29 PM
xiiiContents
A Closer Look at throwable 361
Using f inal ly 363
Using throws 365
Java’s Built-in Exceptions 366
New Exception Features Added by JDK 7 369
Creating Exception Subclasses 370
Exercises 377
ChAPTER 11 using I/O 383 Java’s I/O Is Built on Streams 384 Byte Streams and Character Streams 384 The Byte Stream Classes 384 The Character Stream Classes 385 The Predefined Streams 386 Using the Byte Streams 387 Reading Console Input 388 Writing Console Output 389
Reading and Writing Files Using Byte Streams 390
Inputting from a File 391 Writing to a File 394
Automatically Closing a File 396 Reading and Writing Binary Data 399 Random-Access Files 404 Using Java’s Character-Based Streams 407 Console Input Using Character Streams 407 Console Output Using Character Streams 411
File I/O Using Character Streams 412 Using a FileWriter 412 Using a FileReader 413 File 415 Obtaining a File’s Properties 415 Obtaining a Directory Listing 417 Using FilenameFilter 418 The listFiles( ) Alternative 419 Various File Utility Methods 419
Using Java’s Type Wrappers to Convert Numeric Strings 421
Exercises 430
sch2207X_fm_p0i-xxxvi.indd 13 23/12/11 4:29 PM
xiv contents
ChAPTER 12 Multithreaded Programming 435 Multithreading Fundamentals 435 The Thread Class and Runnable Interface 436 Creating a Thread 437 Some Simple Improvements 440
Creating Multiple Threads 445 Determining When a Thread Ends 447 Thread Priorities 450 Synchronization 451 Using Synchronized Methods 452 The Synchronized Statement 455 Thread Communication Using notify( ) ,
wait( ) , and notifyA l l( ) 458 An Example That Uses wait( ) and notify( ) 458
Suspending, Resuming, and Stopping Threads 464
Exercises 469
ChAPTER 13 Enumerations, Autoboxing, and Annotations 475 Enumerations 475 Enumeration Fundamentals 476
Java Enumerations are Class Types 479
The values( ) and valueO f( ) Methods 479
Constructors, Methods, Instance Variables, and Enumerations 480 Two Important Restrictions 482
Enumerations Inherit Enum 482 Autoboxing 490 Type Wrappers and Boxing 490 Autoboxing Fundamentals 492 Autoboxing and Methods 493 Autoboxing/Unboxing Occurs in Expressions 494 A Word of Warning 496
Annotations (Metadata) 497 Creating and Using an Annotation 497 Built-in Annotations 498
Exercises 500
ChAPTER 14 generics 505 Generics Fundamentals 506 A Simple Generics Example 506
sch2207X_fm_p0i-xxxvi.indd 14 23/12/11 4:29 PM
xvContents
Generics Work Only with Objects 510 Generic Types Differ Based on Their Type Arguments 510 A Generic Class with Two Type Parameters 510 The General Form of a Generic Class 512
Bounded Types 513 Using Wildcard Arguments 516 Bounded Wildcards 519 Generic Methods 522 Generic Constructors 524 Generic Class Hierarchies 525 Generic Interfaces 528 Raw Types and Legacy Code 535 Type Inference with the Diamond Operator 538 Erasure 540 Ambiguity Errors 540 Some Generic Restrictions 541 Type Parameters Can’t be Instantiated 541 Restrictions on Static Members 542 Generic Array Restrictions 542 Generic Exception Restriction 543
Exercises 543
ChAPTER 15 Applets and the Remaining Java Keywords 549 Applet Basics 549 A Complete Applet Skeleton 553 Applet Initialization and Termination 554 A Key Aspect of an Applet’s Architecture 554 Requesting Repainting 555 Using the Status Window 560 Passing Parameters to Applets 561 The Remaining Java Keywords 563 The volatile Modifier 564 The transient Modifier 564 instanceof 564 strictfp 564 assert 565 Native Methods 565
Exercises 567
ChAPTER 16 Introduction to Object-Oriented Design 569 Elegant Software and Why It Matters 570 Properties of Elegant Software 571
sch2207X_fm_p0i-xxxvi.indd 15 23/12/11 4:29 PM
xvi contents
Elegant Methods 573 Naming Conventions 573 Method Cohesion 574 Well-formed Objects 576 Internal Documentation 577 External Documentation 578
Elegant Classes 581 Class Cohesion and the Expert Pattern 581 Avoiding Duplication 583 Complete Interface 585 Design with Change in Mind 586 Demeter’s Law 589
Inheritance versus Delegation 591 UML Class Diagrams 591 Code Reuse Perspective 594 The Is-a Relationship 594 Similar Behavior 597 Polymorphism 600 Costs of Inheritance 600
Design Patterns 603 Adapter Pattern 604 Observer Pattern 607
Exercises 612
PART II INTRODuCINg guI PROgRAMMINg WITh SWINg 617
ChAPTER 17 Swing Fundamentals 619 The Origins and Design Philosophy
of Swing 620
Components and Containers 622 Components 622 Containers 623 The Top-Level Container Panes 623
Layout Managers 624 A First Simple Swing Program 625 The First Swing Example Line by Line 626
Event Handling 631 Events 631 Event Sources 631 Event Listeners 632 Event Classes and Listener Interfaces 632 Adapter Classes 632
sch2207X_fm_p0i-xxxvi.indd 16 23/12/11 4:29 PM
xviiContents
Using a Push Button 635 Introducing JTextF ield 643 Use Anonymous Inner Classes
to Handle Events 655 Exercises 656
ChAPTER 18 Exploring Swing Controls 659 JLabel and ImageIcon 660 The Swing Buttons 663 Handling Action Events 664 Handling Item Events 664 JButton 665 JToggleButton 668 Check Boxes 670 Radio Buttons 672
JTextF ield 675 JScrollPane 685 JL i s t 692 JComboBox 696 Trees 699 JTable 703 A Brief Word about Models 706 Exercises 707
ChAPTER 19 Working with Menus 711 Menu Basics 711 An Overview of JMenuBar , JMenu ,
and JMenuI tem 713 JMenuBar 713 JMenu 714 JMenuItem 715
Create a Main Menu 715 Add Mnemonics and Accelerators
to Menu Items 720 Add Images and Tooltips to Menu Items 723 Use JRadioButtonMenuItem
and JCheckBoxMenuI tem 730 Exercises 733
ChAPTER 20 Dialogs 737 JOptionPane 738 showMessageD ia log( ) 740
sch2207X_fm_p0i-xxxvi.indd 17 23/12/11 4:29 PM
xviii contents
showConfirmD ia log( ) 744 showInputD ia log( ) 748 showOptionD ia log( ) 753 JD ia log 758 Create a Modeless Dialog 762 Select Files with JF i leChooser 763 Exercises 774
ChAPTER 21 Threading, Applets, and Painting 779 Multithreading in Swing 779 Use T imer 786 Create Swing Applets 792 A Simple Swing Applet 793
Painting 800 Painting Fundamentals 800 The Graphics Context 801 Compute the Paintable Area 802 Request Painting 802 A Paint Example 802
Exercises 808
PART III ExPLORINg ThE JAvA API LIBRARy 811
ChAPTER 22 String handling 813 String Fundamentals 813 The String Constructors 814 Three String-Related Language Features 816 String Literals 817 String Concatenation 817 String Concatenation with Other Data Types 817 Overriding toString( ) 818
The length() Method 823 Obtaining the Characters within a String 824 charAt( ) 824 getChars( ) 824 toCharArray( ) 825
String Comparison 826 equals( ) and equalsIgnoreCase( ) 826 equals( ) Versus == 827 regionMatches( ) 828 startsWith( ) and endsWith( ) 828 compareTo( ) and compareToIgnoreCase( ) 829
sch2207X_fm_p0i-xxxvi.indd 18 23/12/11 4:29 PM
xixContents
Using indexOf( ) and lastIndexO f( ) 831 Obtaining a Modified String 833 substring( ) 833 replace( ) 834 trim( ) 835
Changing the Case of Characters Within a String 836
S tr ingBuffer and S tr ingBuilder 839 Exercises 839
ChAPTER 23 Exploring java.lang 843 Primitive Type Wrappers 844 Number 844 Double and Float 845 Byte, Short, Integer, and Long 846 Character 849 Boolean 852 Autoboxing and the Type Wrappers 852
The Math Class 853 The Process Class 857 The ProcessBuilder Class 857 The Runtime Class 859 The System Class 861 Using currentTimeMillis( ) to Time Program Execution 862 Using arraycopy( ) 863 Obtaining Property Values 864 Redirecting Standard I/O Streams 864
The Object Class 866 The C lass Class 866 The Enum Class 868 Thread-Related Classes and The Runnable Interface 868 Other Classes 869 The java . lang Interfaces 869 The Comparable Interface 870 The Appendable Interface 872 The Iterable Interface 873 The Readable Interface 873 The CharSequence Interface 873 The AutoCloseable Interface 874
Exercises 875
sch2207X_fm_p0i-xxxvi.indd 19 23/12/11 4:29 PM
xx contents
ChAPTER 24 Exploring java.util 879 The Locale Class 881
Working with Date and Time 884 Date 884 Calendar and GregorianCalendar 885
Formatting Output with Formatter 890 The Formatter Constructors 890 Formatting Basics 891 Formatting Strings and Characters 894 Formatting Numbers 894 Formatting Date and Time 895 The %n and %% Specifiers 897 Specifying a Minimum Field Width 897 Specifying Precision 898 Using the Format Flags 899 The Uppercase Option 902 Using an Argument Index 902 Formatting for a Different Locale 903 Closing a Formatter 904
Formatting and the printf( ) Method 907 The Scanner Class 909 The Scanner Constructors 909 Scanning Basics 909 Some Scanner Examples 911 Some Other Scanner Features 916
The Random Class 917 Use Observable and Observer 918 The T imer and T imerTask Classes 922 Miscellaneous Utility Classes
and Interfaces 924 Exercises 925
ChAPTER 25 using the Data Structures in the Collections Framework 929
An Overview of Data Structures 930 Stacks and Queues 930 Linked Lists 931 Trees 932 Hash Tables 933 Choosing a Data Structure 933
sch2207X_fm_p0i-xxxvi.indd 20 23/12/11 4:29 PM
xxiContents
Collections Overview 934 The Collection Interfaces 935 The Collection Interface 936 The List Interface 938 The Set Interface 938 The SortedSet Interface 938 The NavigableSet Interface 940 The Queue Interface 940 The Deque Interface 942
The Collection Classes 944 The ArrayList Class 945 The LinkedList Class 948 The HashSet Class 952 The TreeSet Class 954 The LinkedHashSet Class 956 The ArrayDeque Class 957 The PriorityQueue Class 959
Accessing a Collection via an Iterator 960 Using an Iterator 960 The For-Each Alternative to Iterators 964
Working with Maps 964 The Map Interfaces 964 The Map Classes 969
Comparators 974 The Collection Algorithms 976 The Arrays Class 980 The Legacy Classes and Interfaces 981 The Enumeration Interface 981 Vector 981 Stack 981 Dictionary 981 Hashtable 981 Properties 982
Exercises 982
ChAPTER 26 Networking with java.net 985 Networking Fundamentals 985 The Networking Classes and Interfaces 986 The InetAddress Class 987 The Socket Class 989 The URL Class 993 The URLConnection Class 995
sch2207X_fm_p0i-xxxvi.indd 21 23/12/11 4:29 PM
xxii contents
The httpuRLConnection Class 1000 Datagrams 1002 DatagramSocket 1003 DatagramPacket 1003 A Datagram Example 1004
Exercises 1007
ChAPTER 27 The Concurrency utilities 1009 The Concurrent API Packages 1010 java.util.concurrent 1010 java.util.concurrent.atomic 1011 java.util.concurrent.locks 1011
Using Synchronization Objects 1012 Semaphore 1012 CountDownLatch 1015 CyclicBarrier 1018 Exchanger 1020 Phaser 1023
Using an Executor 1030 A Simple Executor Example 1031 Using Cal lable and Future 1033 The T imeUnit Enumeration 1036 The Concurrent Collections 1038 Locks 1038 Atomic Operations 1041 Parallel Programming via the Fork/
Join Framework 1042 The Main Fork/Join Classes 1043 ForkJoinTask 1043 RecursiveAction 1044 RecursiveTask 1044 ForkJoinPool 1045
The Divide-and-Conquer Strategy 1046 A Simple First Fork/Join Example 1047 Understanding the Impact of the Level of Parallelism 1049 An Example That Uses RecursiveTask 1052 Executing a Task Asynchronously 1054
sch2207X_fm_p0i-xxxvi.indd 22 23/12/11 4:29 PM
xxiiiContents
The Concurrency Utilities versus Java’s Traditional Approach 1055 Exercises 1056
APPENDIx A using Java’s Documentation Comments 1059 The javadoc Tags 1059
The General Form of a Documentation Comment 1063
What javadoc Outputs 1064
An Example That Uses Documentation
Comments 1064
APPENDIx B An Introduction to Regular Expressions 1067
The Pattern Class 1067
The Matcher Class 1068
Regular Expression Syntax Basics 1068
Demonstrating Pattern Matching 1069
Using the Wildcard Character and Quantifiers 1071
Working with Classes of Characters 1073
Using replaceAll( ) 1073
The String Class Connection 1074
Things to Explore 1074
APPENDIx C Answers to Selected Exercises 1075
INDEx 1129
sch2207X_fm_p0i-xxxvi.indd 23 23/12/11 4:29 PM
sch2207X_fm_p0i-xxxvi.indd 24 23/12/11 4:29 PM
This book teaches the fundamentals of programming by way of the Java language. It assumes no prior programming experience and begins with the basics, such as how to compile and run a Java program. Next, it discusses the keywords, opera- tors, and constructs that form the Java language. The book also covers several parts of the Java Application Programming Interface (API) library, including Swing, which is the framework used to create programs that have a graphical user interface (GUI), and the Collections Framework, which is used to store collections of objects. In short, this book is intended as a comprehensive introduction to Java. Like most computer languages, Java has evolved over time. At the time of this writing, the latest version is Java 7 (JDK 7), and this is the version of Java covered by this book. However, most of the material is also applicable to other recent versions of Java, such as version 6.
A STRAIghT AhEAD APPROACh This book uses what we characterize as a “straight ahead” approach. By this, we mean that topics are introduced in a cohesive sequence that is intended to keep the focus of each discussion on the topic at hand. This approach simplifies and streamlines the presentation. On occasions when a departure from the main presentation flow is nec- essary, we attempt to do so in a way that minimizes the disruption. The goal of our approach is to present the Java language in a way that clearly shows the interrelation- ship of its parts, rather than as a jumble of disconnected features. To help manage the material, this book is organized into three parts. Part One describes the elements that define the Java language and the core elements of pro- gramming. It begins with an overview of Java followed by the basic concepts of data types, operators, and control statements. It then progressively introduces the more sophisticated features of the language, such as classes, methods, inheritance, inter- faces, packages, exceptions, multithreading, and generics. Part One also describes I/O, because it is integral to many Java programs, and applet fundamentals, because the applet is a quintessential Java application. Part One ends with a chapter on object- oriented design. As it relates directly to Part One, our “straight ahead” approach keeps the focus on the elements of the Java language and the fundamentals of programming, with each new section building on the foundation of what comes before. Where possible, we avoid digressions that distract from the main topic. For example, discussions of GUI programming via Swing are handled in Part Two, rather than being intermixed with discussions of basic concepts. This way, the presentation in Part One remains firmly rooted in the core issues of Java and of programming.
PREFACE
sch2207X_fm_p0i-xxxvi.indd 25 23/12/11 4:29 PM
xxvi
Part Two introduces Swing. It begins with an overview of GUI programming with Swing, including the basic concepts of components, events, and layout manag- ers. Subsequent chapters advance in an orderly fashion, presenting an overview of several Swing components, followed by menus, dialogs, painting, and so on. This “straight ahead” approach is intended to help students more easily integrate each new feature into the overall picture they are forming of the Swing framework. Part Three explores portions of the Java API library. Because the API library is very large, it is not possible to discuss it in its entirety in this book. Instead, we focus on what we consider to be those parts of the library with which every Java pro- grammer should be familiar. In addition to covering large portions of java.lang and java.util (with special emphasis on the Collections Framework), we also present an overview of networking, and introduce the concurrency API, including the Fork/Join Framework. The material is presented in a straightforward manner that is designed to give the student a solid overview of several core library elements.
OBJECTS SOON…BuT NOT TOO SOON One of the first commonly-asked questions about a programming book is whether it uses an “objects early” or an “objects late” approach to teaching the key tenets of object-oriented programming. Of course, what constitutes “early” or “late” can be somewhat subjective, and neither term precisely describes the organization of this book. The phrase we use to characterize our approach is “objects soon, but not too soon.” Our goal is to introduce objects at the appropriate time for the student. We believe that this is not until key features of the language have been learned. Towards this end, the focus of the first three chapters is on the fundamentals of the Java language, such as its syntax, data types, operators, and control statements. We believe that mastery of these elements is a necessary first step because they form the foundation of the language, and the foundation of programming in general. (In other words, it is difficult to write meaningful programs without understanding these ele- ments.) In our view, only after the basic elements of a program have been learned, is the student ready to move forward to objects. After the book has covered the fundamentals, objects are introduced in Chapter 4, and from that point on, object-oriented features, techniques, and concepts are inte- grated into the remaining chapters. Additionally, objects are introduced in a carefully paced, step-by-step fashion. This is intended to help the student grasp each new fea- ture in context, and without being overwhelmed.
PEDAgOgICAL FEATuRES This book includes several pedagogical elements to facilitate and reinforce learning. Each feature helps ensure that students are fully aware of key skills, can gauge their advancement, and can verify that all concepts are learned.
j Key Skills & Concepts: Each chapter begins with a list that identifies the key skills and concepts presented in the chapter.
j Ask the Expert: At various points throughout the book are Ask the Expert boxes. These contain additional information or interesting commentary about
preface
sch2207X_fm_p0i-xxxvi.indd 26 23/12/11 4:29 PM
a topic, and use a Question/Answer format. They provide supplemental infor- mation without disrupting the main presentation flow.
j Try This Elements: Each chapter contains one or more Try This elements. These are step-by-step examples that walk through the development of a program that demonstrates an aspect of Java related to the chapter’s topic. Typically, these are longer examples that show a feature in a more practical setting.
j Progress Checks: Throughout each chapter, Progress Checks are presented to test the student’s understanding of the preceding section. The answers to these questions are at the bottom of the same page.
j Exercises: Each chapter concludes with exercises that include short answer, fill-in-the-blank, and true/false questions, and coding exercises. The answers to selected exercises are in Appendix C.
ACM RECOMMENDATIONS The 2008 update to the ACM Curricula Recommendations (http://www.acm.org/ education/curricula/ComputerScience2008.pdf) recommends that all computer science students be fluent in at least one programming language and have some understanding of object-oriented and event-driven programming. We believe that students who learn the material covered by this book will have the desired knowledge and skills. We have included in the book not just an introduction to programming using the Java language, but broader coverage that includes advanced Java features, the Swing framework, and large parts of several important API packages. The first part of the book covers a significant portion of the topics in the Programming Fundamentals (PF) knowledge area of the ACM Recommendations (the main exceptions being the knowledge units FoundationsInformationSecurity and SecureProgramming). The first part also includes a chapter on object-oriented design, which covers a number of the topics in the PL/ObjectOrientedProgramming and SE/ SoftwareDesign knowledge units. The second part of the book, which introduces GUI programming with Swing, addresses some of the topics in the knowledge unit HC/GUIProgramming. The third part includes, among others, topics that relate to concurrency. In fact, we devote Chapters 12 and 27 to multithreading and concurrency because we feel, as the ACM Curricular Recommendations discuss, that concurrency is becoming increasingly relevant to the discipline of computer science.
ONLINE RESOuRCES Students can access all of the source code for the programs in the text at the website that accompanies Java Programming: A Comprehensive Approach: www.mhhe.com/ schildt1e. This site also offers a number of useful resources for the Java instructor.
j A Solutions manual for end-of-chapter exercises.
Preface xxvii
sch2207X_fm_p0i-xxxvi.indd 27 23/12/11 4:29 PM
xxviii preface
j Instructor Notes, including suggested curricula and suggestions for teaching particular topics.
j Supplemental Exercises that can be used to create quizzes and tests. j PowerPoint Slides that serve as an outline for in-class instruction.
Please contact your McGraw-Hill representative for access information.
Additional instructor resources include:
This text is available as an eBook at www.CourseSmart.com. At CourseSmart your students can take advantage of significant savings off the cost of a print textbook, reduce their impact on the environment, and gain access to powerful web tools for learning. CourseSmart eBooks can be viewed online or downloaded to a computer. The eBooks allow students to do full text searches, add highlighting and notes, and share notes with classmates. CourseSmart has the largest selection of eBooks available anywhere. Visit www.CourseSmart.com to learn more and to try a sample chapter.
Craft your teaching resources to match the way you teach! With McGraw-Hill Create™, www.mcgrawhillcreate.com, you can easily rearrange chapters, combine material from other content sources, and quickly upload content you have written, such as your course syllabus or teaching notes. Find the content you need in Create by searching through thousands of leading McGraw-Hill textbooks. Arrange your book to fit your teaching style. Create even allows you to personalize your book’s appearance by selecting the cover and adding your name, school, and course infor- mation. Order a Create book and you’ll receive a complimentary print review copy in 3–5 business days or a complimentary electronic review copy (eComp) via email in minutes. Go to www.mcgrawhillcreate.com today and register to experience how McGraw-Hill Create™ empowers you to teach your students your way.
ACKNOWLEDgMENTS We wish to acknowledge the many contributions made by the following people at McGraw-Hill, without whom this book would not exist. They have made working on the book a delight.
Editorial Director, Michael Lange Global Publisher, Raghu Srinivasan Senior Marketing Manager, Curt Reynolds Developmental Editor, Robin Reed Developmental Editor, Kathryn Neubauer
sch2207X_fm_p0i-xxxvi.indd 28 23/12/11 4:29 PM
xxixPreface
Senior Project Manager, Lisa Bruflodt Design Coordinator, Brenda Rolwes Production Editor, Rose Kernan
We would also like to thank the following reviewers for their many helpful comments, which were much appreciated.
Bill Barge, Trine University Chris Bennett, University of Maine–Farmington Augusto Casas, St Thomas Aquinas College I-ping Chu, DePaul University Vasil Hnatyshin, Rowan University Rodney Hoffman, Occidental College David Kamper Sr., Northeastern Illinois University BJ Tjaden, Anne Arundel Community College Richard Weiss, Evergreen State College James Braman, Towson University Steve Cooper, Stanford University Michael Main, University of Colorado—Boulder Jay McCarthy, Brigham Young University Robert Moll, University of Massachusetts—Amherst Jagadeesh Nandigam, Grand Valley State University Gurpur Prabhu, Iowa State University Daisy Sang, California State Polytechnic University Mark Sherriff, University of Virginia Joslyn Smith, Florida International University James Young, University of Manitoba
Finally, and most importantly, we would like to thank our families for their support during the preparation of this book.
sch2207X_fm_p0i-xxxvi.indd 29 23/12/11 4:29 PM
sch2207X_fm_p0i-xxxvi.indd 30 23/12/11 4:29 PM
About the Authors
Herbert Schildt has been writing about programming since 1984 and is the author of several books on Java, C++, C, and C#. His programming books have sold millions of copies worldwide and have been widely translated. Although he is interested in all facets of computing, his primary focus is computer languages, including the standardization of languages. Schildt holds BA and MCS degrees from the University of Illinois, Urbana/Champaign. He provided the initial drafts for most of the chapters in this book.
Dale Skrien has been teaching mathematics and computer science at Colby College since 1980 and has been teaching Java since 1996. His interest in teaching stu- dents not just how to program, but how to program well, led to the publication of his textbook Object-Oriented Design using Java by McGraw-Hill. He holds a BA degree from St. Olaf College, MS degrees from the University of Illinois and the University of Washington, and a PhD degree from the University of Washington. In addition to contributions throughout the book, he provided Chapter 16, which introduces object-oriented design. He also provided the online supplements for this book.Java Programming: A Comprehensive Introduction is designed for an introductory programming course using Java. This text takes a logical approach to the presentation of core topics, moving step by step from the basics to more advanced material, with objects being introduced at the appropriate time. The book is divided into three parts:
Part One covers the elements of the Java language and the fundamentals of programming. An introduction to object-oriented design is also included.
Part Two introduces GUI (Graphical User Interface) programming using Swing.
Part Three explores key aspects of Java’s API (Application Programming Interface) library, including the Collections Framework and the concurrency API.
Hallmark Features Presents topics in a clear and logical order. This “straight ahead” approach introduces each new feature in a cohesive, logical sequence.
Introduces objects after the basics. Objects are introduced in Chapter 4, after key elements of the language are covered.
Separates the teaching of the GUI from the teaching of the language elements. The instructor has fl exibility in choosing when to introduce GUI programming.
Includes coverage of Java 7 (JDK 7). Students can learn a modern version of the language.
Provides numerous examples and exercises. Examples given throughout make the purpose and use of program elements clear, while the exercises test the student’s grasp of material. Answers to selected exercises are given in the back of the book.
Pedagogical Highlights Progress Checks reinforce core concepts and provide immediate feedback to the student that key concepts have been learned.
Ask the Expert sections supply additional information or interesting commentary related to the topic at hand.
Try This elements provide step-by-step examples that show core programming topics in action.
Learn more about Java Programming at the book’s web site: www.mhhe.com/schildt1e
TM
Herbert Schildt | Dale Skrien
Java Programming A Comprehensive Introduction
College Programming Series
Java P rogram
m ing
A C
o m p re h e n sive
In tro
d u c tio
n S childt S krien
M D
D A
L IM
#1174731 11/18/11 C Y
A N
M A
G Y
E L
O B
L K
Java Programming
sch2207X_fm_p0i-xxxvi.indd 1 23/12/11 4:29 PM
sch2207X_fm_p0i-xxxvi.indd 2 23/12/11 4:29 PM
Java Programming A Comprehensive Introduction
Herbert Schildt
Dale Skrien Colby College
sch2207X_fm_p0i-xxxvi.indd 3 23/12/11 4:29 PM
JAVA PROGRAMMING: A COMPREHENSIVE INTRODUCTION
Published by McGraw-Hill, a business unit of The McGraw-Hill Companies, Inc., 1221 Avenue of the Americas, New York, NY 10020. Copyright © 2013 by The McGraw-Hill Companies, Inc. All rights reserved. Printed in the United States of America. No part of this publication may be reproduced or distributed in any form or by any means, or stored in a database or retrieval system, without the prior written consent of The McGraw-Hill Companies, Inc., including, but not limited to, in any network or other electronic storage or transmission, or broadcast for distance learning.
Oracle and Java are registered trademarks of Oracle Corporation and/or its affiliates. All other trademarks are the property of their respective owners, and McGraw-Hill makes no claim of ownership by the mention of products that contain these marks.
Some ancillaries, including electronic and print components, may not be available to customers outside the United States.
This book is printed on acid-free paper.
1 2 3 4 5 6 7 8 9 0 DOC/DOC 1 0 9 8 7 6 5 4 3 2 ISBN: 978-0-07-802207-4 MHID 0-07-802207-X
Vice President & Editor-in-Chief: Marty Lange Vice President & Director Specialized Publishing: Janice M. Roerig-Blong Editorial Director: Michael Lange Global Publisher: Raghothaman Srinivasan Senior Marketing Manager: Curt Reynolds Developmental Editor: Robin A. Reed Senior Project Manager: Lisa A. Bruflodt Buyer: Sandy Ludovissy Design Coordinator: Brenda A. Rolwes Media Project Manager: Prashanthi Nadipalli Cover Design by Studio Montage, St. Louis, Missouri Cover Image: © Iconotec/Alamy Compositor: RPK Editorial Services Typeface: 10.5/12 Times Roman Printer: R. R. Donnelley Crawfordsville, IN
Library of Congress Cataloging-in-Publication Data Schildt, Herbert. Java programming : a comprehensive introduction / Herbert Schildt, Dale Skrien. -- 1st ed. p. cm. Includes bibliographical references and index. ISBN 978-0-07-802207-4 1. Java (Computer program language) I. Skrien, Dale John. II. Title. QA76.73.J38S332 2013 005.13’3–dc23 2011047187 www.mhhe.com
sch2207X_fm_p0i-xxxvi.indd 4 23/12/11 4:29 PM
B R I E F C O N T E N T S
PART I ThE JAvA LANguAgE 1 ChAPTER 1 Java Programming Fundamentals 3 ChAPTER 2 Introducing Data Types and Operators 43 ChAPTER 3 Program Control Statements 77 ChAPTER 4 Introducing Classes, Objects, and Methods 119 ChAPTER 5 More Data Types and Operators 155 ChAPTER 6 A Closer Look at Methods and Classes 205 ChAPTER 7 Inheritance 257 ChAPTER 8 Interfaces 303 ChAPTER 9 Packages 327 ChAPTER 10 Exception handling 347 ChAPTER 11 using I/O 383 ChAPTER 12 Multithreaded Programming 435 ChPATER 13 Enumerations, Autoboxing, and Annotations 475 ChAPTER 14 generics 505 ChAPTER 15 Applets and the Remaining Java Keywords 549 ChAPTER 16 Introduction to Object-Oriented Design 569
PART II INTRODuCINg guI PROgRAMMINg WITh SWINg 617
ChAPTER 17 Swing Fundamentals 619 ChAPTER 18 Exploring Swing Controls 659 ChAPTER 19 Working with Menus 711 ChAPTER 20 Dialogs 737 ChAPTER 21 Threading, Applets, and Painting 779
PART III ExPLORINg ThE JAvA API LIBRARy 811 ChAPTER 22 String handling 813 ChAPTER 23 Exploring java.lang 843 ChAPTER 24 Exploring java.util 879 ChAPTER 25 using the Data Structures in the Collections Framework 929 ChAPTER 26 Networking with java.net 985 ChAPTER 27 The Concurrency utilities 1009
APPENDIx A using Java’s Documentation Comments 1059 APPENDIx B An Introduction to Regular Expressions 1067 APPENDIx C Answers to Selected Exercises 1075
INDEx 1129
sch2207X_fm_p0i-xxxvi.indd 5 23/12/11 4:29 PM
sch2207X_fm_p0i-xxxvi.indd 6 23/12/11 4:29 PM
C O N T E N T S
PREFACE xxv
PART I ThE JAvA LANguAgE 1
ChAPTER 1 Java Programming Fundamentals 3 Computing Basics 4 The Hardware Components of a Computer 4 Bits, Bytes, and Binary 5 The Operating System 6
The Program 7
Programming Languages 8 The Java Language 9 The Origins of Java 9 Java’s Contribution to the Internet 11 Java Applets 11 Security 11 Portability 12 Java’s Solution: The Bytecode 12 The Evolution of Java 13
The Key Attributes of Object-Oriented Programming 14
Encapsulation 15 Polymorphism 16 Inheritance 16
The Java Development Kit 17 A First Simple Program 18 Entering the Program 18 Compiling the Program 19 Running the Program 19 The First Sample Program Line by Line 19
Handling Syntax Errors 22 A Second Simple Program 23 Another Data Type 25
sch2207X_fm_p0i-xxxvi.indd 7 23/12/11 4:29 PM
viii contents
Two Control Statements 28 The if Statement 28 The for Loop 30
Create Blocks of Code 32 Semicolons and Positioning 33 Indentation Practices 34 Indentation Practices 34 The Java Keywords 36 Identifiers in Java 37 The Java Class Libraries 38 Exercises 39
ChAPTER 2 Introducing Data Types and Operators 43 Why Data Types are Important 43 Java’s Primitive Types 44 Integers 44 Floating-Point Types 46 Characters 47 The Boolean Type 48
Literals 50 Hexadecimal, Octal, and Binary Literals 51 Character Escape Sequences 52 String Literals 52
A Closer Look at Variables 53 Initializing a Variable 54 Dynamic Initialization 54
The Scope and Lifetime of Variables 55 Operators 58 Arithmetic Operators 58 Increment and Decrement 59
Relational and Logical Operators 60 Short-Circuit Logical Operators 62 The Assignment Operator 64 Shorthand Assignments 64 Type Conversion in Assignments 65 Using a Cast 66 Operator Precedence 68 Expressions 70 Type Conversion in Expressions 70 Spacing and Parentheses 72
Exercises 73
sch2207X_fm_p0i-xxxvi.indd 8 23/12/11 4:29 PM
ixContents
ChAPTER 3 Program Control Statements 77 Input Characters from the Keyboard 78 The i f Statement 79 Nested i f s 81 The i f -e lse - i f Ladder 82 The switch Statement 83 Nested switch Statements 86 The for Loop 90 Some Variations on the for Loop 91 Missing Pieces 92 The Infinite Loop 93 Loops with No Body 93
Declaring Loop Control Variables Inside the for Statement 94 The Enhanced for Loop 95 The while Loop 95 The do-while Loop 97 Use break to Exit a Loop 102 Use break as a Form of goto 104 Use continue 108 Nested Loops 113 Exercises 114
ChAPTER 4 Introducing Classes, Objects, and Methods 119 Class Fundamentals 119 The General Form of a Class 120 Defining a Class 121
How Objects are Created 124 Reference Variables and Assignment 124 Methods 126 Adding a Method to the Vehicle Class 126
Returning from a Method 128 Returning a Value 129 Using Parameters 131 Adding a Parameterized Method to Vehicle 133
Constructors 141 Parameterized Constructors 142 Adding a Constructor to the Vehicle Class 143
The new Operator Revisited 145
sch2207X_fm_p0i-xxxvi.indd 9 23/12/11 4:29 PM
x contents
Garbage Collection and Finalizers 145 The finalize( ) Method 146
The this Keyword 149 Exercises 151
ChAPTER 5 More Data Types and Operators 155 Arrays 155 One-Dimensional Arrays 156
Multidimensional Arrays 161 Two-Dimensional Arrays 161 Irregular Arrays 163 Arrays of Three or More Dimensions 164 Initializing Multidimensional Arrays 164
Alternative Array Declaration Syntax 166 Assigning Array References 166 Using the length Member 168 The For-Each Style for Loop 176 Iterating Over Multidimensional Arrays 179 Applying the Enhanced for 180
Strings 181 Constructing Strings 182 Operating on Strings 182 Arrays of Strings 184 Strings are Immutable 185 Using a String to Control a switch Statement 186
Using Command-Line Arguments 187 The Bitwise Operators 189 The Bitwise AND, OR, XOR, and NOT Operators 189 The Shift Operators 194 Bitwise Shorthand Assignments 196
The ? Operator 200 Exercises 201
ChAPTER 6 A Closer Look at Methods and Classes 205 Controlling Access to Class Members 205 Java’s Access Modifiers 206
Pass Objects to Methods 211 How Arguments are Passed 212 Returning Objects 215 Method Overloading 217
sch2207X_fm_p0i-xxxvi.indd 10 23/12/11 4:29 PM
xiContents
Overloading Constructors 222 Recursion 228 Understanding stat ic 232 Static Variables 233 Static Methods 235 Static Blocks 236
Introducing Nested and Inner Classes 240 Varargs: Variable-Length Arguments 244 Varargs Basics 245 Overloading Varargs Methods 247 Varargs and Ambiguity 249
Exercises 250
ChAPTER 7 Inheritance 257 Inheritance Basics 257 Member Access and Inheritance 260 Constructors and Inheritance 263 Using super to Call Superclass
Constructors 265 Using super to Access Superclass Members 269 Creating a Multilevel Hierarchy 273 When are Constructors Executed? 276 Superclass References
and Subclass Objects 277 Method Overriding 282 Overridden Methods Support
Polymorphism 285 Why Overridden Methods? 287 Applying Method Overriding to TwoDShape 287
Using Abstract Classes 291 Using f inal 296 final Prevents Overriding 296 final Prevents Inheritance 296 Using final with Data Members 297
The Object Class 298 Exercises 299
ChAPTER 8 Interfaces 303 Interface Fundamentals 303 Creating an Interface 304
sch2207X_fm_p0i-xxxvi.indd 11 23/12/11 4:29 PM
xii contents
Implementing an Interface 305 Using Interface References 309 Implementing Multiple Interfaces 311 Constants in Interfaces 319 Interfaces can be Extended 321 Nested Interfaces 322 Final Thoughts on Interfaces 323 Exercises 323
ChAPTER 9 Packages 327 Package Fundamentals 327 Defining a Package 328 Finding Packages and CLASSPATH 329 A Short Package Example 329
Packages and Member Access 331 A Package Access Example 332 Understanding Protected Members 334
Importing Packages 336 Importing Java’s Standard Packages 337
Static Import 341 Exercises 344
ChAPTER 10 Exception handling 347 The Exception Hierarchy 348
Exception Handling Fundamentals 348 Using try and catch 349 A Simple Exception Example 349
The Consequences of an Uncaught Exception 352
Exceptions Enable You to Handle Errors Gracefully 353
Using Multiple catch Clauses 355
Catching Subclass Exceptions 356
try Blocks can be Nested 357
Throwing an Exception 359 Rethrowing an Exception 360
sch2207X_fm_p0i-xxxvi.indd 12 23/12/11 4:29 PM
xiiiContents
A Closer Look at throwable 361
Using f inal ly 363
Using throws 365
Java’s Built-in Exceptions 366
New Exception Features Added by JDK 7 369
Creating Exception Subclasses 370
Exercises 377
ChAPTER 11 using I/O 383 Java’s I/O Is Built on Streams 384 Byte Streams and Character Streams 384 The Byte Stream Classes 384 The Character Stream Classes 385 The Predefined Streams 386 Using the Byte Streams 387 Reading Console Input 388 Writing Console Output 389
Reading and Writing Files Using Byte Streams 390
Inputting from a File 391 Writing to a File 394
Automatically Closing a File 396 Reading and Writing Binary Data 399 Random-Access Files 404 Using Java’s Character-Based Streams 407 Console Input Using Character Streams 407 Console Output Using Character Streams 411
File I/O Using Character Streams 412 Using a FileWriter 412 Using a FileReader 413 File 415 Obtaining a File’s Properties 415 Obtaining a Directory Listing 417 Using FilenameFilter 418 The listFiles( ) Alternative 419 Various File Utility Methods 419
Using Java’s Type Wrappers to Convert Numeric Strings 421
Exercises 430
sch2207X_fm_p0i-xxxvi.indd 13 23/12/11 4:29 PM
xiv contents
ChAPTER 12 Multithreaded Programming 435 Multithreading Fundamentals 435 The Thread Class and Runnable Interface 436 Creating a Thread 437 Some Simple Improvements 440
Creating Multiple Threads 445 Determining When a Thread Ends 447 Thread Priorities 450 Synchronization 451 Using Synchronized Methods 452 The Synchronized Statement 455 Thread Communication Using notify( ) ,
wait( ) , and notifyA l l( ) 458 An Example That Uses wait( ) and notify( ) 458
Suspending, Resuming, and Stopping Threads 464
Exercises 469
ChAPTER 13 Enumerations, Autoboxing, and Annotations 475 Enumerations 475 Enumeration Fundamentals 476
Java Enumerations are Class Types 479
The values( ) and valueO f( ) Methods 479
Constructors, Methods, Instance Variables, and Enumerations 480 Two Important Restrictions 482
Enumerations Inherit Enum 482 Autoboxing 490 Type Wrappers and Boxing 490 Autoboxing Fundamentals 492 Autoboxing and Methods 493 Autoboxing/Unboxing Occurs in Expressions 494 A Word of Warning 496
Annotations (Metadata) 497 Creating and Using an Annotation 497 Built-in Annotations 498
Exercises 500
ChAPTER 14 generics 505 Generics Fundamentals 506 A Simple Generics Example 506
sch2207X_fm_p0i-xxxvi.indd 14 23/12/11 4:29 PM
xvContents
Generics Work Only with Objects 510 Generic Types Differ Based on Their Type Arguments 510 A Generic Class with Two Type Parameters 510 The General Form of a Generic Class 512
Bounded Types 513 Using Wildcard Arguments 516 Bounded Wildcards 519 Generic Methods 522 Generic Constructors 524 Generic Class Hierarchies 525 Generic Interfaces 528 Raw Types and Legacy Code 535 Type Inference with the Diamond Operator 538 Erasure 540 Ambiguity Errors 540 Some Generic Restrictions 541 Type Parameters Can’t be Instantiated 541 Restrictions on Static Members 542 Generic Array Restrictions 542 Generic Exception Restriction 543
Exercises 543
ChAPTER 15 Applets and the Remaining Java Keywords 549 Applet Basics 549 A Complete Applet Skeleton 553 Applet Initialization and Termination 554 A Key Aspect of an Applet’s Architecture 554 Requesting Repainting 555 Using the Status Window 560 Passing Parameters to Applets 561 The Remaining Java Keywords 563 The volatile Modifier 564 The transient Modifier 564 instanceof 564 strictfp 564 assert 565 Native Methods 565
Exercises 567
ChAPTER 16 Introduction to Object-Oriented Design 569 Elegant Software and Why It Matters 570 Properties of Elegant Software 571
sch2207X_fm_p0i-xxxvi.indd 15 23/12/11 4:29 PM
xvi contents
Elegant Methods 573 Naming Conventions 573 Method Cohesion 574 Well-formed Objects 576 Internal Documentation 577 External Documentation 578
Elegant Classes 581 Class Cohesion and the Expert Pattern 581 Avoiding Duplication 583 Complete Interface 585 Design with Change in Mind 586 Demeter’s Law 589
Inheritance versus Delegation 591 UML Class Diagrams 591 Code Reuse Perspective 594 The Is-a Relationship 594 Similar Behavior 597 Polymorphism 600 Costs of Inheritance 600
Design Patterns 603 Adapter Pattern 604 Observer Pattern 607
Exercises 612
PART II INTRODuCINg guI PROgRAMMINg WITh SWINg 617
ChAPTER 17 Swing Fundamentals 619 The Origins and Design Philosophy
of Swing 620
Components and Containers 622 Components 622 Containers 623 The Top-Level Container Panes 623
Layout Managers 624 A First Simple Swing Program 625 The First Swing Example Line by Line 626
Event Handling 631 Events 631 Event Sources 631 Event Listeners 632 Event Classes and Listener Interfaces 632 Adapter Classes 632
sch2207X_fm_p0i-xxxvi.indd 16 23/12/11 4:29 PM
xviiContents
Using a Push Button 635 Introducing JTextF ield 643 Use Anonymous Inner Classes
to Handle Events 655 Exercises 656
ChAPTER 18 Exploring Swing Controls 659 JLabel and ImageIcon 660 The Swing Buttons 663 Handling Action Events 664 Handling Item Events 664 JButton 665 JToggleButton 668 Check Boxes 670 Radio Buttons 672
JTextF ield 675 JScrollPane 685 JL i s t 692 JComboBox 696 Trees 699 JTable 703 A Brief Word about Models 706 Exercises 707
ChAPTER 19 Working with Menus 711 Menu Basics 711 An Overview of JMenuBar , JMenu ,
and JMenuI tem 713 JMenuBar 713 JMenu 714 JMenuItem 715
Create a Main Menu 715 Add Mnemonics and Accelerators
to Menu Items 720 Add Images and Tooltips to Menu Items 723 Use JRadioButtonMenuItem
and JCheckBoxMenuI tem 730 Exercises 733
ChAPTER 20 Dialogs 737 JOptionPane 738 showMessageD ia log( ) 740
sch2207X_fm_p0i-xxxvi.indd 17 23/12/11 4:29 PM
xviii contents
showConfirmD ia log( ) 744 showInputD ia log( ) 748 showOptionD ia log( ) 753 JD ia log 758 Create a Modeless Dialog 762 Select Files with JF i leChooser 763 Exercises 774
ChAPTER 21 Threading, Applets, and Painting 779 Multithreading in Swing 779 Use T imer 786 Create Swing Applets 792 A Simple Swing Applet 793
Painting 800 Painting Fundamentals 800 The Graphics Context 801 Compute the Paintable Area 802 Request Painting 802 A Paint Example 802
Exercises 808
PART III ExPLORINg ThE JAvA API LIBRARy 811
ChAPTER 22 String handling 813 String Fundamentals 813 The String Constructors 814 Three String-Related Language Features 816 String Literals 817 String Concatenation 817 String Concatenation with Other Data Types 817 Overriding toString( ) 818
The length() Method 823 Obtaining the Characters within a String 824 charAt( ) 824 getChars( ) 824 toCharArray( ) 825
String Comparison 826 equals( ) and equalsIgnoreCase( ) 826 equals( ) Versus == 827 regionMatches( ) 828 startsWith( ) and endsWith( ) 828 compareTo( ) and compareToIgnoreCase( ) 829
sch2207X_fm_p0i-xxxvi.indd 18 23/12/11 4:29 PM
xixContents
Using indexOf( ) and lastIndexO f( ) 831 Obtaining a Modified String 833 substring( ) 833 replace( ) 834 trim( ) 835
Changing the Case of Characters Within a String 836
S tr ingBuffer and S tr ingBuilder 839 Exercises 839
ChAPTER 23 Exploring java.lang 843 Primitive Type Wrappers 844 Number 844 Double and Float 845 Byte, Short, Integer, and Long 846 Character 849 Boolean 852 Autoboxing and the Type Wrappers 852
The Math Class 853 The Process Class 857 The ProcessBuilder Class 857 The Runtime Class 859 The System Class 861 Using currentTimeMillis( ) to Time Program Execution 862 Using arraycopy( ) 863 Obtaining Property Values 864 Redirecting Standard I/O Streams 864
The Object Class 866 The C lass Class 866 The Enum Class 868 Thread-Related Classes and The Runnable Interface 868 Other Classes 869 The java . lang Interfaces 869 The Comparable Interface 870 The Appendable Interface 872 The Iterable Interface 873 The Readable Interface 873 The CharSequence Interface 873 The AutoCloseable Interface 874
Exercises 875
sch2207X_fm_p0i-xxxvi.indd 19 23/12/11 4:29 PM
xx contents
ChAPTER 24 Exploring java.util 879 The Locale Class 881
Working with Date and Time 884 Date 884 Calendar and GregorianCalendar 885
Formatting Output with Formatter 890 The Formatter Constructors 890 Formatting Basics 891 Formatting Strings and Characters 894 Formatting Numbers 894 Formatting Date and Time 895 The %n and %% Specifiers 897 Specifying a Minimum Field Width 897 Specifying Precision 898 Using the Format Flags 899 The Uppercase Option 902 Using an Argument Index 902 Formatting for a Different Locale 903 Closing a Formatter 904
Formatting and the printf( ) Method 907 The Scanner Class 909 The Scanner Constructors 909 Scanning Basics 909 Some Scanner Examples 911 Some Other Scanner Features 916
The Random Class 917 Use Observable and Observer 918 The T imer and T imerTask Classes 922 Miscellaneous Utility Classes
and Interfaces 924 Exercises 925
ChAPTER 25 using the Data Structures in the Collections Framework 929
An Overview of Data Structures 930 Stacks and Queues 930 Linked Lists 931 Trees 932 Hash Tables 933 Choosing a Data Structure 933
sch2207X_fm_p0i-xxxvi.indd 20 23/12/11 4:29 PM
xxiContents
Collections Overview 934 The Collection Interfaces 935 The Collection Interface 936 The List Interface 938 The Set Interface 938 The SortedSet Interface 938 The NavigableSet Interface 940 The Queue Interface 940 The Deque Interface 942
The Collection Classes 944 The ArrayList Class 945 The LinkedList Class 948 The HashSet Class 952 The TreeSet Class 954 The LinkedHashSet Class 956 The ArrayDeque Class 957 The PriorityQueue Class 959
Accessing a Collection via an Iterator 960 Using an Iterator 960 The For-Each Alternative to Iterators 964
Working with Maps 964 The Map Interfaces 964 The Map Classes 969
Comparators 974 The Collection Algorithms 976 The Arrays Class 980 The Legacy Classes and Interfaces 981 The Enumeration Interface 981 Vector 981 Stack 981 Dictionary 981 Hashtable 981 Properties 982
Exercises 982
ChAPTER 26 Networking with java.net 985 Networking Fundamentals 985 The Networking Classes and Interfaces 986 The InetAddress Class 987 The Socket Class 989 The URL Class 993 The URLConnection Class 995
sch2207X_fm_p0i-xxxvi.indd 21 23/12/11 4:29 PM
xxii contents
The httpuRLConnection Class 1000 Datagrams 1002 DatagramSocket 1003 DatagramPacket 1003 A Datagram Example 1004
Exercises 1007
ChAPTER 27 The Concurrency utilities 1009 The Concurrent API Packages 1010 java.util.concurrent 1010 java.util.concurrent.atomic 1011 java.util.concurrent.locks 1011
Using Synchronization Objects 1012 Semaphore 1012 CountDownLatch 1015 CyclicBarrier 1018 Exchanger 1020 Phaser 1023
Using an Executor 1030 A Simple Executor Example 1031 Using Cal lable and Future 1033 The T imeUnit Enumeration 1036 The Concurrent Collections 1038 Locks 1038 Atomic Operations 1041 Parallel Programming via the Fork/
Join Framework 1042 The Main Fork/Join Classes 1043 ForkJoinTask 1043 RecursiveAction 1044 RecursiveTask 1044 ForkJoinPool 1045
The Divide-and-Conquer Strategy 1046 A Simple First Fork/Join Example 1047 Understanding the Impact of the Level of Parallelism 1049 An Example That Uses RecursiveTask 1052 Executing a Task Asynchronously 1054
sch2207X_fm_p0i-xxxvi.indd 22 23/12/11 4:29 PM
xxiiiContents
The Concurrency Utilities versus Java’s Traditional Approach 1055 Exercises 1056
APPENDIx A using Java’s Documentation Comments 1059 The javadoc Tags 1059
The General Form of a Documentation Comment 1063
What javadoc Outputs 1064
An Example That Uses Documentation
Comments 1064
APPENDIx B An Introduction to Regular Expressions 1067
The Pattern Class 1067
The Matcher Class 1068
Regular Expression Syntax Basics 1068
Demonstrating Pattern Matching 1069
Using the Wildcard Character and Quantifiers 1071
Working with Classes of Characters 1073
Using replaceAll( ) 1073
The String Class Connection 1074
Things to Explore 1074
APPENDIx C Answers to Selected Exercises 1075
INDEx 1129
sch2207X_fm_p0i-xxxvi.indd 23 23/12/11 4:29 PM
sch2207X_fm_p0i-xxxvi.indd 24 23/12/11 4:29 PM
This book teaches the fundamentals of programming by way of the Java language. It assumes no prior programming experience and begins with the basics, such as how to compile and run a Java program. Next, it discusses the keywords, opera- tors, and constructs that form the Java language. The book also covers several parts of the Java Application Programming Interface (API) library, including Swing, which is the framework used to create programs that have a graphical user interface (GUI), and the Collections Framework, which is used to store collections of objects. In short, this book is intended as a comprehensive introduction to Java. Like most computer languages, Java has evolved over time. At the time of this writing, the latest version is Java 7 (JDK 7), and this is the version of Java covered by this book. However, most of the material is also applicable to other recent versions of Java, such as version 6.
A STRAIghT AhEAD APPROACh This book uses what we characterize as a “straight ahead” approach. By this, we mean that topics are introduced in a cohesive sequence that is intended to keep the focus of each discussion on the topic at hand. This approach simplifies and streamlines the presentation. On occasions when a departure from the main presentation flow is nec- essary, we attempt to do so in a way that minimizes the disruption. The goal of our approach is to present the Java language in a way that clearly shows the interrelation- ship of its parts, rather than as a jumble of disconnected features. To help manage the material, this book is organized into three parts. Part One describes the elements that define the Java language and the core elements of pro- gramming. It begins with an overview of Java followed by the basic concepts of data types, operators, and control statements. It then progressively introduces the more sophisticated features of the language, such as classes, methods, inheritance, inter- faces, packages, exceptions, multithreading, and generics. Part One also describes I/O, because it is integral to many Java programs, and applet fundamentals, because the applet is a quintessential Java application. Part One ends with a chapter on object- oriented design. As it relates directly to Part One, our “straight ahead” approach keeps the focus on the elements of the Java language and the fundamentals of programming, with each new section building on the foundation of what comes before. Where possible, we avoid digressions that distract from the main topic. For example, discussions of GUI programming via Swing are handled in Part Two, rather than being intermixed with discussions of basic concepts. This way, the presentation in Part One remains firmly rooted in the core issues of Java and of programming.
PREFACE
sch2207X_fm_p0i-xxxvi.indd 25 23/12/11 4:29 PM
xxvi
Part Two introduces Swing. It begins with an overview of GUI programming with Swing, including the basic concepts of components, events, and layout manag- ers. Subsequent chapters advance in an orderly fashion, presenting an overview of several Swing components, followed by menus, dialogs, painting, and so on. This “straight ahead” approach is intended to help students more easily integrate each new feature into the overall picture they are forming of the Swing framework. Part Three explores portions of the Java API library. Because the API library is very large, it is not possible to discuss it in its entirety in this book. Instead, we focus on what we consider to be those parts of the library with which every Java pro- grammer should be familiar. In addition to covering large portions of java.lang and java.util (with special emphasis on the Collections Framework), we also present an overview of networking, and introduce the concurrency API, including the Fork/Join Framework. The material is presented in a straightforward manner that is designed to give the student a solid overview of several core library elements.
OBJECTS SOON…BuT NOT TOO SOON One of the first commonly-asked questions about a programming book is whether it uses an “objects early” or an “objects late” approach to teaching the key tenets of object-oriented programming. Of course, what constitutes “early” or “late” can be somewhat subjective, and neither term precisely describes the organization of this book. The phrase we use to characterize our approach is “objects soon, but not too soon.” Our goal is to introduce objects at the appropriate time for the student. We believe that this is not until key features of the language have been learned. Towards this end, the focus of the first three chapters is on the fundamentals of the Java language, such as its syntax, data types, operators, and control statements. We believe that mastery of these elements is a necessary first step because they form the foundation of the language, and the foundation of programming in general. (In other words, it is difficult to write meaningful programs without understanding these ele- ments.) In our view, only after the basic elements of a program have been learned, is the student ready to move forward to objects. After the book has covered the fundamentals, objects are introduced in Chapter 4, and from that point on, object-oriented features, techniques, and concepts are inte- grated into the remaining chapters. Additionally, objects are introduced in a carefully paced, step-by-step fashion. This is intended to help the student grasp each new fea- ture in context, and without being overwhelmed.
PEDAgOgICAL FEATuRES This book includes several pedagogical elements to facilitate and reinforce learning. Each feature helps ensure that students are fully aware of key skills, can gauge their advancement, and can verify that all concepts are learned.
j Key Skills & Concepts: Each chapter begins with a list that identifies the key skills and concepts presented in the chapter.
j Ask the Expert: At various points throughout the book are Ask the Expert boxes. These contain additional information or interesting commentary about
preface
sch2207X_fm_p0i-xxxvi.indd 26 23/12/11 4:29 PM
a topic, and use a Question/Answer format. They provide supplemental infor- mation without disrupting the main presentation flow.
j Try This Elements: Each chapter contains one or more Try This elements. These are step-by-step examples that walk through the development of a program that demonstrates an aspect of Java related to the chapter’s topic. Typically, these are longer examples that show a feature in a more practical setting.
j Progress Checks: Throughout each chapter, Progress Checks are presented to test the student’s understanding of the preceding section. The answers to these questions are at the bottom of the same page.
j Exercises: Each chapter concludes with exercises that include short answer, fill-in-the-blank, and true/false questions, and coding exercises. The answers to selected exercises are in Appendix C.
ACM RECOMMENDATIONS The 2008 update to the ACM Curricula Recommendations (http://www.acm.org/ education/curricula/ComputerScience2008.pdf) recommends that all computer science students be fluent in at least one programming language and have some understanding of object-oriented and event-driven programming. We believe that students who learn the material covered by this book will have the desired knowledge and skills. We have included in the book not just an introduction to programming using the Java language, but broader coverage that includes advanced Java features, the Swing framework, and large parts of several important API packages. The first part of the book covers a significant portion of the topics in the Programming Fundamentals (PF) knowledge area of the ACM Recommendations (the main exceptions being the knowledge units FoundationsInformationSecurity and SecureProgramming). The first part also includes a chapter on object-oriented design, which covers a number of the topics in the PL/ObjectOrientedProgramming and SE/ SoftwareDesign knowledge units. The second part of the book, which introduces GUI programming with Swing, addresses some of the topics in the knowledge unit HC/GUIProgramming. The third part includes, among others, topics that relate to concurrency. In fact, we devote Chapters 12 and 27 to multithreading and concurrency because we feel, as the ACM Curricular Recommendations discuss, that concurrency is becoming increasingly relevant to the discipline of computer science.
ONLINE RESOuRCES Students can access all of the source code for the programs in the text at the website that accompanies Java Programming: A Comprehensive Approach: www.mhhe.com/ schildt1e. This site also offers a number of useful resources for the Java instructor.
j A Solutions manual for end-of-chapter exercises.
Preface xxvii
sch2207X_fm_p0i-xxxvi.indd 27 23/12/11 4:29 PM
xxviii preface
j Instructor Notes, including suggested curricula and suggestions for teaching particular topics.
j Supplemental Exercises that can be used to create quizzes and tests. j PowerPoint Slides that serve as an outline for in-class instruction.
Please contact your McGraw-Hill representative for access information.
Additional instructor resources include:
This text is available as an eBook at www.CourseSmart.com. At CourseSmart your students can take advantage of significant savings off the cost of a print textbook, reduce their impact on the environment, and gain access to powerful web tools for learning. CourseSmart eBooks can be viewed online or downloaded to a computer. The eBooks allow students to do full text searches, add highlighting and notes, and share notes with classmates. CourseSmart has the largest selection of eBooks available anywhere. Visit www.CourseSmart.com to learn more and to try a sample chapter.
Craft your teaching resources to match the way you teach! With McGraw-Hill Create™, www.mcgrawhillcreate.com, you can easily rearrange chapters, combine material from other content sources, and quickly upload content you have written, such as your course syllabus or teaching notes. Find the content you need in Create by searching through thousands of leading McGraw-Hill textbooks. Arrange your book to fit your teaching style. Create even allows you to personalize your book’s appearance by selecting the cover and adding your name, school, and course infor- mation. Order a Create book and you’ll receive a complimentary print review copy in 3–5 business days or a complimentary electronic review copy (eComp) via email in minutes. Go to www.mcgrawhillcreate.com today and register to experience how McGraw-Hill Create™ empowers you to teach your students your way.
ACKNOWLEDgMENTS We wish to acknowledge the many contributions made by the following people at McGraw-Hill, without whom this book would not exist. They have made working on the book a delight.
Editorial Director, Michael Lange Global Publisher, Raghu Srinivasan Senior Marketing Manager, Curt Reynolds Developmental Editor, Robin Reed Developmental Editor, Kathryn Neubauer
sch2207X_fm_p0i-xxxvi.indd 28 23/12/11 4:29 PM
xxixPreface
Senior Project Manager, Lisa Bruflodt Design Coordinator, Brenda Rolwes Production Editor, Rose Kernan
We would also like to thank the following reviewers for their many helpful comments, which were much appreciated.
Bill Barge, Trine University Chris Bennett, University of Maine–Farmington Augusto Casas, St Thomas Aquinas College I-ping Chu, DePaul University Vasil Hnatyshin, Rowan University Rodney Hoffman, Occidental College David Kamper Sr., Northeastern Illinois University BJ Tjaden, Anne Arundel Community College Richard Weiss, Evergreen State College James Braman, Towson University Steve Cooper, Stanford University Michael Main, University of Colorado—Boulder Jay McCarthy, Brigham Young University Robert Moll, University of Massachusetts—Amherst Jagadeesh Nandigam, Grand Valley State University Gurpur Prabhu, Iowa State University Daisy Sang, California State Polytechnic University Mark Sherriff, University of Virginia Joslyn Smith, Florida International University James Young, University of Manitoba
Finally, and most importantly, we would like to thank our families for their support during the preparation of this book.
sch2207X_fm_p0i-xxxvi.indd 29 23/12/11 4:29 PM
sch2207X_fm_p0i-xxxvi.indd 30 23/12/11 4:29 PM
About the Authors
Herbert Schildt has been writing about programming since 1984 and is the author of several books on Java, C++, C, and C#. His programming books have sold millions of copies worldwide and have been widely translated. Although he is interested in all facets of computing, his primary focus is computer languages, including the standardization of languages. Schildt holds BA and MCS degrees from the University of Illinois, Urbana/Champaign. He provided the initial drafts for most of the chapters in this book.
Dale Skrien has been teaching mathematics and computer science at Colby College since 1980 and has been teaching Java since 1996. His interest in teaching stu- dents not just how to program, but how to program well, led to the publication of his textbook Object-Oriented Design using Java by McGraw-Hill. He holds a BA degree from St. Olaf College, MS degrees from the University of Illinois and the University of Washington, and a PhD degree from the University of Washington. In addition to contributions throughout the book, he provided Chapter 16, which introduces object-oriented design. He also provided the online supplements for this book.