100% found this document useful (1 vote)
30 views

Instant ebooks textbook (eBook PDF) Java How To Program (Early Objects) 10th download all chapters

How

Uploaded by

custumrafsun
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
30 views

Instant ebooks textbook (eBook PDF) Java How To Program (Early Objects) 10th download all chapters

How

Uploaded by

custumrafsun
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Download the full version of the ebook now at ebooksecure.

com

(eBook PDF) Java How To Program (Early


Objects) 10th

https://ebooksecure.com/product/ebook-pdf-java-
how-to-program-early-objects-10th/

Explore and download more ebook at https://ebooksecure.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

(eBook PDF) Java How to Program, Late Objects Global


Edition 11th Edition

http://ebooksecure.com/product/ebook-pdf-java-how-to-program-late-
objects-global-edition-11th-edition/

ebooksecure.com

(eBook PDF) Java How to Program, Early Objects 11th


Edition by Paul J. Deitel

http://ebooksecure.com/product/ebook-pdf-java-how-to-program-early-
objects-11th-edition-by-paul-j-deitel/

ebooksecure.com

C++ How to Program Early Objects Version 9th Edition


(eBook PDF)

http://ebooksecure.com/product/c-how-to-program-early-objects-
version-9th-edition-ebook-pdf/

ebooksecure.com

C++ How to Program: An Objects-Natural Approach, 11e 11th


Edition Paul Deitel - eBook PDF

https://ebooksecure.com/download/c-how-to-program-an-objects-natural-
approach-11e-ebook-pdf/

ebooksecure.com
(eBook PDF) Translational Medicine in CNS Drug
Development, Volume 29

http://ebooksecure.com/product/ebook-pdf-translational-medicine-in-
cns-drug-development-volume-29/

ebooksecure.com

Progress in Heterocyclic Chemistry Volume 29 1st Edition -


eBook PDF

https://ebooksecure.com/download/progress-in-heterocyclic-chemistry-
ebook-pdf/

ebooksecure.com

(eBook PDF) C++ How to Program 10th Edition by Paul J.


Deitel

http://ebooksecure.com/product/ebook-pdf-c-how-to-program-10th-
edition-by-paul-j-deitel/

ebooksecure.com

(eBook PDF) Big Java: Early Objects 5th Edition

http://ebooksecure.com/product/ebook-pdf-big-java-early-objects-5th-
edition/

ebooksecure.com

(eBook PDF) Big Java: Early Objects, 7th Edition

http://ebooksecure.com/product/ebook-pdf-big-java-early-objects-7th-
edition/

ebooksecure.com
Global Global
edition edition

edition
GlobalJava™ How to Program
For these Global Editions, the editorial team at Pearson has
collaborated with educators across the world to address a
wide range of subjects and requirements, equipping students

Early Objects
with the best possible learning tools. This Global Edition
preserves the cutting-edge approach and pedagogy of the
original, but also features alterations, customization and
adaptation from the North American version.

edition
TENTH
Java™ How to Program
Deitel • Deitel
This is a special edition of an established
title widely used by colleges and universities
throughout the world. Pearson published this
Early Objects
exclusive edition for the benefit of students
outside the United States and Canada. If you TENTH edition
purchased this book within the United States
or Canada you should be aware that it has
been imported without the approval of the
Publisher or Author.
Paul Deitel • Harvey Deitel
Pearson Global Edition
A01_DEIT7806_SE_10_TP.fm Page 6 Monday, July 7, 2014 12:37 PM

Trademarks
DEITEL, the double-thumbs-up bug and DIVE INTO are registered trademarks of Deitel and Associates,
Inc.
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks
of their respective owners.
Microsoft and/or its respective suppliers make no representations about the suitability of the information
contained in the documents and related graphics published as part of the services for any purpose. All
such documents and related graphics are provided “as is” without warranty of any kind. Microsoft and/
or its respective suppliers hereby disclaim all warranties and conditions with regard to this information,
including all warranties and conditions of merchantability, whether express, implied or statutory, fitness
for a particular purpose, title and non-infringement. In no event shall Microsoft and/or its respective sup-
pliers be liable for any special, indirect or consequential damages or any damages whatsoever resulting
from loss of use, data or profits, whether in an action of contract, negligence or other tortious action,
arising out of or in connection with the use or performance of information available from the services.
The documents and related graphics contained herein could include technical inaccuracies or typograph-
ical errors. Changes are periodically added to the information herein. Microsoft and/or its respective sup-
pliers may make improvements and/or changes in the product(s) and/or the program(s) described herein
at any time. Partial screen shots may be viewed in full within the software version specified.
Microsoft® and Windows® are registered trademarks of the Microsoft Corporation in the U.S.A. and
other countries. Screen shots and icons reprinted with permission from the Microsoft Corporation. This
book is not sponsored or endorsed by or affiliated with the Microsoft Corporation.UNIX is a registered
trademark of The Open Group.
Apache is a trademark of The Apache Software Foundation.
CSS and XML are registered trademarks of the World Wide Web Consortium.
Firefox is a registered trademark of the Mozilla Foundation.
Google is a trademark of Google, Inc.
Mac and OS X are trademarks of Apple Inc., registered in the U.S. and other countries.
Linux is a registered trademark of Linus Torvalds. All trademarks are property of their respective owners.
Throughout this book, trademarks are used. Rather than put a trademark symbol in every occurrence of
a trademarked name, we state that we are using the names in an editorial fashion only and to the benefit
of the trademark owner, with no intention of infringement of the trademark.
A02_DEIT7806_SE_10_TOC.fm Page 7 Monday, July 7, 2014 11:59 AM

Contents
Chapters 26–34 and Appendices F–N are PDF documents posted online at the book’s
Companion Website (located at www.pearsonglobaleditions.com/deitel). See the in-
side front cover for information on accessing the Companion Website.

Foreword 23
Preface 25
Before You Begin 39
1 Introduction to Computers, the Internet and Java 43
1.1 Introduction 44
1.2 Hardware and Software 46
1.2.1 Moore’s Law 46
1.2.2 Computer Organization 47
1.3 Data Hierarchy 48
1.4 Machine Languages, Assembly Languages and High-Level Languages 51
1.5 Introduction to Object Technology 52
1.5.1 The Automobile as an Object 52
1.5.2 Methods and Classes 53
1.5.3 Instantiation 53
1.5.4 Reuse 53
1.5.5 Messages and Method Calls 53
1.5.6 Attributes and Instance Variables 53
1.5.7 Encapsulation and Information Hiding 54
1.5.8 Inheritance 54
1.5.9 Interfaces 54
1.5.10 Object-Oriented Analysis and Design (OOAD) 54
1.5.11 The UML (Unified Modeling Language) 55
1.6 Operating Systems 55
1.6.1 Windows—A Proprietary Operating System 55
1.6.2 Linux—An Open-Source Operating System 56
1.6.3 Android 56
1.7 Programming Languages 57
1.8 Java 59
1.9 A Typical Java Development Environment 59
1.10 Test-Driving a Java Application 63
A02_DEIT7806_SE_10_TOC.fm Page 8 Monday, July 7, 2014 11:59 AM

8 Contents

1.11 Internet and World Wide Web 67


1.11.1 The Internet: A Network of Networks 68
1.11.2 The World Wide Web: Making the Internet User-Friendly 68
1.11.3 Web Services and Mashups 68
1.11.4 Ajax 69
1.11.5 The Internet of Things 69
1.12 Software Technologies 70
1.13 Keeping Up-to-Date with Information Technologies 72

2 Introduction to Java Applications;


Input/Output and Operators 76
2.1 Introduction 77
2.2 Your First Program in Java: Printing a Line of Text 77
2.3 Modifying Your First Java Program 83
2.4 Displaying Text with printf 85
2.5 Another Application: Adding Integers 87
2.5.1 import Declarations 87
2.5.2 Declaring Class Addition 88
2.5.3 Declaring and Creating a Scanner to Obtain User Input from
the Keyboard 88
2.5.4 Declaring Variables to Store Integers 89
2.5.5 Prompting the User for Input 90
2.5.6 Obtaining an int as Input from the User 90
2.5.7 Prompting for and Inputting a Second int 91
2.5.8 Using Variables in a Calculation 91
2.5.9 Displaying the Result of the Calculation 91
2.5.10 Java API Documentation 91
2.6 Memory Concepts 92
2.7 Arithmetic 93
2.8 Decision Making: Equality and Relational Operators 96
2.9 Wrap-Up 100

3 Introduction to Classes, Objects, Methods


and Strings 111
3.1 Introduction 112
3.2 Instance Variables, set Methods and get Methods 113
3.2.1 Account Class with an Instance Variable, a set Method and
a get Method 113
3.2.2 AccountTest Class That Creates and Uses an Object of
Class Account 116
3.2.3 Compiling and Executing an App with Multiple Classes 119
3.2.4 Account UML Class Diagram with an Instance Variable and
set and get Methods 119
3.2.5 Additional Notes on Class AccountTest 120
A02_DEIT7806_SE_10_TOC.fm Page 9 Monday, July 7, 2014 11:59 AM

Contents 9

3.2.6 Software Engineering with private Instance Variables and


public set and get Methods 121
3.3 Primitive Types vs. Reference Types 122
3.4 Account Class: Initializing Objects with Constructors 123
3.4.1 Declaring an Account Constructor for Custom Object Initialization 123
3.4.2 Class AccountTest: Initializing Account Objects When
They’re Created 124
3.5 Account Class with a Balance; Floating-Point Numbers 126
3.5.1 Account Class with a balance Instance Variable of Type double 127
3.5.2 AccountTest Class to Use Class Account 128
3.6 (Optional) GUI and Graphics Case Study: Using Dialog Boxes 132
3.7 Wrap-Up 135

4 Control Statements: Part 1; Assignment,


++ and -- Operators 143
4.1 Introduction 144
4.2 Algorithms 144
4.3 Pseudocode 145
4.4 Control Structures 145
4.5 if Single-Selection Statement 147
4.6 if…else Double-Selection Statement 148
4.7 Student Class: Nested if…else Statements 153
4.8 while Repetition Statement 155
4.9 Formulating Algorithms: Counter-Controlled Repetition 157
4.10 Formulating Algorithms: Sentinel-Controlled Repetition 161
4.11 Formulating Algorithms: Nested Control Statements 168
4.12 Compound Assignment Operators 173
4.13 Increment and Decrement Operators 173
4.14 Primitive Types 176
4.15 (Optional) GUI and Graphics Case Study: Creating Simple Drawings 177
4.16 Wrap-Up 181

5 Control Statements: Part 2; Logical Operators 194


5.1 Introduction 195
5.2 Essentials of Counter-Controlled Repetition 195
5.3 for Repetition Statement 197
5.4 Examples Using the for Statement 201
5.5 do…while Repetition Statement 205
5.6 switch Multiple-Selection Statement 207
5.7 Class AutoPolicy Case Study: Strings in switch Statements 213
5.8 break and continue Statements 216
5.9 Logical Operators 218
5.10 Structured Programming Summary 224
5.11 (Optional) GUI and Graphics Case Study: Drawing Rectangles and Ovals 229
5.12 Wrap-Up 232
A02_DEIT7806_SE_10_TOC.fm Page 10 Monday, July 7, 2014 11:59 AM

10 Contents

6 Methods: A Deeper Look 242


6.1 Introduction 243
6.2 Program Modules in Java 243
6.3 static Methods, static Fields and Class Math 245
6.4 Declaring Methods with Multiple Parameters 247
6.5 Notes on Declaring and Using Methods 250
6.6 Method-Call Stack and Stack Frames 251
6.7 Argument Promotion and Casting 252
6.8 Java API Packages 253
6.9 Case Study: Secure Random-Number Generation 255
6.10 Case Study: A Game of Chance; Introducing enum Types 260
6.11 Scope of Declarations 264
6.12 Method Overloading 267
6.13 (Optional) GUI and Graphics Case Study: Colors and Filled Shapes 269
6.14 Wrap-Up 272

7 Arrays and ArrayLists 285


7.1 Introduction 286
7.2 Arrays 287
7.3 Declaring and Creating Arrays 288
7.4 Examples Using Arrays 289
7.4.1 Creating and Initializing an Array 289
7.4.2 Using an Array Initializer 290
7.4.3 Calculating the Values to Store in an Array 291
7.4.4 Summing the Elements of an Array 293
7.4.5 Using Bar Charts to Display Array Data Graphically 293
7.4.6 Using the Elements of an Array as Counters 295
7.4.7 Using Arrays to Analyze Survey Results 296
7.5 Exception Handling: Processing the Incorrect Response 298
7.5.1 The try Statement 298
7.5.2 Executing the catch Block 298
7.5.3 toString Method of the Exception Parameter 299
7.6 Case Study: Card Shuffling and Dealing Simulation 299
7.7 Enhanced for Statement 304
7.8 Passing Arrays to Methods 305
7.9 Pass-By-Value vs. Pass-By-Reference 307
7.10 Case Study: Class GradeBook Using an Array to Store Grades 308
7.11 Multidimensional Arrays 314
7.12 Case Study: Class GradeBook Using a Two-Dimensional Array 317
7.13 Variable-Length Argument Lists 323
7.14 Using Command-Line Arguments 325
7.15 Class Arrays 327
7.16 Introduction to Collections and Class ArrayList 329
7.17 (Optional) GUI and Graphics Case Study: Drawing Arcs 333
7.18 Wrap-Up 336
A02_DEIT7806_SE_10_TOC.fm Page 11 Monday, July 7, 2014 11:59 AM

Contents 11

8 Classes and Objects: A Deeper Look 357


8.1 Introduction 358
8.2 Time Class Case Study 358
8.3 Controlling Access to Members 363
8.4 Referring to the Current Object’s Members with the this Reference 364
8.5 Time Class Case Study: Overloaded Constructors 366
8.6 Default and No-Argument Constructors 372
8.7 Notes on Set and Get Methods 372
8.8 Composition 374
8.9 enum Types 377
8.10 Garbage Collection 379
8.11 static Class Members 380
8.12 static Import 384
8.13 final Instance Variables 385
8.14 Package Access 386
8.15 Using BigDecimal for Precise Monetary Calculations 387
8.16 (Optional) GUI and Graphics Case Study: Using Objects with Graphics 390
8.17 Wrap-Up 394

9 Object-Oriented Programming: Inheritance 402


9.1 Introduction 403
9.2 Superclasses and Subclasses 404
9.3 protected Members 406
9.4 Relationship Between Superclasses and Subclasses 407
9.4.1 Creating and Using a CommissionEmployee Class 407
9.4.2 Creating and Using a BasePlusCommissionEmployee Class 413
9.4.3 Creating a CommissionEmployee–BasePlusCommissionEmployee
Inheritance Hierarchy 418
9.4.4 CommissionEmployee–BasePlusCommissionEmployee
Inheritance Hierarchy Using protected Instance Variables 421
9.4.5 CommissionEmployee–BasePlusCommissionEmployee
Inheritance Hierarchy Using private Instance Variables 424
9.5 Constructors in Subclasses 429
9.6 Class Object 429
9.7 (Optional) GUI and Graphics Case Study: Displaying Text and
Images Using Labels 430
9.8 Wrap-Up 433

10 Object-Oriented Programming:
Polymorphism and Interfaces 437
10.1 Introduction 438
10.2 Polymorphism Examples 440
10.3 Demonstrating Polymorphic Behavior 441
10.4 Abstract Classes and Methods 443
A02_DEIT7806_SE_10_TOC.fm Page 12 Monday, July 7, 2014 11:59 AM

12 Contents

10.5 Case Study: Payroll System Using Polymorphism 446


10.5.1 Abstract Superclass Employee 447
10.5.2 Concrete Subclass SalariedEmployee 449
10.5.3 Concrete Subclass HourlyEmployee 451
10.5.4 Concrete Subclass CommissionEmployee 453
10.5.5 Indirect Concrete Subclass BasePlusCommissionEmployee 455
10.5.6 Polymorphic Processing, Operator instanceof and Downcasting 456
10.6 Allowed Assignments Between Superclass and Subclass Variables 461
10.7 final Methods and Classes 461
10.8 A Deeper Explanation of Issues with Calling Methods from Constructors 462
10.9 Creating and Using Interfaces 463
10.9.1 Developing a Payable Hierarchy 464
10.9.2 Interface Payable 465
10.9.3 Class Invoice 466
10.9.4 Modifying Class Employee to Implement Interface Payable 468
10.9.5 Modifying Class SalariedEmployee for Use in the Payable
Hierarchy 470
10.9.6 Using Interface Payable to Process Invoices and Employees
Polymorphically 472
10.9.7 Some Common Interfaces of the Java API 473
10.10 Java SE 8 Interface Enhancements 474
10.10.1 default Interface Methods 474
10.10.2 static Interface Methods 475
10.10.3 Functional Interfaces 475
10.11 (Optional) GUI and Graphics Case Study: Drawing with Polymorphism 475
10.12 Wrap-Up 478

11 Exception Handling: A Deeper Look 483


11.1 Introduction 484
11.2 Example: Divide by Zero without Exception Handling 485
11.3 Example: Handling ArithmeticExceptions and InputMismatchExceptions 487
11.4 When to Use Exception Handling 493
11.5 Java Exception Hierarchy 493
11.6 finally Block 496
11.7 Stack Unwinding and Obtaining Information from an Exception Object 501
11.8 Chained Exceptions 503
11.9 Declaring New Exception Types 506
11.10 Preconditions and Postconditions 507
11.11 Assertions 507
11.12 try-with-Resources: Automatic Resource Deallocation 509
11.13 Wrap-Up 509

12 GUI Components: Part 1 515


12.1 Introduction 516
A02_DEIT7806_SE_10_TOC.fm Page 13 Monday, July 7, 2014 11:59 AM

Contents 13

12.2 Java’s Nimbus Look-and-Feel 517


12.3 Simple GUI-Based Input/Output with JOptionPane 518
12.4 Overview of Swing Components 521
12.5 Displaying Text and Images in a Window 523
12.6 Text Fields and an Introduction to Event Handling with Nested Classes 527
12.7 Common GUI Event Types and Listener Interfaces 533
12.8 How Event Handling Works 535
12.9 JButton 537
12.10 Buttons That Maintain State 540
12.10.1 JCheckBox 541
12.10.2 JRadioButton 543
12.11 JComboBox; Using an Anonymous Inner Class for Event Handling 546
12.12 JList 550
12.13 Multiple-Selection Lists 553
12.14 Mouse Event Handling 555
12.15 Adapter Classes 560
12.16 JPanel Subclass for Drawing with the Mouse 564
12.17 Key Event Handling 567
12.18 Introduction to Layout Managers 570
12.18.1 FlowLayout 572
12.18.2 BorderLayout 574
12.18.3 GridLayout 578
12.19 Using Panels to Manage More Complex Layouts 580
12.20 JTextArea 581
12.21 Wrap-Up 584

13 Graphics and Java 2D 597


13.1 Introduction 598
13.2 Graphics Contexts and Graphics Objects 600
13.3 Color Control 601
13.4 Manipulating Fonts 608
13.5 Drawing Lines, Rectangles and Ovals 613
13.6 Drawing Arcs 617
13.7 Drawing Polygons and Polylines 620
13.8 Java 2D API 623
13.9 Wrap-Up 630

14 Strings, Characters and Regular Expressions 638


14.1 Introduction 639
14.2 Fundamentals of Characters and Strings 639
14.3 Class String 640
14.3.1 String Constructors 640
14.3.2 String Methods length, charAt and getChars 641
14.3.3 Comparing Strings 642
A02_DEIT7806_SE_10_TOC.fm Page 14 Monday, July 7, 2014 11:59 AM

14 Contents

14.3.4 Locating Characters and Substrings in Strings 647


14.3.5 Extracting Substrings from Strings 649
14.3.6 Concatenating Strings 650
14.3.7 Miscellaneous String Methods 650
14.3.8 String Method valueOf 652
14.4 Class StringBuilder 653
14.4.1 StringBuilder Constructors 654
14.4.2 StringBuilder Methods length, capacity, setLength
and ensureCapacity 654
14.4.3 StringBuilder Methods charAt, setCharAt, getChars
and reverse 656
14.4.4 StringBuilder append Methods 657
14.4.5 StringBuilder Insertion and Deletion Methods 659
14.5 Class Character 660
14.6 Tokenizing Strings 665
14.7 Regular Expressions, Class Pattern and Class Matcher 666
14.8 Wrap-Up 675

15 Files, Streams and Object Serialization 686


15.1 Introduction 687
15.2 Files and Streams 687
15.3 Using NIO Classes and Interfaces to Get File and Directory Information 689
15.4 Sequential-Access Text Files 693
15.4.1 Creating a Sequential-Access Text File 693
15.4.2 Reading Data from a Sequential-Access Text File 697
15.4.3 Case Study: A Credit-Inquiry Program 699
15.4.4 Updating Sequential-Access Files 703
15.5 Object Serialization 704
15.5.1 Creating a Sequential-Access File Using Object Serialization 705
15.5.2 Reading and Deserializing Data from a Sequential-Access File 710
15.6 Opening Files with JFileChooser 712
15.7 (Optional) Additional java.io Classes 715
15.7.1 Interfaces and Classes for Byte-Based Input and Output 715
15.7.2 Interfaces and Classes for Character-Based Input and Output 717
15.8 Wrap-Up 718

16 Generic Collections 726


16.1 Introduction 727
16.2 Collections Overview 727
16.3 Type-Wrapper Classes 729
16.4 Autoboxing and Auto-Unboxing 729
16.5 Interface Collection and Class Collections 729
16.6 Lists 730
16.6.1 ArrayList and Iterator 731
16.6.2 LinkedList 733
Visit https://ebooksecure.com
now to explore a rich
collection of ebook and enjoy
exciting offers!
A02_DEIT7806_SE_10_TOC.fm Page 15 Monday, July 7, 2014 11:59 AM

Contents 15

16.7 Collections Methods 738


16.7.1 Method sort 739
16.7.2 Method shuffle 742
16.7.3 Methods reverse, fill, copy, max and min 744
16.7.4 Method binarySearch 746
16.7.5 Methods addAll, frequency and disjoint 748
16.8 Stack Class of Package java.util 750
16.9 Class PriorityQueue and Interface Queue 752
16.10 Sets 753
16.11 Maps 756
16.12 Properties Class 760
16.13 Synchronized Collections 763
16.14 Unmodifiable Collections 763
16.15 Abstract Implementations 764
16.16 Wrap-Up 764

17 Java SE 8 Lambdas and Streams 771


17.1 Introduction 772
17.2 Functional Programming Technologies Overview 773
17.2.1 Functional Interfaces 774
17.2.2 Lambda Expressions 775
17.2.3 Streams 776
17.3 IntStream Operations 778
17.3.1 Creating an IntStream and Displaying Its Values with the
forEach Terminal Operation 780
17.3.2 Terminal Operations count, min, max, sum and average 781
17.3.3 Terminal Operation reduce 781
17.3.4 Intermediate Operations: Filtering and Sorting IntStream Values 783
17.3.5 Intermediate Operation: Mapping 784
17.3.6 Creating Streams of ints with IntStream Methods range and
rangeClosed 785
17.4 Stream<Integer> Manipulations 785
17.4.1 Creating a Stream<Integer> 786
17.4.2 Sorting a Stream and Collecting the Results 787
17.4.3 Filtering a Stream and Storing the Results for Later Use 787
17.4.4 Filtering and Sorting a Stream and Collecting the Results 787
17.4.5 Sorting Previously Collected Results 787
17.5 Stream<String> Manipulations 788
17.5.1 Mapping Strings to Uppercase Using a Method Reference 789
17.5.2 Filtering Strings Then Sorting Them in Case-Insensitive
Ascending Order 790
17.5.3 Filtering Strings Then Sorting Them in Case-Insensitive
Descending Order 790
17.6 Stream<Employee> Manipulations 790
17.6.1 Creating and Displaying a List<Employee> 792
A02_DEIT7806_SE_10_TOC.fm Page 16 Monday, July 7, 2014 11:59 AM

16 Contents

17.6.2 Filtering Employees with Salaries in a Specified Range 793


17.6.3 Sorting Employees By Multiple Fields 794
17.6.4 Mapping Employees to Unique Last Name Strings 796
17.6.5 Grouping Employees By Department 797
17.6.6 Counting the Number of Employees in Each Department 798
17.6.7 Summing and Averaging Employee Salaries 798
17.7 Creating a Stream<String> from a File 800
17.8 Generating Streams of Random Values 803
17.9 Lambda Event Handlers 805
17.10 Additional Notes on Java SE 8 Interfaces 805
17.11 Java SE 8 and Functional Programming Resources 806
17.12 Wrap-Up 806

18 Recursion 818
18.1 Introduction 819
18.2 Recursion Concepts 820
18.3 Example Using Recursion: Factorials 821
18.4 Reimplementing Class FactorialCalculator Using Class BigInteger 823
18.5 Example Using Recursion: Fibonacci Series 825
18.6 Recursion and the Method-Call Stack 828
18.7 Recursion vs. Iteration 829
18.8 Towers of Hanoi 831
18.9 Fractals 833
18.9.1 Koch Curve Fractal 833
18.9.2 (Optional) Case Study: Lo Feather Fractal 834
18.10 Recursive Backtracking 843
18.11 Wrap-Up 844

19 Searching, Sorting and Big O 852


19.1 Introduction 853
19.2 Linear Search 854
19.3 Big O Notation 856
19.3.1 O(1) Algorithms 856
19.3.2 O(n) Algorithms 857
19.3.3 O(n2) Algorithms 857
19.3.4 Big O of the Linear Search 858
19.4 Binary Search 858
19.4.1 Binary Search Implementation 859
19.4.2 Efficiency of the Binary Search 862
19.5 Sorting Algorithms 862
19.6 Selection Sort 863
19.6.1 Selection Sort Implementation 863
19.6.2 Efficiency of the Selection Sort 866
19.7 Insertion Sort 866
A02_DEIT7806_SE_10_TOC.fm Page 17 Monday, July 7, 2014 11:59 AM

Contents 17

19.7.1 Insertion Sort Implementation 867


19.7.2 Efficiency of the Insertion Sort 869
19.8 Merge Sort 869
19.8.1 Merge Sort Implementation 870
19.8.2 Efficiency of the Merge Sort 874
19.9 Big O Summary for This Chapter’s Searching and Sorting Algorithms 875
19.10 Wrap-Up 876

20 Generic Classes and Methods 881


20.1 Introduction 882
20.2 Motivation for Generic Methods 882
20.3 Generic Methods: Implementation and Compile-Time Translation 884
20.4 Additional Compile-Time Translation Issues: Methods That Use a
Type Parameter as the Return Type 887
20.5 Overloading Generic Methods 890
20.6 Generic Classes 891
20.7 Raw Types 898
20.8 Wildcards in Methods That Accept Type Parameters 902
20.9 Wrap-Up 906

21 Custom Generic Data Structures 911


21.1 Introduction 912
21.2 Self-Referential Classes 913
21.3 Dynamic Memory Allocation 913
21.4 Linked Lists 914
21.4.1 Singly Linked Lists 914
21.4.2 Implementing a Generic List Class 915
21.4.3 Generic Classes ListNode and List 920
21.4.4 Class ListTest 920
21.4.5 List Method insertAtFront 920
21.4.6 List Method insertAtBack 921
21.4.7 List Method removeFromFront 922
21.4.8 List Method removeFromBack 923
21.4.9 List Method print 924
21.4.10 Creating Your Own Packages 924
21.5 Stacks 928
21.6 Queues 932
21.7 Trees 935
21.8 Wrap-Up 942

22 GUI Components: Part 2 953


22.1 Introduction 954
22.2 JSlider 954
A02_DEIT7806_SE_10_TOC.fm Page 18 Monday, July 7, 2014 11:59 AM

18 Contents

22.3 Understanding Windows in Java 958


22.4 Using Menus with Frames 959
22.5 JPopupMenu 967
22.6 Pluggable Look-and-Feel 970
22.7 JDesktopPane and JInternalFrame 975
22.8 JTabbedPane 978
22.9 BoxLayout Layout Manager 980
22.10 GridBagLayout Layout Manager 984
22.11 Wrap-Up 994

23 Concurrency 999
23.1 Introduction 1000
23.2 Thread States and Life Cycle 1002
23.2.1 New and Runnable States 1003
23.2.2 Waiting State 1003
23.2.3 Timed Waiting State 1003
23.2.4 Blocked State 1003
23.2.5 Terminated State 1003
23.2.6 Operating-System View of the Runnable State 1004
23.2.7 Thread Priorities and Thread Scheduling 1004
23.2.8 Indefinite Postponement and Deadlock 1005
23.3 Creating and Executing Threads with the Executor Framework 1005
23.4 Thread Synchronization 1009
23.4.1 Immutable Data 1010
23.4.2 Monitors 1010
23.4.3 Unsynchronized Mutable Data Sharing 1011
23.4.4 Synchronized Mutable Data Sharing—Making Operations Atomic 1016
23.5 Producer/Consumer Relationship without Synchronization 1018
23.6 Producer/Consumer Relationship: ArrayBlockingQueue 1026
23.7 (Advanced) Producer/Consumer Relationship with synchronized,
wait, notify and notifyAll 1029
23.8 (Advanced) Producer/Consumer Relationship: Bounded Buffers 1036
23.9 (Advanced) Producer/Consumer Relationship: The Lock and
Condition Interfaces 1044
23.10 Concurrent Collections 1051
23.11 Multithreading with GUI: SwingWorker 1053
23.11.1 Performing Computations in a Worker Thread:
Fibonacci Numbers 1054
23.11.2 Processing Intermediate Results: Sieve of Eratosthenes 1060
23.12 sort and parallelSort Timings with the Java SE 8 Date/Time API 1067
23.13 Java SE 8: Sequential vs. Parallel Streams 1069
23.14 (Advanced) Interfaces Callable and Future 1072
23.15 (Advanced) Fork/Join Framework 1076
23.16 Wrap-Up 1076
A02_DEIT7806_SE_10_TOC.fm Page 19 Monday, July 7, 2014 11:59 AM

Contents 19

24 Accessing Databases with JDBC 1087


24.1 Introduction 1088
24.2 Relational Databases 1089
24.3 A books Database 1090
24.4 SQL 1094
24.4.1 Basic SELECT Query 1094
24.4.2 WHERE Clause 1095
24.4.3 ORDER BY Clause 1097
24.4.4 Merging Data from Multiple Tables: INNER JOIN 1098
24.4.5 INSERT Statement 1100
24.4.6 UPDATE Statement 1101
24.4.7 DELETE Statement 1102
24.5 Setting up a Java DB Database 1102
24.5.1 Creating the Chapter’s Databases on Windows 1103
24.5.2 Creating the Chapter’s Databases on Mac OS X 1104
24.5.3 Creating the Chapter’s Databases on Linux 1105
24.6 Manipulating Databases with JDBC 1105
24.6.1 Connecting to and Querying a Database 1105
24.6.2 Querying the books Database 1109
24.7 RowSet Interface 1122
24.8 PreparedStatements 1124
24.9 Stored Procedures 1140
24.10 Transaction Processing 1140
24.11 Wrap-Up 1141

25 JavaFX GUI: Part 1 1149


25.1 Introduction 1150
25.2 JavaFX Scene Builder and the NetBeans IDE 1151
25.3 JavaFX App Window Structure 1152
25.4 Welcome App—Displaying Text and an Image 1153
25.4.1 Creating the App’s Project 1153
25.4.2 NetBeans Projects Window—Viewing the Project Contents 1155
25.4.3 Adding an Image to the Project 1156
25.4.4 Opening JavaFX Scene Builder from NetBeans 1156
25.4.5 Changing to a VBox Layout Container 1157
25.4.6 Configuring the VBox Layout Container 1158
25.4.7 Adding and Configuring a Label 1158
25.4.8 Adding and Configuring an ImageView 1158
25.4.9 Running the Welcome App 1159
25.5 Tip Calculator App—Introduction to Event Handling 1160
25.5.1 Test-Driving the Tip Calculator App 1161
25.5.2 Technologies Overview 1161
25.5.3 Building the App’s GUI 1164
25.5.4 TipCalculator Class 1168
25.5.5 TipCalculatorController Class 1170
A02_DEIT7806_SE_10_TOC.fm Page 20 Monday, July 7, 2014 11:59 AM

20 Contents

25.6 Features Covered in the Online JavaFX Chapters 1175


25.7 Wrap-Up 1176

Chapters on the Web 1183

A Operator Precedence Chart 1185

B ASCII Character Set 1187

C Keywords and Reserved Words 1188

D Primitive Types 1189

E Using the Debugger 1190


E.1 Introduction 1191
E.2 Breakpoints and the run, stop, cont and print Commands 1191
E.3 The print and set Commands 1195
E.4 Controlling Execution Using the step, step up and next Commands 1197
E.5 The watch Command 1200
E.6 The clear Command 1202
E.7 Wrap-Up 1204

Appendices on the Web 1207

Index 1209

Online Chapters and Appendices


Chapters 26–34 and Appendices F–N are PDF documents posted online at the book’s
Companion Website (located at www.pearsonglobaleditions.com/deitel). See the in-
side front cover for information on accessing the Companion Website.

26 JavaFX GUI: Part 2


27 JavaFX Graphics and Multimedia
28 Networking
29 Java Persistence API (JPA)
30 JavaServer™ Faces Web Apps: Part 1
A02_DEIT7806_SE_10_TOC.fm Page 21 Monday, July 7, 2014 11:59 AM

Contents 21

31 JavaServer™ Faces Web Apps: Part 2


32 REST-Based Web Services
33 (Optional) ATM Case Study, Part 1:
Object-Oriented Design with the UML
34 (Optional) ATM Case Study, Part 2:
Implementing an Object-Oriented Design
F Using the Java API Documentation
G Creating Documentation with javadoc
H Unicode®
I Formatted Output
J Number Systems
K Bit Manipulation
L Labeled break and continue Statements
M UML 2: Additional Diagram Types
N Design Patterns
A02_DEIT7806_SE_10_TOC.fm Page 22 Monday, July 7, 2014 11:59 AM
A03_DEIT7806_SE_10_FWD.fm Page 23 Monday, July 7, 2014 11:28 AM

Foreword
I’ve been enamored with Java even prior to its 1.0 release in 1995, and have subsequently
been a Java developer, author, speaker, teacher and Oracle Java Technology Ambassador.
In this journey, it has been my privilege to call Paul Deitel a colleague, and to often lever-
age and recommend his Java How To Program book. In its many editions, this book has
proven to be a great text for college and professional courses that I and others have devel-
oped to teach the Java programming language.
One of the qualities that makes this book a great resource is its thorough and insightful
coverage of Java concepts, including those introduced recently in Java SE 8. Another useful
quality is its treatment of concepts and practices essential to effective software development.
As a long-time fan of this book, I’d like to point out some of the features of this tenth
edition about which I’m most excited:
• An ambitious new chapter on Java lambda expressions and streams. This chapter
starts out with a primer on functional programming, introducing Java lambda ex-
pressions and how to use streams to perform functional programming tasks on
collections.
• Although concurrency has been addressed since the first edition of the book, it is
increasingly important because of multi-core architectures. There are timing ex-
amples—using the new Date/Time API classes introduced in Java SE 8—in the
concurrency chapter that show the performance improvements with multi-core
over single-core.
• JavaFX is Java’s GUI/graphics/multimedia technology moving forward, so it is
nice to see a three-chapter treatment of JavaFX in the Deitel live-code pedagogic
style. One of these chapters is in the printed book and the other two are online.
Please join me in congratulating Paul and Harvey Deitel on their latest edition of a won-
derful resource for computer science students and software developers alike!

James L. Weaver
Java Technology Ambassador
Oracle Corporation
Other documents randomly have
different content
All turned their attention to the game. The well thumbed pack
was brought out and given to John to cut. The game progressed
merrily enough for the others, but John was silent. Finally he lost the
game.
“Wine all around,” he muttered hoarsely.
“Here, Maria,” shouted her father to the daughter in the store
proper, “come and give these gentlemen some wine.” They drank the
wine and John flung the marked coin on the counter and started for
the door.
Oh, this raiding business was awful!
But before he had reached the door he heard Manuel shout to his
daughter, “Ajoga o dinheiro.” (Throw away the money.) “The police
are upon us!”
Maria had the coin, which John had paid, in her hand. Just
outside the little back room was a pit covered with boards over
which her father’s horse and wagon were washed. Maria ran out
quickly, dropped the coin between the cracks, and heard the splash
which it made as it touched the water.
She returned and saw an officer examining the cash drawer for
the marked coin.
“Eu digo a verdade,” her father said, “Me no sell wine; me give
mans.”
“You’re a liar,” said the officer testily, for he hated to be beaten in
a raid, “but just the same I’ll have to let you go this time. Look out
for us, however.” And the police left the store amid the jeers and
gibes of the hangers-on at Manuel’s.
“The rascal,” said Manuel to his daughter when all was quiet, “to
try and catch us in a trap like that.”
“Never mind him,” said Maria with a toss of her pretty head. “I
fooled him once tonight and I’ll fool him again. I just promised
Antonio that I’d marry him after the Festa do Espirito Santo.”
A CHANGE OF
OPINION
A CHANGE OF OPINION

I.
f course it happened at the club. Things of this kind
always happen at a club, either because the members
feel freer to discuss the weaker sex when they are not
around, or because some men think a club the only
place for such speeches.
John Harris made the remark, and Walter Andrews, the pet of half
the ladies in the town, was its bitterest opposer.
“I do not believe it,” he said vehemently. “You can not make me
believe it.”
“Nevertheless, my boy, I repeat; no one ever saw or heard of a
really beautiful woman who was good. Mark you, I’m not saying
anything against the merely ‘very pretty girl.’ I’ll admit that there are
some very pretty women who, in addition to their loveliness, are
really good. But these are merely pretty, not beautiful,” Harris
replied.
“What is your standard of ‘goodness’ in a woman, anyway?”
“Well, I’ll admit that my ideal woman would be hard to find. Even
the ‘goodness’ part would be largely above par in a plain, ugly
woman, let alone in a beautiful one. So I’ll take off a few
requirements, and if you can find me a woman who is not a flirt
even in the strictest sense of the word, and who never has been
accused of trying to make a man love her, and, when she has him in
that fix, declare that she only ‘likes him,’ and ‘hopes that they’ll
always be friends’; if you can find such a woman, I’ll—but you can’t.”
The subject was dropped, and shortly after Andrews left the club.
He went home early and to bed, but sleep did not come as it was
wont to. All night long he tossed thinking of what Harris had said,
and wondering where he could find a woman who could come up to
the requirements.

II.
It was a very preoccupied Andrews which entered the office of
“Roberts and Andrews” the next morning, and more than once his
partner asked, “What is the matter with you?”
“Nothing much,” was the invariable response.
Toward afternoon, Mr. Roberts came to him and said, “Andrews,
my niece is coming here to visit us for a while. Can you suggest
anything which would be nice for a young lady of twenty or twenty-
one to do?”
“How’s yachting?”
“The very thing. Funny that we did not think about that. Diana is
very fond of it, she writes. You have a yacht, haven’t you?”
“Yes.”
“What do you call her?”
“The yacht’s name is Diana,” said Andrews, digging his paper-
cutter into the blotter on his desk.
“Queer name that, for a yacht. If I wasn’t positive that I had not
mentioned my niece’s name to you, I would swear that you
christened your boat since I began talking to you. However, I will
have to go back to the house for a while, as I left Diana’s picture at
home and Jones wants to make a cut of it for tomorrow’s Leader. I’ll
be back soon and will show it to you before I take it down.”
The senior partner left the office and Andrews laughed loud and
long. “Positive that he hadn’t mentioned the young lady’s name to
me, was he? Oh, that reminds me that I’ll have to get the name on
the yacht changed.” He reached for the ’phone and after getting into
communication with the man that took care of the boat for him, he
said, “Say, strike off the name and put on Diana.”
Andrews had barely resumed work when Harris came in. “Hello,
old man,” he said in response to Andrews’ greeting, “I dreamed
about you last night.”
“The dickens you did,” replied Andrews, “I dreamed about you.”
“This is getting interesting. What did you dream?”
“I dreamed that I saw the most beautiful woman imaginable
coming toward me with outstretched arms. Just as I was about to
touch her she disappeared, and in her stead, I saw you. You had a
hard, cynical sneer upon your face and you said to me, ‘She is
beautiful, but is she good?’ Yes, she is beautiful, but she is not
good.”
“By Jove, Andrews, my dream was almost exactly like yours. What
can it mean?”
Walter shook his head. “I don’t know,” he said; “but I wish you
hadn’t made such a fool statement.”
Roberts came in just then, and excusing himself, Harris left the
office.
Walter went over to the old man’s desk and watched him as he
slowly took out a large photograph from a mailing envelope.
Andrews gave one glance at it, then with a shriek he flung the
picture to the floor and sank into a chair pale as a sheet. Mr. Roberts
looked at him in blank amazement.
“I am not feeling well,” he explained as he picked up his hat to go
home.
The picture which his partner had shown him was a duplicate of
the face he had seen in his dreams, and which, without doubt, was
the same which his friend had seen.

III.
The train to Mulford slowed down at the station of the little
seaport town and from one of the parlor cars a young woman
stepped out to the platform.
“She was beautiful.” There was no denying the fact. Even the
most unemotional man would have stared long and hard at the
retreating figure once he caught sight of her face.
Anthony Roberts stepped out from the interior of the station and
kissed his niece impulsively.

“Now then, Harris,” said a voice at his ear, “dare you say that that
beautiful woman is not good?”
Harris turned and saw a young member of the club who had been
present when his challenge had been made. “Hello, George, what
woman do you mean?”
“The one walking with old man Roberts.”
Harris looked in the direction which his friend pointed, then
gripped his arm convulsively.
“What the mischief are you gripping me that way for? If all
women affect you this way no wonder you say that no beautiful
woman is good. But, man, you are pale as a ghost. Are you ill?”
“I am not well. Let’s go to the club.”
When they reached their destination, Harris sought a secluded
corner. “Has she come to follow me up and torment me again?” he
thought. “Poor Walter, if he sees her he’ll try to prove that although
she is beautiful, this—” he swallowed hard—“is a good woman. By
God! I’ll let him alone, let him get severely punished and see if he
won’t change his mind a bit. They said that I was to marry her.”
Silently one by one there came to him scenes of what had seemed
like a year in heaven, and following them, came what he had
thought a miniature Hell on earth.
As if from the throat of some unseen person there came the
word, “I can’t marry you John, let us just be friends.”
“I hate you,” he shouted at the top of his voice.
A waiter ran up to the room. “Did you call, sir?”
“Yes, bring me a whiskey.”
Tossing the glass off at one gulp, Harris left the room.

IV.
As Walter was about to open the door to his private office the
sound of girlish laughter floated over the open transom.
“It must be Diana,” he said. Opening the door he stepped into his
office.
“Good morning, Andrews,” said his partner, “allow me.” He took
Andrews’ arm and led him up to the sofa where the young lady of
his dreams was seated.
Andrews bowed his acknowledgment of the introduction. He could
not trust himself to speak. The room was swimming about him and
he seemed to be enveloped in a hazy mist, out of which a woman’s
voice was saying, “I made bold, Mr. Andrews, to come in and
arrange your office; freshen it up a bit, you understand.”
Andrews pulled himself together and looked about him. The usual
staid office was transformed into a flower garden. Flowers were
banked upon each other in a way which bespoke a practised hand.
Roberts and his niece left Andrews’ office and went to the firm’s
waiting rooms.
“What is the matter with your partner?” Diana asked, “he has
such a far away look in his eyes and he seems to be miles away
from the office.”
“Only lately, my dear, only lately. I believe you have had some
thing to do with it.”
“I, Uncle?” Diana gasped in astonishment, “what do you mean? I
never saw him before.”
“Until I showed him your photograph, Andrews was all that one
could ask, but when he saw your picture, he dropped it as suddenly
as if he were holding a hot coal, gave a shriek, and skipped out of
the office. I had intended to ask him what made him act the way he
did, but it passed my mind.”
“I am going to ask him myself.” And Diana started for Andrew’s
office.
“Diana,” called her uncle. But that young lady kept on until she
had reached Andrews’ room. She knocked twice and receiving no
answer, opened the door and walked in. She found Andrews with his
head down upon his arms on his desk. Gently touching him on the
shoulder she said, “Mr. Andrews!”
Walter started up suddenly. “I beg pardon,” he stammered, “but I
did not sleep at all well last night and now I was almost gone. Can I,
and may I, be of any assistance to you?” His old manner had
returned and he was now the Walter Andrews which his partner had
known all his life.
Diana was astonished at the sudden transition which had taken
place and it was her turn to be at a loss for something to say.
“Uncle said you had a yacht,” she finally began.
“Yes,” he replied, “will you be ready to go out with me this
afternoon?”
“I should be delighted to go.”
They were silent for a moment, then Diana said, “Mr. Andrews, I
heard that when you saw my picture you dropped it and gave a
scream of terror. May I ask why?”
Andrews dropped back into the manner which Diana had first
seen him. In a strained tone of voice he said, “Miss Langdon,
someday, but not now, I hope to be able to tell you the reason for
my astonishing behavior.”
“‘Some day, but not now,’” she quoted; “When will that be?”
“When I have known you better,” he said bluntly. “When may I
call for you?”
“I have changed my mind; I am not going.”
“But you promised,” reminded Andrews.
“I do not care if I did,” she returned with some heat as she rose
and left the room.
“‘She is beautiful, but is she good?’” Andrews unconsciously
murmured. “Oh, confound it, will I never forget that dream?”

V.
Towards afternoon Andrews heard a gentle knock on his door.
“Come in,” he said.
Miss Langdon entered dressed in a sailor suit. “You see,” she
explained, “I just realized that a promise is a promise and so I’ve
come to go yachting with you. Can you go now?”
“Can I go?” asked Andrews. “Just watch me.” And giving his desk
cover a pull, he reached for his hat and said, “I’m ready now.”
“It took you less time to get ready than it took me,” she smiled.
Andrews looked admiringly at her costume but said nothing. The
distance to the pier was not long, and today Andrews found it much
shorter than usual. Given, a bright vivacious girl and a man who
appreciates that kind, and it needs no mathematician to prove that
they will make a congenial couple.
The day was delightful. Just the right amount of wind was
blowing for a sail. They talked pleasantly for some time as the big
yacht skimmed over the water like a great white bird. Then Andrews
said, “Miss Langdon, I have a friend who says that all women are
flirts. Is he right?”
“Really Mr. Andrews, you take me at a disadvantage.”
“How so?”
“Why, you ask me either to laud or condemn myself, and you
know that no man can, on trial, be compelled to give testimony
against himself.”
Andrews laughed. “Let’s change the subject. See that school of
red fish?”
“Yes.”
“Well, if we were in Hawaii and these fish came into the harbor
we might expect to hear of the death of a member of the royal
family. The Hawaiians have a superstition that these fish come to
announce the death of a chief. Are you at all superstitious?”
“Well, I believe that thirteen is an unlucky number.”
“Yes?”
“There were thirteen of us in our club and all but five got married
before the club was a year old.”
“What kind of a club; Browning or Shakespeare?”
“Neither. We had vowed solemn vows that we would not marry
until—” she stopped short.
“Why do you stop?” Andrews asked.
“You men say that women can not keep a secret. I guess that you
are right. I came near giving our club secret away.”
They soon landed, and giving Diana in charge of her uncle, who
was at the dock waiting for them, Andrews went to the club.
“Diana,” said her uncle, “what made you go with Andrews after
you said that you would not?”
“Because,” said that young lady, “because I love—sailing.”

VI.
Andrews met Diana quite frequently during the following days.
Their meeting always awoke in Andrews the question, “Will she
stand the test?”
“I can stand this no longer,” he said one day; “I shall have to
settle the matter at once.” He turned to his telephone and calling up
Miss Langdon, asked her if she cared for a sail.
“I’ll be down directly,” she replied, and she soon appeared. They
boarded the yacht in silence. Neither spoke for a while, then
Andrews broke the silence saying, bluntly, “Diana, I love you; I have
always loved you. Will you be my wife?”
Miss Langdon was silent for a moment, then she asked, “Why did
you act the way you did when you saw my picture?”
“Your answer first,” groaned Andrews.
“I cannot give you my answer today. Come to my uncle’s
tomorrow and I will answer then and there. Let’s go back.”
Knowing that it would be useless to argue with her and make her
give him her answer immediately, Andrews turned the yacht and
started for home.
After landing, he took her to her uncle’s and left her at the gate.
She had not asked him to come in, but he had not noticed the
omission.
“One who has never been accused of trying to make a man love
her, and when she has him in that fix, declare that she only likes him
and hopes that they will always be friends,” kept ringing in his ears.
Certain it was that since she had met him Diana had tried to make
him love her. Would she stand the test?

VII.
Andrews did not come to work the day after. “He ’phoned me that
he would not be down until afternoon,” said Roberts, when Harris
called to see his friend. “He is not feeling well. But, Harris, you have
not met my niece. Come this way.” An urgent message intercepted
him as they went to Andrews’ room, and hearing that his niece and
Harris were old acquaintances, Harris was left to renew his
friendship.
Somehow, Harris had not met the young lady since her arrival at
Mulford. He avoided all parties and gatherings which he knew she
was to attend and once he had gone away just as he reached the
door of a friend’s house, because he caught a glimpse of her as she
talked to Walter Andrews.
Harris stopped at the door. Should he go in or should he meet her
and denounce her and her works? He decided on the latter and
knocked at the office. A low voice bade him enter. Closing the door
he turned and saw the beautiful woman reading a book. Looking her
full in the face he said, “Diana.”
“John!” she exclaimed.
“Yes, it is John. Diana, have you changed your mind?” Somehow
the dreadful words which he had planned to utter failed to come and
instead he realized that he loved her, and loved with his whole heart.
Diana was silent. “Then you still do not love me?” he asked.
“I really do not know,” she replied softly.
Harris started for the door.
“John,” she called.
He left the door and flung himself beside her chair.
“I love you,” she said; “I love, love you.”
It was the same old story, the telling of which has never made it
grow out of fashion. He caught her up and kissed her again and
again.
“Won’t Andrews be glad that I am at last to settle down and
marry the most beautiful woman on earth?” he asked playfully.
“I think not,” she answered.
“You think not? Why?”
“Because yesterday he asked me to marry him.”
“What did you tell him?”
“To call this afternoon.”
“Send for him now; don’t keep the poor fellow in suspense.”
A messager was dispatched and Andrews came looking haggard
and wan.
“Your answer?” he asked.
“Mr. Andrews, I sent for you to tell you that I can not marry you. I
love another man. Can’t we just be friends?”
Andrews sank into a chair. “He was right,” Andrews muttered,
“Harris was right. No beautiful woman is good.” Then springing up
he shouted, “‘Let’s be friends,’ did you say? Never! Henceforth my
greatest enemy shall be a beautiful woman.”
A FATAL EXCURSION
A FATAL EXCURSION
hree is a large school in Honolulu, called the Royal
School. It is so named because at one time only
children of royal blood were allowed to attend it. But
that is another story.
Business with the principal took me up there one day, and, while
waiting for him, I sat and talked with the janitor.
The school is on a small hill and the road near it is quite steep.
Trolley cars run up that road and come down with the speed of
lightning.
“Whew!” I could not help exclaiming as one car in particular shot
past us, “if some day an axle should break, more than one person
would get hurt, and badly too.”
“You bet,” replied the janitor. There was a pause, and then he
said, “Anyhow, I never ride in them cars unless I can’t help it. I hate
anything with wheels.”
I smiled, sympathetically, I thought, but I suppose in his
estimation it was a smile of incredulity for he hastened to say, “I
used to be a locomotive fireman, but since the day that Jim got
killed, I’ve had but little use for anything but my legs.”
Scenting a story, I asked, “How was that?”
He bit off a fresh bite of tobacco and then began:
“As I said before, I used to be a locomotive fireman over on
Hawaii. Good job alright, but I couldn’t stand it after Jim died. Jim
was my friend, and a right good fellow he was. His job was night
watchman on the docks, but his health gave way and the doctor told
him the best thing he could do was to go to ’Frisco.
“My run included Kohala—ever been there?”
I shook my head.
“Well, you don’t know what you have missed then. The scenery is
magnificent. I had often talked with Jim concerning the place, and
he was just crazy to go and see for himself. He never had a chance,
though, because he used to sleep all day and work all night. But
when the doctor ordered him to throw up his job, he came to me
and asked me to try and get him a permit to ride on my train. We
were on a freighter, and didn’t carry passengers, so I went up to the
manager, and told him the circumstances. But the manager was
cross that day and of course he said ‘no’; said he’d quit giving
passes to people. I told that to Jim and he was dreadfully
disappointed; told me he wanted to see the place before he went
back to the States. So I went to my engineer and asked him to take
Jim as a brakeman. At first he refused, but I insisted, and while we
were talking, a kanaka woman came up and said that her Joe
wouldn’t be able to work that trip, as he was sick.
“I jumped up and made the engineer promise to take Jim in his
stead. He said ‘yes,’ and I went to tell Jim that he might go, and to
explain his duties to him. We were to leave at six o’clock Sunday
morning, and I left Jim’s house early so as to let him sleep enough
to get up early the next morning.
“Sunday morning came, and, by Jove! I never saw a more
beautiful morning again. The birds were singing most glorious, and
the sun shining through the heavy dew drops, made them look like
so many diamonds.
“Before you get to Kohala, you have to come to a steep, curved
incline. We always whistled for ‘brakes’ when we got there and I had
explained to Jim that when we’d blow three whistles, he was to
apply the brakes. He said he understood and took his seat on a
brake, one of them circular kind that you turn with your hand, you
know. He sat on the last box car, but there were a whole lot of flat
cars back of him.
“We started off; Jim enjoying the air, and I, happy in thinking that
I had been able to give the poor fellow such pleasure. By and by we
came near that curve and the engineer blew the whistle for brakes.
Before we started, Jim seemed to understand the signals, but now
the cars were coming down that hill faster than I had ever seen
them before.
“‘What’s the matter with that brakeman?’ the engineer asked me.
“‘I dunno,’ I said, ‘unless he’s fallen off.’
“‘Maybe that’s it,’ the engineer told me, ‘when we get to the
bottom of this, we’d better see.’ So when we got to the foot of the
hill, he stopped the engine and we walked back.
“It was at the beginning of the curve that we found Jim. Yes, he
had fallen off. Poor fellow; ten flat cars had gone over him, and
there was mighty little left of him. He had been cutting up some
tobacco for his pipe, and we found his pipe and a plug of tobacco
and his knife lying near him. I’ve got the knife at home now.
“When we got back from Kohala, I packed up and came to
Honolulu. I couldn’t stand any more railroading.
“That’s why, I can’t bear cars of any sort. Do you blame me?”
I couldn’t say that I did.
Transcriber’s Note:
Jargon, dialect, obsolete and alternative spellings were left
unchanged. Misspelled words were corrected. Obvious printing
errors, such as backwards, upside down, or partially printed letters
and punctuation, were corrected. Final stops missing at the end of
sentences and abbreviations were added.
“Mary” changed to “Maria”
*** END OF THE PROJECT GUTENBERG EBOOK CUPID AND THE
LAW ***

Updated editions will replace the previous one—the old editions will
be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States copyright in
these works, so the Foundation (and you!) can copy and distribute it
in the United States without permission and without paying
copyright royalties. Special rules, set forth in the General Terms of
Use part of this license, apply to copying and distributing Project
Gutenberg™ electronic works to protect the PROJECT GUTENBERG™
concept and trademark. Project Gutenberg is a registered trademark,
and may not be used if you charge for an eBook, except by following
the terms of the trademark license, including paying royalties for use
of the Project Gutenberg trademark. If you do not charge anything
for copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such as
creation of derivative works, reports, performances and research.
Project Gutenberg eBooks may be modified and printed and given
away—you may do practically ANYTHING in the United States with
eBooks not protected by U.S. copyright law. Redistribution is subject
to the trademark license, especially commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the free


distribution of electronic works, by using or distributing this work (or
any other work associated in any way with the phrase “Project
Gutenberg”), you agree to comply with all the terms of the Full
Project Gutenberg™ License available with this file or online at
www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand, agree
to and accept all the terms of this license and intellectual property
(trademark/copyright) agreement. If you do not agree to abide by all
the terms of this agreement, you must cease using and return or
destroy all copies of Project Gutenberg™ electronic works in your
possession. If you paid a fee for obtaining a copy of or access to a
Project Gutenberg™ electronic work and you do not agree to be
bound by the terms of this agreement, you may obtain a refund
from the person or entity to whom you paid the fee as set forth in
paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only be


used on or associated in any way with an electronic work by people
who agree to be bound by the terms of this agreement. There are a
few things that you can do with most Project Gutenberg™ electronic
works even without complying with the full terms of this agreement.
See paragraph 1.C below. There are a lot of things you can do with
Project Gutenberg™ electronic works if you follow the terms of this
agreement and help preserve free future access to Project
Gutenberg™ electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright law
in the United States and you are located in the United States, we do
not claim a right to prevent you from copying, distributing,
performing, displaying or creating derivative works based on the
work as long as all references to Project Gutenberg are removed. Of
course, we hope that you will support the Project Gutenberg™
mission of promoting free access to electronic works by freely
sharing Project Gutenberg™ works in compliance with the terms of
this agreement for keeping the Project Gutenberg™ name associated
with the work. You can easily comply with the terms of this
agreement by keeping this work in the same format with its attached
full Project Gutenberg™ License when you share it without charge
with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the
terms of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.

1.E. Unless you have removed all references to Project Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project Gutenberg™
work (any work on which the phrase “Project Gutenberg” appears,
or with which the phrase “Project Gutenberg” is associated) is
accessed, displayed, performed, viewed, copied or distributed:
This eBook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this eBook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is derived


from texts not protected by U.S. copyright law (does not contain a
notice indicating that it is posted with permission of the copyright
holder), the work can be copied and distributed to anyone in the
United States without paying any fees or charges. If you are
redistributing or providing access to a work with the phrase “Project
Gutenberg” associated with or appearing on the work, you must
comply either with the requirements of paragraphs 1.E.1 through
1.E.7 or obtain permission for the use of the work and the Project
Gutenberg™ trademark as set forth in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is posted


with the permission of the copyright holder, your use and distribution
must comply with both paragraphs 1.E.1 through 1.E.7 and any
additional terms imposed by the copyright holder. Additional terms
will be linked to the Project Gutenberg™ License for all works posted
with the permission of the copyright holder found at the beginning
of this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files containing a
part of this work or any other work associated with Project
Gutenberg™.

1.E.5. Do not copy, display, perform, distribute or redistribute this


electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the Project
Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if you
provide access to or distribute copies of a Project Gutenberg™ work
in a format other than “Plain Vanilla ASCII” or other format used in
the official version posted on the official Project Gutenberg™ website
(www.gutenberg.org), you must, at no additional cost, fee or
expense to the user, provide a copy, a means of exporting a copy, or
a means of obtaining a copy upon request, of the work in its original
“Plain Vanilla ASCII” or other form. Any alternate format must
include the full Project Gutenberg™ License as specified in
paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™ works
unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or providing


access to or distributing Project Gutenberg™ electronic works
provided that:

• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt
that s/he does not agree to the terms of the full Project
Gutenberg™ License. You must require such a user to return or
destroy all copies of the works possessed in a physical medium
and discontinue all use of and all access to other copies of
Project Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project Gutenberg™


electronic work or group of works on different terms than are set
forth in this agreement, you must obtain permission in writing from
the Project Gutenberg Literary Archive Foundation, the manager of
the Project Gutenberg™ trademark. Contact the Foundation as set
forth in Section 3 below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on, transcribe
and proofread works not protected by U.S. copyright law in creating
the Project Gutenberg™ collection. Despite these efforts, Project
Gutenberg™ electronic works, and the medium on which they may
be stored, may contain “Defects,” such as, but not limited to,
incomplete, inaccurate or corrupt data, transcription errors, a
copyright or other intellectual property infringement, a defective or
damaged disk or other medium, a computer virus, or computer
codes that damage or cannot be read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for


the “Right of Replacement or Refund” described in paragraph 1.F.3,
the Project Gutenberg Literary Archive Foundation, the owner of the
Project Gutenberg™ trademark, and any other party distributing a
Project Gutenberg™ electronic work under this agreement, disclaim
all liability to you for damages, costs and expenses, including legal
fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR
NEGLIGENCE, STRICT LIABILITY, BREACH OF WARRANTY OR
BREACH OF CONTRACT EXCEPT THOSE PROVIDED IN PARAGRAPH
1.F.3. YOU AGREE THAT THE FOUNDATION, THE TRADEMARK
OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL
NOT BE LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT,
CONSEQUENTIAL, PUNITIVE OR INCIDENTAL DAMAGES EVEN IF
YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you


discover a defect in this electronic work within 90 days of receiving
it, you can receive a refund of the money (if any) you paid for it by
sending a written explanation to the person you received the work
from. If you received the work on a physical medium, you must
return the medium with your written explanation. The person or
entity that provided you with the defective work may elect to provide
a replacement copy in lieu of a refund. If you received the work
electronically, the person or entity providing it to you may choose to
give you a second opportunity to receive the work electronically in
lieu of a refund. If the second copy is also defective, you may
demand a refund in writing without further opportunities to fix the
problem.

1.F.4. Except for the limited right of replacement or refund set forth
in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of damages.
If any disclaimer or limitation set forth in this agreement violates the
law of the state applicable to this agreement, the agreement shall be
interpreted to make the maximum disclaimer or limitation permitted
by the applicable state law. The invalidity or unenforceability of any
provision of this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation,


the trademark owner, any agent or employee of the Foundation,
anyone providing copies of Project Gutenberg™ electronic works in
accordance with this agreement, and any volunteers associated with
the production, promotion and distribution of Project Gutenberg™
electronic works, harmless from all liability, costs and expenses,
including legal fees, that arise directly or indirectly from any of the
following which you do or cause to occur: (a) distribution of this or
any Project Gutenberg™ work, (b) alteration, modification, or
additions or deletions to any Project Gutenberg™ work, and (c) any
Defect you cause.

Section 2. Information about the Mission


of Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new computers.
It exists because of the efforts of hundreds of volunteers and
donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the


assistance they need are critical to reaching Project Gutenberg™’s
goals and ensuring that the Project Gutenberg™ collection will

You might also like