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