Download as pdf or txt
Download as pdf or txt
You are on page 1of 53

Java Programming: A Comprehensive

Introduction, First edition


Visit to download the full and correct content document:
https://ebookmass.com/product/java-programming-a-comprehensive-introduction-first
-edition/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Introduction to Java Programming, Comprehensive Version


Y. Daniel Liang

https://ebookmass.com/product/introduction-to-java-programming-
comprehensive-version-y-daniel-liang/

Introduction to Programming with Java: A Problem


Solving Approach 3rd Edition John Dean

https://ebookmass.com/product/introduction-to-programming-with-
java-a-problem-solving-approach-3rd-edition-john-dean/

Java Programming 9th Edition Joyce Farrell

https://ebookmass.com/product/java-programming-9th-edition-joyce-
farrell/

Learning Java: Beginning programming with java for


dummies Bach

https://ebookmass.com/product/learning-java-beginning-
programming-with-java-for-dummies-bach/
Introduction to Java Through Game Development: Learn
Java Programming Skills by Working with Video Games 1st
Edition Victor G. Brusca

https://ebookmass.com/product/introduction-to-java-through-game-
development-learn-java-programming-skills-by-working-with-video-
games-1st-edition-victor-g-brusca/

Java Programming (MindTap Course List), 10th Edition


Joyce Farrell

https://ebookmass.com/product/java-programming-mindtap-course-
list-10th-edition-joyce-farrell/

C++ Mastery: A Comprehensive Guide to Programming


Excellence Alen Bonds

https://ebookmass.com/product/c-mastery-a-comprehensive-guide-to-
programming-excellence-alen-bonds/

Programming Logic & Design, Comprehensive 9th edition


Joyce Farrell

https://ebookmass.com/product/programming-logic-design-
comprehensive-9th-edition-joyce-farrell/

Beginning Programming with Java For Dummies 6th Edition


Barry Burd

https://ebookmass.com/product/beginning-programming-with-java-
for-dummies-6th-edition-barry-burd/
Herbert Schildt | Dale Skrien

Java
Java Programming: A Comprehensive Introduction is designed for an introductory

Java Programming
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.

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
A Comprehensive Introduction
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 flexibility in choosing when to introduce GUI programming.

Introduction
A Comprehensive
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

MD DALIM #1174731 11/18/11 CYAN MAG YELO BLK


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

Schildt
Skrien

TM

College Programming Series


CONTENTS

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 content s

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
Exercis es 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
Literal s 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 Ass ignment 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
Exercis es 73

sch2207X_fm_p0i-xxxvi.indd 8 23/12/11 4:29 PM


Contents ix

CHAPTER 3 Program Control Statements 77


Input Characters from the Keyboard 78
The if Statement 79
Nested ifs 81
The if-else-if 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 content s

Garbage Collection and Finalizers 145


The finalize( ) Method 146
The this Keyword 149
Exercis es 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
Exercis es 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


Contents xi

Overloading Constructors 222


Recursion 228
Understanding static 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 final 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 content s

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
Exercis es 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
Exercis es 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


Contents xiii

A Closer Look at throwable 361


Using finally 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 content s

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 notifyAll( ) 458
An Example That Uses wait( ) and notify( ) 458
Suspending, Resuming, and
 Stopping Threads 464
Exercis es 469

CHAPTER 13 Enumerations, Autoboxing, and Annotations 475


Enumerations 475
Enumeration Fundamentals 476
Java Enumerations are Class Types 479
The values( ) and valueOf( ) 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
Exercis es 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


Contents xv

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 content s

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
Exercis es 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


Contents xvii

Using a Push Button 635


Introducing JTextField 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
JTextField 675
JScrollPane 685
JList 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 JMenuItem 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 JRadioButto nMenuItem
 and JCheckBoxMenuItem 730
Exercises 733

CHAPTER 20 Dialogs 737


JOptionPane 738
showMessageDialog( ) 740

sch2207X_fm_p0i-xxxvi.indd 17 23/12/11 4:29 PM


xviii content s

showConfirmDialog( ) 744
showInputDialog( ) 748
showOptionDialog( ) 753
JDialog 758
Create a Modeless Dialog 762
Select Files with JFileChooser 763
Exercis es 774

CHAPTER 21 Threading, Applets, and Painting 779


Multithreading in Swing 779
Use Timer 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
Exercis es 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


Contents xix

Using indexOf( ) and lastIndexOf( ) 831


Obtaining a Modified String 833
substring( ) 833
replace( ) 834
trim( ) 835
Changing the Case of Characters
  Within a String 836
StringBuffer and StringBuilder 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 Class 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 content s

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 Timer and TimerTask Classes 922
Miscellaneous Utility Classes
 and Interfaces 924
Exercis es 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


Contents xxi

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 URLConnec tion Class 995

sch2207X_fm_p0i-xxxvi.indd 21 23/12/11 4:29 PM


xxii content s

The H ttpURLConnection Class 1000


Datagrams 1002
DatagramSocket 1003
DatagramPacket 1003
A Datagram Example 1004
Exercis es 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 Callable and Future 1033
The TimeUnit 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<V> 1043
RecursiveAction 1044
RecursiveTask<V> 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<V> 1052
Executing a Task Asynchronously 1054

sch2207X_fm_p0i-xxxvi.indd 22 23/12/11 4:29 PM


Contents xxiii

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
         
C omment 1063
What javadoc Outputs 1064
An Example That Uses Documentation
         
C omments 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
         
a nd 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
PREFACE

T
his 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.

sch2207X_fm_p0i-xxxvi.indd 25 23/12/11 4:29 PM


xxvi preface

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

sch2207X_fm_p0i-xxxvi.indd 26 23/12/11 4:29 PM


Preface xxvii

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.

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


Preface xxix

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.

sch2207X_fm_p0i-xxxvi.indd 31 23/12/11 4:29 PM


Chapter
A Total solution
Introducing Classes, Objects,
and methods
key skills & concepts
j Know the fundamentals of the class
j Understand how objects are
Java Programming 35 created
j Understand how reference variables are assigned
Try This
Key 1-2&Improving
Skills Concepts the Gallons-
j Create a method
to-Liters Converter j Use the return keyword
Outlines the main topics j Return a value from a method
and techniques presented
GalToLitTable.java
j Add parameters to a method
You can use the for loop, the if statement, and code blocks to create an improved
in the chapter. j Utilize
version of the gallons-to-liters converter that you developed in Try constructors
This 1-1. This
new version will print a table of conversions, beginning with 1 j gallon and parameterized
Create ending constructors
at 100 gallons. After every 10 gallons, a blank line will be output. This is accom-
j Understand new
plished through the use of a variable called counter that counts the number of lines
that have been output. Pay special attention to its use. j Understand garbage collection and finalizers
j Use the this keyword
Step-By-Step
1. Create a new file called GaltoLittable.java. Before you can go much further in your study of Java, you need to learn about th
2. Enter the following program into the file: class. The class is the essence of Java. It is the foundation on which the Java languag
/*
is built because the class defines the nature of an object. As such, the class forms th
Try This 1-2 basis for object-oriented programming in Java. Within a class are defined data and
code that acts upon that data. The code is contained in methods. Because classes
This program displays a conversion objects, and methods are fundamental to Java, they are introduced in this chapter
table of gallons to liters.
Having a basic understanding of these features will allow you to write more sophis
Call this program "GalToLitTable.java". ticated programs and better understand certain key Java features described in the fol
*/ lowing chapter.
class GalToLitTable {
public static void main(String[] args) {
double gallons, liters;
int counter;
Class Fundamentals
Line counter is initially set to zero.

Since all Java programCode


activityListings
occurs within a class, we have been using classes sinc
counter = 0;
for(gallons = 1; gallons <= 100; gallons++)the
{ start of this book. Of course, only extremely simple classes have been used, and
liters = gallons * 3.7854; // convert to liters Examples that show program
System.out.println(gallons + " gallons is " +
liters + " liters.");
elements and techniques in
action. Call-outs point to key
counter++; Increment the line counter
blank line with
// every 10th line, print aSchildt_CH04.indd 119 each loop iteration.
features, where appropriate.
if(counter == 10) { If counter is 10,
System.out.println(); output a blank line.
counter = 0; // reset the line counter
}
}
}
}

3. Compile the program using the following command line:


javac GalToLitTable.java

Schildt_CH01.indd 35 02/12/11 2:47 PM

sch2207X_fm_p0i-xxxvi.indd 32 23/12/11 4:29 PM


c contains -1
c is negative

c contains 1
c is non-negative

Notice one other thing in this program. The line


int a, b, c;
A Total Solution xxxiii
declares three variables, a, b, and c, by use of a comma-separated list. As mentioned
earlier, when you need two or more variables of the same type, they can be declared
in one statement. Just separate the variable names by commas.
Ask the Expert
Ask the Expert
Additional information or Q Insiontheisdiscussion of the if statement, you mentioned that a true/false expres-
referred to as Boolean expression. Why is that term used?
commentary from an “expert”
perspective related to the topic A The term Boolean is named after George Boole (1815–1864). He developed
and formalized the laws that govern true/false expressions. This became
Java Programming 87
known as Boolean algebra. His work eventually came to form the basis of computer
at hand. logic.
break;
case 'B': // ...
} // end of inner switch
break;
The for Loop
case 'B': // ... Many times a program will need to perform a task more than once. For example,
you might want to display the time of day, with the time updated once every second.
Obviously, it would not be practical to write such a program using hundreds of separate
println( ) statements, one for each possible time, in one-second intervals. Instead, such
Progress Check a repetitive operation would be accomplished by a loop. A loop is a control statement
that repeatedly executes a sequence of code. Loops are used extensively by nearly all
1. The expression controlling the switch can beLike
programs. of what
the iftype?
statement, loops are a fundamental part of programming.
2. When the switch expression matches aJava casesupplies
constant, what happens?
a powerful assortment of loop constructs. The one we will introduce
3. If a case sequence does not end in break,
here is the
whatforhappens?
loop. The simplest form of the for loop is shown next:
for(initialization; condition; iteration) statement;
In its most common form, the initialization portion of the loop sets a loop control
Try This 3-1 Start Building a Java variable to an initial value. The condition is a Boolean expression that tests the loop
Help System
Help.java

This project builds a simple help system that displays the syntax for the Java
Schildt_CH01.indd 30 02/12/11 2:49 PM
control statements. In the process, it shows the switch statement in action. The
program displays a menu containing the control statements and then waits for you
to choose one. After one is chosen, the syntax of the statement is displayed. In this
first version of the program, help is available for only the if and switch statements.
The other control statements are added in subsequent examples.
Try This
Step-by-step examples
StEp-by-StEp
that demonstrate a key
1. Create a file called Help.java. feature or technique.
2. The program begins by displaying the following menu:
Help on:
1. if
2. switch
Choose one:

To accomplish this, you will use the statement sequence shown here:
System.out.println("Help on:");
System.out.println(" 1. if");

Answers:
1. The switch expression can be of type char, short, int, byte, or an enumera-
tion. Beginning with JDK 7, a String can also be used.
2. When a matching case constant is found, the statement sequence associated
with that case is executed.
3. If a case sequence does not end with break, execution continues into the
next case sequence, if one exists.

sch2207X_ch03_p077-118.indd 87 22/12/11 5:03 PM

sch2207X_fm_p0i-xxxvi.indd 33 23/12/11 4:29 PM


The output is shown here:
First line
Second line
A B C
250 c h apter 6 A Closer Look at Methods and
D ClassesE F
xxxiv a to t a l solut ion
Notice how the \n escape sequence is used to generate a new line. You don’t need
In this program, the overloading of vaTest(
to use )multiple
is perfectly correct.
println( However,tothis
) statements getpro-
multiline output. Just embed \n within a
gram will not compile because of the following call:
longer string at the points where you want the new lines to occur.
Progress
vaTest(); //Check
Error: Ambiguous!

Becauseshort
These the vararg parameter can be empty,progress
self-tests this call couldCheck
be translated into a call
to vaTest(int ...) or to vaTest(boolean ...). Both are equally valid. Thus, the call is
let students
inherently test their
ambiguous. 1. What is the type of the literal 10? What is the type of the literal 10.0?
understanding
Here is anotherof example
the of ambiguity. The do
2. How following overloaded
you specify versions of
a long literal?
vaTest( ) are
material as inherently
the chapter ambiguous even though one
3. Is "x" takes aornormal
a string parameter:
a character literal?
progresses.
static void vaTest(int ... v) { // ...

static void vaTest(int n, int ... v) { // ... ask the expert


Although the parameter lists of vaTest( ) differ, there is no way for the compiler to
resolve the following call:
vaTest(1)
Q Is a string consisting of a single character the same as a character literal? For
example, is "k" the same as 'k'?

to answer this question. Thus, the situation


A
Does this translate into a call to vaTest(int ...),No.with
call to vaTest(int, int ...) with no varargs arguments?
Youone
sents a There
varargs
must
single is
is ambiguous.
string.
argument,
not confuse
no way
letter for the
of type
or into
strings witha characters. A character literal repre-
compiler
char. A string containing only one letter is still a
Although strings consist of characters, they are not the same type.
Because of ambiguity errors like those just shown, sometimes you will need to
forego overloading and simply use two different method names. Also, in some cases,
ambiguity errors expose a conceptual flaw in your code, which you can remedy by
more carefully crafting a solution. a CLoser Look at varIaBLes
Variables were introduced in Chapter 1. Here, we will take a closer look at them. As
you learned earlier, variables are declared using this form of statement,
type var-name;
ExErCisEs
1. Given this fragment,
Answers:
class X {
1. The literal 10 is an int, and 10.0 is a double.
private int count;
2. A long literal is specified by adding the L or l suffix. For example, 100L.
3. The literal "x" is a string.
is the following fragment correct?
End-of-Chapter Exercises
class Y { Questions and coding exercises
public static void main(String[] args) { that test the student’s grasp of
X ob = new X();
the material discussed in the
ob.count = 10; sch2207X_ch02_p043-076.indd 53
chapter. 22/12/11 4:54 PM

2. An access modifier must __________ a member’s declaration.


3. Given this class,
class Test {
int a;
Test(int i) { a = i; }
}

ldt_CH06.indd 250 02/12/11 2:52 PM

sch2207X_fm_p0i-xxxvi.indd 34 23/12/11 4:29 PM


Another random document with
no related content on Scribd:
CHAPTER XXIII
NAT JUMPS AT A CONCLUSION

All this time Tavia and Nat were having anything but a happy life.
Nat would not have admitted it for the world, but he wished he could
leave home and never appear at The Cedars again until Tavia had
gone.
On her part, Tavia would have returned to Dalton before the new
year had Dorothy allowed her to have her own way. Dorothy would
not hear of such a thing.
To make the situation worse for the pair of young people so
tragically enduring their first vital misunderstanding, Ned and Jennie
Hapgood were sailing upon a sea of blissful and unruffled happiness.
Nat and Tavia could not help noting this fact. The feeling of the
exalted couple for each other was so evident that even the Dale
boys discussed it—and naturally with deep disgust.
“Gee!” breathed Joe, scandalized. “Old Ned is so mushy over
Jennie Hapgood that he goes around in a trance. He could tread on
his own corns and not know it, his head is so far up in the clouds.
Gee!”
“I wouldn’t ever get so silly over a girl—not even our Dorothy,”
Roger declared. “Would you, Joe?”
“Not in a hundred years,” was his brother’s earnest response.
The major admitted with a chuckle that Ned certainly was hard hit.
The time set for Jennie Hapgood to return to Sunnyside Farm came
and passed, and still many reasons were found for the prolongation
of her visit. Ned went off to New York one day by himself and
brought home at night something that made a prominent bulge in his
lower right-hand vest pocket.
“Oh, oh, OH! Dorothy!” ejaculated Tavia, for the moment coming
out of her own doldrums. “Do you know what it is? A Tiffany box!
Nothing less!”
“Dear old Ned,” said her chum, with a smile.
Ned and Jennie disappeared together right after dinner. Then, an
hour later, they appeared in the drawing-room where the family was
assembled and Ned led Jennie forward by her left hand—the fingers
prominently extended.
“White gold—platinum!” murmured Tavia, standing enthralled as
she beheld the beautifully set stone.
“Set old Ned back five hundred bucks if it did a cent,” growled Nat,
under his breath and keeping in the background.
“Oh, Jennie!” cried Dorothy, jumping up.
But Aunt Winnie seemed to be nearest. She reached the happy
couple before anybody else.
“Ned needn’t tell me,” she said, with a little laugh and a little sob
and putting both arms about Jennie. “Welcome, my daughter! Very
welcome to the White family. I have for years tried to divide Dorothy
with the major; now I am to have at least one daughter of my very
own.”
Did she flash a glance at Tavia standing in the background? Tavia
thought so. The proud and headstrong girl was shot to the quick with
the arrow of the thought that Mrs. White had been told by Nat of the
difference between himself and Tavia and that the lady would never
come to Tavia and ask that question on behalf of her younger son
that the girl so desired her to ask.
Never before had Tavia realized so keenly the great chasm
between herself and Jennie Hapgood. Mrs. White welcomed Jennie
so warmly, and was so glad, because Jennie was of the same level
in society as the Whites. Both in blood and wealth Jennie was Ned’s
equal.
Tavia knew very well that by explaining to Nat about Lance
Petterby’s letters she could easily bring that young man to his knees.
In her heart, in the very fiber of the girl’s being, indeed, had grown
the desire to have Dorothy Dale’s Aunt Winnie tell her that she, too,
would be welcome in the White family. Now Tavia doubted if Aunt
Winnie would ever do that.
Jennie was to go home to Sunnyside Farm the next day. This final
decision had probably spurred Ned to action. Because of certain
business matters in town which occupied both Ned and Nat at train
time and the fact that Dorothy was busy with some domestic duty, it
was Tavia who drove the Fire Bird, the Whites’ old car, to the station
with Jennie Hapgood.
A train from the West had come in a few minutes before the
westbound one which Jennie was to take was due. Tavia, sitting in
the car while Jennie ran to get her checks, saw a tall man carrying
two heavy suitcases and wearing a broad-brimmed hat walking down
the platform.
“Why! if that doesn’t look——Surely it can’t be—I—I believe I’ve
got ’em again!” murmured Tavia Travers.
Then suddenly she shot out from behind the wheel, leaped to the
platform, and ran straight for the tall figure.
“Garry Knapp!” she exploded.
“Why—why—Miss Travers!” responded the big young man,
smiling suddenly and that “cute” little dimple just showing in his
bronzed cheek. “You don’t mean to say you live in this man’s town?”
He looked about the station in a puzzled way, and, having dropped
his bags to shake hands with her, rubbed the side of his head as
though to awaken his understanding.
“I don’t understand your being here, Miss Travers,” he murmured.
“Why, I’m visiting here,” she said, blithely. “But you——?”
“I—I’m here on business. Or I think I am,” he said soberly. “How’s
your—Miss Dale! She doesn’t live here, does she?”
“Of course. Didn’t you know?” demanded Tavia, eyeing him
curiously.
“No. Who—what’s this Major Dale to her, Miss Travers?” asked the
young man and his heavy brows met for an instant over his nose.
“Her father, of course, Mr. Knapp. Didn’t you know Dorothy’s father
was the only Major Dale there is, and the nicest man there ever
was?”
“How should I know?” demanded Garry Knapp, contemplating
Tavia with continued seriousness. “What is he—a real estate man?”
“Why! didn’t you know?” Tavia asked, thinking quickly. “Didn’t I tell
you that time that he was a close friend of Colonel Hardin, who
owned that estate you told me joined your ranch there by Desert
City?”
“Uh-huh,” grunted the young man. “Seems to me you did tell me
something about that. But I—I must have had my mind on something
else.”
“On somebody else, you mean,” said Tavia, dimpling suddenly.
“Well! Colonel Hardin left his place to Major Dale.”
“Oh! that’s why, then. He wants to buy my holdings because his
land joins mine,” said Garry Knapp, reflectively.
Tavia had her suspicions of the truth well aroused; but all she
replied was:
“I shouldn’t wonder, Mr. Knapp.”
“I got a good offer—leastways, better than those sharks, Stiffbold
and Lightly, would make me after they’d seen the ranch—from some
lawyers out there. They planked down a thousand for an option, and
told me to come East and close the deal with this Major Dale. And it
never entered into this stupid head of mine that he was related to—
to Miss Dale.”
“Isn’t that funny?” giggled Tavia. Then, as Jennie appeared from
the baggage room and the westbound train whistled for the station,
she added: “Just wait for me until I see a friend off on this train, Mr.
Knapp, and I’ll drive you out.”
“Drive me out where?” asked Garry Knapp.
“To see—er—Major Dale,” she returned, and ran away.
When the train had gone she found the Westerner standing
between his two heavy bags about where she had left him.
“Those old suitcases look so natural,” she said, laughing at his
serious face. “Throw them into the tonneau and sit beside me in
front. I’ll show you some driving.”
“But look here! I can’t do this,” he objected.
“You cannot do what?” demanded Tavia.
“Are you staying with Miss Dale?”
“Of course I am staying with Doro. I don’t know but I am more at
home at The Cedars than I am at the Travers domicile in Dalton.”
“But wait!” he begged. “There must be a hotel here?”
“In North Birchland? Of course.”
“You’d better take me there, Miss Travers, if you’ll be so kind. I
want to secure a room.”
“Nothing doing! You’ve got to come out to The Cedars with me,”
Tavia declared. “Why, Do—I mean, of course, Major Dale would
never forgive me if I failed to bring you, baggage and all. His friends
do not stop at the North Birchland House I’d have you know.”
“But, honestly, Miss Travers, I don’t like it. I don’t understand it.
And Major Dale isn’t my friend.”
“Oh, isn’t he? You just wait and see!” cried Tavia. “I didn’t know
about your coming East. Of course, if it is business——”
“That is it, exactly,” the young man said, nervously. “I—I couldn’t
impose upon these people, you know.”
“Say! you want to sell your land, don’t you?” demanded Tavia.
“Ye—es,” admitted Garry Knapp, slowly.
“Well, if a man came out your way to settle a business matter, you
wouldn’t let him go to a hotel, would you? You’d be angry,” said
Tavia, sensibly, “if he insisted upon doing such a thing. Major Dale
could not have been informed when you would arrive, or he would
have had somebody here at the station to meet you.”
“No. I didn’t tell the lawyers when I’d start,” said Garry.
“Don’t make a bad matter worse then,” laughed Tavia, her eyes
twinkling as she climbed in and sat back of the wheel. “Hurry up. If
you want to sell your land you’d better waste no more time getting
out to The Cedars.”
The Westerner got into the car in evident doubt. He suspected that
he had been called East for something besides closing a real estate
transaction. Tavia suspected so, too; and she was vastly amused.
She drove slowly, for Garry began asking her for full particulars
about Dorothy and the family. Tavia actually did not know anything
about the proposed purchase of the Knapp ranch by her chum’s
father. Dorothy had said not a word to her about Garry since their
final talk some weeks before.
At a place in the woods where there was not a house in sight,
Tavia even stopped the car the better to give her full attention to Mr.
Garry Knapp, and to talk him out of certain objections that seemed to
trouble his mind.
It was just here that Nat White, on a sputtering motorcycle he
sometimes rode, passed the couple in the automobile. He saw Tavia
talking earnestly to a fine-looking, broad-shouldered young man
wearing a hat of Western style. She had an eager hand upon his
shoulder and the stranger was evidently much interested in what the
girl said.
Nat did not even slow down. It is doubtful if Tavia noticed him at
all. Nat went straight home, changed his clothes, flung a few things
into a traveling bag, and announced to his mother that he was off for
Boston to pay some long-promised visits to friends there and in
Cambridge.
Nat, with his usual impulsiveness, had jumped at a conclusion
which, like most snap judgments, was quite incorrect. He rode to the
railroad station by another way and so did not meet Tavia and Garry
Knapp as they approached The Cedars.
CHAPTER XXIV
THIN ICE

Dorothy spied the Fire Bird just as it turned in at the entrance gate.
And she identified the person sitting beside her chum, too.
Therefore, she had a few minutes in which to prepare for her
meeting with Garry Knapp.
She was on the porch when the car stopped, and her welcome to
the young Westerner possessed just the degree of cordiality that it
should. Neither by word nor look did she betray the fact that her
heart’s action was accelerated, or that she felt a thrill of joy to think
that the first of her moves in this intricate game had been successful.
“Of course, it would be Tavia’s good fortune to pick you up at the
station,” she said, while Garry held her hand just a moment longer
than was really necessary for politeness’ sake. “Had you telegraphed
us——”
“I hadn’t a thought that I was going to run up against Miss Travers
or you, Miss Dale,” he said.
“Oh, then, this is a business visit?” and she laughed. “Entirely?
You only wish to see Major Dale?”
“Well—now—that’s unfair,” he said, his eyes twinkling. “But I told
Miss Travers she might drive me to the hotel.”
“Oh, this will be your hotel while you remain, of course. Father
would not hear of anything else I am sure.”
“I can thank you, then, Miss Dale,” he said quietly and with a
sudden serious mien, “for the chance to sell my ranch at a better
price than those sharks were ready to give?”
“No. You may thank Major Dale’s bump of acquisitiveness,” she
said, laughing at him over her shoulder as she led the way into the
house. “Having so much land already out there, like other great
property owners, he is always looking for more.”
If Garry Knapp was not assured that she was entirely frank upon
this matter, he knew that his welcome was as warm as though he
were really an old friend. He met Mrs. White almost at once, and
Dorothy was delighted by her marked approval of him.
Garry Knapp got to the major by slow degrees. Tavia marveled as
she watched Dorothy Dale’s calm and assured methods. This was
the demure, cautious girl whom she had always looked upon as
being quite helpless when it came to managing “affairs” with
members of the opposite sex. Tavia imagined she was quite able to
manage any man—“put him in his place,” she termed it—much
better than Dorothy Dale. But now!
Dorothy quietly sent Joe and Roger out for Mr. Knapp’s bags and
told them to take the bags up to an indicated room. She made no
fuss about it, but took it for granted that Garry Knapp had come for a
visit, not for a call.
The young man from the West had to sit down and talk with Aunt
Winnie. That lady proceeded in her good-humored and tactful way to
draw him out. Aunt Winnie learned more about Garry Knapp in those
few minutes than even Tavia had learned when she took dinner with
the young man. And all the time the watchful Dorothy saw Garry
Knapp growing in her aunt’s estimation.
Ned came in. He had been fussing and fuming because business
had kept him from personally seeing Jennie Hapgood aboard her
train. He welcomed this big fellow from the West, perhaps, because
he helped take Ned’s mind off his own affairs.
“Come on up and dress for dinner,” Ned suggested, having gained
Garry Knapp’s sole attention. “It’s pretty near time for the big eats,
and mother is a stickler for the best bib and tucker at the evening
meal.”
“Great Scott!” gasped Garry Knapp in a panic. “You don’t mean
dinner dress? I haven’t had on a swallowtail since I was in college.”
“Tuxedo will do,” Ned said lightly. “If you didn’t bring ’em I’ll lend
you. I’m about as broad as you, my boy.”
Garry Knapp was three or four years older than Ned, and that “my
boy” sounded rather funny. However, the Westerner did not smile.
He accepted the loan of the dinner coat and the vest without
comment, but he looked very serious while he was dressing.
They went down together to meet the girls in the drawing-room.
Dorothy Dale and Tavia had dressed especially for the occasion.
Tavia flaunted her fine feathers frankly; but demure Dorothy’s eyes
shone more gloriously than her frock. Ned said:
“You look scrumptious, Coz. And, of course, Tavia, you are a
vision of delight. Where’s Nat?”
“Nat?” questioned Tavia, her countenance falling. “Is—isn’t he
upstairs?”
“Why, don’t you know?” Dorothy cried. “He’s gone to Boston. Left
just before you came back from the station, Tavia.”
“Well, of all things!” Ned said. “I’d have gone with him if I’d really
believed he meant it. Old grouch! He’s been talking of lighting out for
a week. But I am glad,” he added cordially, looking at Garry Knapp,
“that I did not go. Then I, too, might have missed meeting Mr.
Knapp.”
Now, what was it kept Major Dale away from the dinner table that
evening? His excuse was that a twinge or two of rheumatism kept
him from appearing with the family when dinner was called. And yet
Dorothy did not appear worried by her father’s absence as she
ordinarily would have been. Tavia was secretly delighted by this
added manifestation of Dorothy’s finesse. Garry Knapp could not find
any excuse for withdrawing from the house until he had interviewed
the major.
As was usual at The Cedars, the evening meal was a lively and
enjoyable occasion. Tavia successfully hid her chagrin at Nat’s
absence; but Joe and Roger were this evening the life of the
company.
“The river’s frozen,” sang Roger, “and we’re going skating on it,
Joe and I. Did you ever go skating, Mr. Knapp?” for Roger believed it
only common politeness to bring the visitor into the conversation.
“Sure enough,” laughed Garry Knapp. “I used to be some skater,
too.”
“You’d better come,” said Roger. “It’s going to be moonlight—
Popeye Jordan says so, and he knows, for his father lights the street
lamps and this is one of the nights he doesn’t have to work.”
“I hope Popeye hasn’t made a mistake—or Mr. Jordan, either—in
reading the almanac,” Dorothy said, when the laugh had subsided.
“You’d better come, too, Dorothy,” said Joe. “The river’s as smooth
as glass.”
“Let’s all go,” proposed Tavia, glad to be in anything active that
would occupy her mind and perhaps would push out certain
unpleasant thoughts that lodged there.
“Mr. Knapp has no skates,” said Dorothy, softly.
“Don’t let that stop you,” the Westerner put in, smiling. “I can go
and look on.”
“Oh, I guess we can give you a look in,” said Ned. “There’s Nat’s
skates. I think he didn’t take ’em with him.”
“Will they fit Mr. Knapp?” asked Tavia.
“Dead sure that nobody’s got a bigger foot than old Nat,” said his
brother wickedly. “If Mr. Knapp can get into my coat, he’ll find no
trouble in getting into Nat’s shoes.”
Ned rather prided himself on his own small and slim foot and often
took a fling at the size of his brother’s shoes. But now, Nat not being
present, he hoped to “get a rise” out of Tavia. The girl, however, bit
her lip and said nothing. She was not even defending Nat these
days.
It was concluded that all should go—that is, all the young people
then present. Nat and Jennie’s absence made what Ned called “a
big hole” in the company.
“You be good to me, Dot,” he said to his cousin, as they waited in
the side hall for Tavia to come down. “I’m going to miss Jennie
awfully. I want to skate with you and tell you all about it.”
“All about what?” demanded his cousin, laughing.
“Why, all about how we came to—to—to find out we cared for
each other,” Ned whispered, blunderingly enough but very earnest.
“You know, Dot, it’s just wonderful——”
“You go on, dear,” said Dorothy, poking a gloved forefinger at him.
“If you two sillies didn’t know you were in love with each other till you
brought home the ring the other night, why everybody else in the
neighborhood was aware of the fact æons and æons ago!”
“Huh?” grunted Ned, his eyes blinking in surprise.
“It was the most transparent thing in the world. Everybody around
here saw how the wind blew.”
“You don’t mean it!” said the really astonished Ned. “Well! and I
didn’t know it myself till I began to think how bad a time I was going
to have without Jennie. I wish old Nat would play up to Tavia.”
Dorothy looked at him scornfully. “Well! of all the stupid people
who ever lived, most men are it,” she thought. But what she said
aloud was:
“I want to skate with Mr. Knapp, Nedward. You know he is our
guest. You take Tavia.”
“Pshaw!” muttered her cousin as the girl in question appeared and
Garry Knapp and the boys came in from the porch where the
Westerner had been trying on Nat’s skating boots. “I can’t talk to the
flyaway as I can to you. But I don’t blame you for wanting to skate
with Knapp. He seems like a mighty fine fellow.”
Dorothy was getting the family’s opinion, one by one, of the man
Tavia wickedly whispered Dorothy had “set her cap” for. The younger
boys were plainly delighted with Garry Knapp. When the party got to
the river Joe and Roger would scarcely let the guest and Dorothy get
away by themselves.
Garry Knapp skated somewhat awkwardly at first, for he had not
been on the ice for several years. But he was very sure footed and it
was evident utterly unafraid.
He soon “got the hang of it,” as he said, and was then ready to
skate away with Dorothy. The Dale boys tried to keep up; but with
one of his smiles into the girl’s face, Knapp suddenly all but picked
her up and carried her off at a great pace over the shining, black ice.
“Oh! you take my breath!” she cried half aloud, yet clinging with
delight to his arm.
“We’ll dodge the little scamps and then get down to talk,” he said.
“I want to know all about it.”
“All about what?” she returned, looking at him with shy eyes and a
fluttering at her heart that she was glad he could not know about.
“About this game of getting me East again. I can see your fine
Italian hand in this, Miss Dale. Does your father really need my
land?”
He said it bluntly, and although he smiled, Dorothy realized there
was something quite serious behind his questioning.
“Well, you see, after you had left the hotel in New York, Tavia and I
overheard those two awful men you agreed to sell to talking about
the bargain,” she said rather stumblingly, but with earnestness.
“You did!” he exclaimed. “The sharks!”
“That is exactly what they were. They said after Stiffbold got out
West he would try to beat you down in your price, although at the
terms agreed upon he knew he was getting a bargain.”
“Oh-ho!” murmured Garry Knapp. “That’s the way of it, eh? They
had me scared all right. I gave them an option for thirty days for a
hundred dollars and they let the option run out. I was about to accept
a lower price when your father’s lawyers came around.”
“You see, Tavia and I were both interested,” Dorothy explained.
“And Tavia wrote to a friend of ours, Lance Petterby——”
IT SEEMED TO DOROTHY THAT THEY FAIRLY FLEW OVER THE
OPEN WATER.
Dorothy Dale’s Engagement Page 198

“Ah! that’s why old Lance came riding over to Bob Douglass’
place, was it?” murmured Garry.
“Then,” said Dorothy, bravely, “I mentioned the matter to father,
and he is always willing to buy property adjoining the Hardin place.
Thinks it is a good investment. He and Aunt Winnie, too, have a high
opinion of that section of the country. They believe it is the coming
wheat-growing land of the States.”
Garry’s mind seemed not to be absorbed by this phase of the
subject. He said abruptly:
“Your folks are mighty rich, Miss Dale, aren’t they?”
Dorothy started at this blunt and unusual question, but, after a
moment’s hesitation, decided to answer as frankly as the question
had been put.
“Oh! Aunt Winnie married a wealthy man—yes,” she said.
“Professor Winthrop White. But we were very poor, indeed, until a
few years ago when a distant relative left the major some property.
Then, of course, this Hardin estate is a big thing.”
“Yes,” said Garry, shortly. “And you are going to be wealthy in your
own right when you are of age. So your little friend told me.”
“Yes,” sighed Dorothy. “Tavia will talk. The same relative who left
father his first legacy, tied up some thousands for poor little me.”
Immediately Garry Knapp talked of other things. The night was
fine and the moon, a silver paring, hung low above the hills. The
stars were so bright that they were reflected in the black ice under
the skaters’ ringing steel.
Garry and Dorothy had shot away from the others and were now
well down the river toward the milldam. So perfectly had the ice
frozen that when they turned the blades of the skates left long,
soaplike shavings behind them.
With clasped hands, they took the stroke together perfectly. Never
had Dorothy skated with a partner that suited her so well. Nor had
she ever sped more swiftly over the ice.
Suddenly, she felt Garry’s muscles stiffen and saw his head jerk
up as he stared ahead.
“What is it?” she murmured, her own eyes so misty that she could
not see clearly. Then in a moment she uttered a frightened “Oh!”
They had crossed the river, and now, on coming back, there
unexpectedly appeared a long, open space before them. The water
was so still that at a distance the treacherous spot looked just like
the surrounding ice.
The discovery was made too late for them to stop. Indeed, Garry
Knapp increased his speed, picked her up in his arms and it seemed
to Dorothy that they fairly flew over the open water, landing with a
resonant ring of steel upon the safe ice beyond.
For the moment that she was held tightly in the young man’s arms,
she clung to him with something besides fear.
“Oh, Garry!” she gasped when he set her down again.
“Some jump, eh?” returned the young man coolly.
They skated on again without another word.
CHAPTER XXV
GARRY BALKS

The major was ready to see Garry Knapp at nine o’clock the next
morning. He was suffering one of his engagements with the enemy
rheumatism, and there really was a strong reason for his having put
off this interview until the shy Westerner had become somewhat
settled at The Cedars as a guest.
Dorothy took Garry up to the major’s room after breakfast, and
they found him well-wrapped in a rug, sitting in his sun parlor which
overlooked the lawns of The Cedars.
The young man from the West could not help being impressed by
the fact that he was the guest of a family that was well supplied with
this world’s goods—one that was used to luxury as well as comfort.
Is it strange that the most impressive point to him was the fact that
he had no right to even think of trying to win Dorothy Dale?
When he had awakened that morning and looked over the
luxurious furnishings of his chamber and the bathroom and dressing
room connected with it, he had told himself:
“Garford Knapp, you are in wrong! This is no place for a
cowpuncher from the Western plains. What little tad of money you
can sell your ranch for won’t put you in any such class as these folk
belong to.
“And as for thinking of that girl—Great Scot! I’d make a fine figure
asking any girl used to such luxury as this to come out and share a
shack in Desert City or thereabout, while I punched cattle, or went to
keeping store, or tried to match my wits in real estate with the sharks
that exploit land out there.
“Forget it, Garford!” he advised himself, grimly. “If you can make
an honest deal with this old major, make it and then clear out. This is
no place for you.”
He had, therefore, braced himself for the interview. The major,
eyeing him keenly as he walked down the long room beside Dorothy,
made his own judgment—as he always did—instantly. When Dorothy
had gone he said frankly to the young man:
“Mr. Knapp, I’m glad to see you. I have heard so much about you
that I feel you and I are already friends.”
“Thank you, sir,” said Garry, quietly, eyeing the major with as much
interest as the latter eyed him.
“When my daughter was talking one day about you and the land
you had in the market adjoining the Hardin tract it struck me that
perhaps it would be a good thing to buy,” went on the major, briskly.
“So I set our lawyers on your trail.”
“So Miss Dorothy tells me, sir,” the young man said.
“Now, they know all about the offer made you by those sharpers,
Stiffbold & Lightly. They advised me to risk a thousand dollar option
on your ranch and I telegraphed them to make you the offer.”
“And you may believe I was struck all of a heap, sir,” said the
young man, still eyeing the major closely. “I’ll tell you something:
You’ve got me guessing.”
“How’s that?” asked the amused Major Dale.
“Why, people don’t come around and hand me a thousand dollars
every day—and just on a gamble.”
“Sure I am gambling?” responded the major.
“I’m not sure of anything,” admitted Garry Knapp. “But it looks like
that. I accepted the certified check—I have it with me. I don’t know
but I’d better hand it back to you, Major, for I think you have been
misinformed about the real value of the ranch. The price per acre
your lawyers offer is away above the market.”
“Hey!” exclaimed Major Dale. “You call yourself a business man?”
“Not much of one, I suppose,” said Garry. “I’ll sell you my ranch
quick enough at a fair price. But this looks as if you were doing me a
favor. I think you have been influenced.”
“Eh?” stammered the astounded old gentleman.
“By your daughter,” said Garry, quietly. “I’m conceited enough to
think it is because of Miss Dale that you make me the offer you do.”
“Any crime in that?” demanded the major.
“No crime exactly,” rejoined Garry with one of his rare smiles,
“unless I take advantage of it. But I’m not the sort of fellow, Major
Dale, who can willingly accept more than I can give value for. Your
offer for my ranch is beyond reason.”
“Would you have thought so if another man—somebody instead of
my daughter’s father——” and his eyes twinkled as he said it, “had
made you the offer?”
Garry Knapp was silent and showed confusion. The major went on
with some grimness of expression:
“But if your conscience troubles you and you wish to call the deal
off, now is your chance to return the check.”
Instantly Garry pulled his wallet from his pocket and produced the
folded green slip, good for a thousand dollars at the Desert City Trust
Company.
“There you are, sir,” he said quietly, and laid the paper upon the
arm of the major’s chair.
The old gentleman picked it up, identified it, and slowly tore the
check into strips, eyeing the young man meanwhile.
“Then,” he said, calmly, “that phase of the matter is closed. But
you still wish to sell your ranch?”
“I do, Major Dale. But I can’t accept what anybody out there would
tell you was a price out of all reason.”
“Except my lawyers,” suggested the major.
“Well——”
“Young man, you have done a very foolish thing,” said Major Dale.
“A ridiculous thing, perhaps. Unless you are shrewder than you
seem. My lawyers have had your land thoroughly cruised. You have
the best wheat land, in embryo, anywhere in the Desert City region.”
Garry started and stared at him for a minute without speaking.
Then he sighed and shrugged his shoulders.
“That may be, sir. Perhaps you do know more about the intrinsic
value of my ranch than I do myself. But I know it would cost a mint of
money to develop that old rundown place into wheat soil.”
“Humph! and if you had this—er—mint of money, what would you
do?”
“Do? I’d develop it myself!” cried the young man, startled into
enthusiastic speech. “I know there is a fortune there. You are making
big profits on the Hardin place already, I understand. Cattle have
gone out; but wheat has come to stay. Oh, I know all about that! But
what’s the use?”
“Have you tried to raise money for the development of your land?”
asked the major quietly.
“I’ve talked to some bankers, yes. Nothing doing. The machinery
and fertilizer cost at the first would be prohibitive. A couple of crop
failures would wipe out everything, and the banks don’t want land on
their hands. As for the money-lenders—well, Major Dale, you can
imagine what sort of hold they demand when they deal with a person
in my situation.”
“And you would rather have what seems to you a fair price for your
land and get it off your hands?”
“I’ll accept a fair price—yes. But I can’t accept any favors,” said the
young man, his face gloomy enough but as stubborn as ever.
“I see,” said the major. “Then what will you do with the money you
get?”
“Try to get into some business that will make me more,” and Garry
looked up again with a sudden smile.
“Raising wheat does not attract you, then?”
“It’s the biggest prospect in that section. I know it has cattle raising
and even mining backed clear across the board. But it’s no game for
a little man with little capital.”
“Then why not get into it?” asked Major Dale, still speaking quietly.
“You seem enthusiastic. Enthusiasm and youth—why, my boy, they
will carry a fellow far!”
Garry looked at him in a rather puzzled way. “But don’t I tell you,
Major Dale, that the banks will not let me have money?”
“I’ll let you have the money—and at a fair interest,” said Major
Dale.
Garry smiled slowly and put out his hand. The major quickly took it
and his countenance began to brighten. But what Garry said caused
the old gentleman’s expression to become suddenly doleful:
“I can’t accept your offer, sir. I know that it is a favor—a favor that
is suggested by Miss Dorothy. If it were not for her, you would never
have thought of sending for me or making either of these more than
kind propositions you have made.
“I shall have to say no—and thank you.”

You might also like