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

(eBook PDF) Introduction to Java Programming and Data Structures, Comprehensive Version, 11th Global Edition download

The document provides information about the 'Introduction to Java Programming and Data Structures, Comprehensive Version, 11th Global Edition' eBook, including download links and descriptions of various related Java programming resources. It outlines the book's organization into five parts covering fundamentals, object-oriented programming, GUI programming, data structures and algorithms, and advanced Java programming. Additionally, it mentions supplementary resources available for students and instructors, including practice tools and video notes.

Uploaded by

nabelvaulxkg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
73 views

(eBook PDF) Introduction to Java Programming and Data Structures, Comprehensive Version, 11th Global Edition download

The document provides information about the 'Introduction to Java Programming and Data Structures, Comprehensive Version, 11th Global Edition' eBook, including download links and descriptions of various related Java programming resources. It outlines the book's organization into five parts covering fundamentals, object-oriented programming, GUI programming, data structures and algorithms, and advanced Java programming. Additionally, it mentions supplementary resources available for students and instructors, including practice tools and video notes.

Uploaded by

nabelvaulxkg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

(eBook PDF) Introduction to Java Programming and

Data Structures, Comprehensive Version, 11th


Global Edition download

https://ebooksecure.com/product/ebook-pdf-introduction-to-java-
programming-and-data-structures-comprehensive-version-11th-
global-edition/

Download full version ebook from https://ebooksecure.com


We believe these products will be a great fit for you. Click
the link to download now, or visit ebooksecure.com
to discover even more!

(eBook PDF) Introduction to JAVA Programming and Data


Structures Comprehensive Version 11

http://ebooksecure.com/product/ebook-pdf-introduction-to-java-
programming-and-data-structures-comprehensive-version-11/

(eBook PDF) Introduction to Java Programming, Brief


Version, Global Edition 11th Edition

http://ebooksecure.com/product/ebook-pdf-introduction-to-java-
programming-brief-version-global-edition-11th-edition/

Introduction to Java Programming, Comprehensive Version


10th edition- eBook PDF

https://ebooksecure.com/download/introduction-to-java-
programming-comprehensive-version-ebook-pdf/

(eBook PDF) Java Foundations: Introduction to Program


Design and Data Structures 5th Edition

http://ebooksecure.com/product/ebook-pdf-java-foundations-
introduction-to-program-design-and-data-structures-5th-edition/
(eBook PDF) Data Structures and Abstractions with Java
4th Global Edition

http://ebooksecure.com/product/ebook-pdf-data-structures-and-
abstractions-with-java-4th-global-edition/

(eBook PDF) Data Structures and Abstractions with Java


4th Edition

http://ebooksecure.com/product/ebook-pdf-data-structures-and-
abstractions-with-java-4th-edition/

Data Structures and Abstractions with Java 5th Edition


(eBook PDF)

http://ebooksecure.com/product/data-structures-and-abstractions-
with-java-5th-edition-ebook-pdf/

(eBook PDF) Data Structures and Other Objects Using


Java 4th Edition

http://ebooksecure.com/product/ebook-pdf-data-structures-and-
other-objects-using-java-4th-edition/

(eBook PDF) Data Structures and Problem Solving Using


Java 4th Edition

http://ebooksecure.com/product/ebook-pdf-data-structures-and-
problem-solving-using-java-4th-edition/
6 Preface

Part I: Fundamentals of Part II: Object-Oriented Part III: GUI Programming Part IV: Data Structures and Part V: Advanced Java
Programming Programming Algorithms Ch 16 Programming
Chapter 1 Introduction to Chapter 9 Objects and Classes Chapter 14 JavaFX Basics Ch 7 Chapter 18 Recursion Chapter 32 Multithreading and
Computers, Programs, and Parallel Programming
Java
Chapter 10 Thinking in Objects Chapter 15 Event-Driven Ch 13 Chapter 19 Generics
Programming and Chapter 33 Networking
Chapter 2 Elementary Animations
Chapter 11 Inheritance and Chapter 20 Lists, Stacks, Queues,
Programming
Polymorphism and Priority Queues Chapter 34 Java Database
Chapter 16 JavaFX Controls Programming
Chapter 3 Selections and Multimedia
Chapter 12 Exception Chapter 21 Sets and Maps
Handling and Text I/O Chapter 35 Advanced Database
Chapter 4 Mathematical Chapter 31 Advanced JavaFX Programming
Chapter 22 Developping
Functions, Characters, Chapter 13 Abstract Classes and FXML Efficient Algorithms
and Strings and Interfaces Chapter 36 Internationalization
Chapter 23 Sorting
Chapter 5 Loops Chapter 17 Binary I/O Chapter 37 Servlets
Chapter 24 Implementing Lists,
Chapter 6 Methods Stacks, Queues, and Priority Chapter 38 JavaServer Pages
Queues

Chapter 7 Single-Dimensional Chapter 39 JavaServer Faces


Arrays Chapter 25 Binary Search Trees
Chapter 40 RMI
Note: Chapters 1–18 are in the
Chapter 8 Multidimensional Chapter 26 AVL Trees
brief version of this book.
Arrays Chapter 41 Web Services
Note: Chapters 1–30 are in the Chapter 27 Hashing
comprehensive version.

Note: Chapters 31–44 are bonus Chapter 28 Graphs and


chapters available from the Applications
Companion Website.

Chapter 29 Weighted Graphs


and Applications

Chapter 30 Aggregate Operations


and Collection Streams

Chapter 42 2-4 Trees and B-


Trees

Chapter 43 Red-Black Trees Ch 9 Chapter 44 Testing Using JUnit


Preface  7

Organization of the Book


The chapters can be grouped into five parts that, taken together, form a comprehensive introduc-
tion to Java programming, data structures and algorithms, and database and Web programming.
Because knowledge is cumulative, the early chapters provide the conceptual basis for under-
standing programming and guide students through simple examples and exercises; subsequent
chapters progressively present Java programming in detail, culminating with the development
of comprehensive Java applications. The appendixes contain a mixed bag of topics, including an
introduction to number systems, bitwise operations, regular expressions, and enumerated types.

Part I: Fundamentals of Programming (Chapters 1–8)


The first part of the book is a stepping stone, preparing you to embark on the journey of learning
Java. You will begin to learn about Java (Chapter 1) and fundamental programming t­echniques
with primitive data types, variables, constants, assignments, expressions, and operators (­Chapter 2),
selection statements (Chapter 3), mathematical functions, characters, and strings (Chapter 4), loops
(Chapter 5), methods (Chapter 6), and arrays (Chapters 7–8). After ­Chapter 7, you can jump to
Chapter 18 to learn how to write recursive methods for solving inherently recursive problems.

Part II: Object-Oriented Programming (Chapters 9–13, and 17)


This part introduces object-oriented programming. Java is an object-oriented programming
language that uses abstraction, encapsulation, inheritance, and polymorphism to provide
great flexibility, modularity, and reusability in developing software. You will learn program-
ming with objects and classes (Chapters 9–10), class inheritance (Chapter 11), polymorphism
(­Chapter 11), exception handling (Chapter 12), abstract classes (Chapter 13), and interfaces
(Chapter 13). Text I/O is introduced in Chapter 12 and binary I/O is discussed in Chapter 17.

Part III: GUI Programming (Chapters 14–16 and Bonus Chapter 31)
JavaFX is a new framework for developing Java GUI programs. It is not only useful for
developing GUI programs, but also an excellent pedagogical tool for learning object-oriented
programming. This part introduces Java GUI programming using JavaFX in Chapters 14–16.
Major topics include GUI basics (Chapter 14), container panes (Chapter 14), drawing shapes
(Chapter 14), event-driven programming (Chapter 15), animations (Chapter 15), and GUI
­controls (Chapter 16), and playing audio and video (Chapter 16). You will learn the a­ rchitecture
of JavaFX GUI programming and use the controls, shapes, panes, image, and video to develop
useful applications. Chapter 31 covers advanced features in JavaFX.

Part IV: Data Structures and Algorithms (Chapters 18–30 and Bonus Chapters 42–43)
This part covers the main subjects in a typical data structures and algorithms course. Chapter 18
introduces recursion to write methods for solving inherently recursive problems. Chapter 19 presents
how generics can improve software reliability. Chapters 20 and 21 introduce the Java Collection
Framework, which defines a set of useful API for data structures. Chapter 22 discusses measur-
ing algorithm efficiency in order to choose an appropriate algorithm for applications. Chapter 23
describes classic sorting algorithms. You will learn how to implement several classic data struc-
tures lists, queues, and priority queues in Chapter 24. Chapters 25 and 26 introduce binary search
trees and AVL trees. Chapter 27 presents hashing and implementing maps and sets using hashing.
Chapters 28 and 29 introduce graph applications. Chapter 30 introduces aggregate operations for
collection streams. The 2-4 trees, B-trees, and red-black trees are covered in Bonus Chapters 42–43.

Part V: Advanced Java Programming (Chapters 32-41, 44)


This part of the book is devoted to advanced Java programming. Chapter 32 treats the use of
multithreading to make programs more responsive and interactive and introduces parallel pro-
gramming. Chapter 33 discusses how to write programs that talk with each other from different
8 Preface
hosts over the Internet. Chapter 34 introduces the use of Java to develop database projects.
Chapter 35 delves into advanced Java database programming. Chapter 36 covers the use of
internationalization support to develop projects for international audiences. Chapters 37 and
38 introduce how to use Java servlets and JavaServer Pages to generate dynamic content from
Web servers. Chapter 39 introduces modern Web application development using JavaServer
Faces. Chapter 40 introduces remote method invocation and Chapter 41 discusses Web ser-
vices. Chapter 44 introduces testing Java programs using JUnit.

Appendixes
This part of the book covers a mixed bag of topics. Appendix A lists Java keywords. ­Appendix B
gives tables of ASCII characters and their associated codes in decimal and in hex. Appen-
dix C shows the operator precedence. Appendix D summarizes Java modifiers and their usage.
Appendix E discusses special floating-point values. Appendix F introduces number systems and
conversions among binary, decimal, and hex numbers. Finally, Appendix G introduces bitwise
operations. Appendix H introduces regular expressions. Appendix I covers enumerated types.

Java Development Tools


You can use a text editor, such as the Windows Notepad or WordPad, to create Java programs
and to compile and run the programs from the command window. You can also use a Java
development tool, such as NetBeans or Eclipse. These tools support an integrated develop-
ment environment (IDE) for developing Java programs quickly. Editing, compiling, building,
executing, and debugging programs are integrated in one graphical user interface. Using these
tools effectively can greatly increase your programming productivity. NetBeans and Eclipse
IDE tutorials are easy to use if you follow the tutorials. Tutorials on NetBeans and Eclipse can be found in
the supplements on the Companion Website www.pearsonglobaleditions.com/Liang.

Student Resources
The Companion Website (www.pearsonglobaleditions.com/Liang) contains the following
resources:
■■ Answers to CheckPoint questions
■■ Solutions to majority of even-numbered programming exercises
■■ Source code for the examples in the book
■■ Interactive quiz (organized by sections for each chapter)
■■ Supplements
■■ Debugging tips
■■ Video notes
■■ Algorithm animations

Supplements
The text covers the essential subjects. The supplements extend the text to introduce additional
topics that might be of interest to readers. The supplements are available from the Companion
Website.
Preface  9

Instructor Resources
The Companion Website, accessible from www.pearsonglobaleditions.com/Liang, contains the
following resources:
■■ Microsoft PowerPoint slides with interactive buttons to view full-color, syntax-highlighted
source code and to run programs without leaving the slides.
■■ Solutions to a majority of odd-numbered programming exercises.
■■ More than 200 additional programming exercises and 300 quizzes organized by ­chapters.
These exercises and quizzes are available only to the instructors. Solutions to these
­exercises and quizzes are provided.
■■ Web-based quiz generator. (Instructors can choose chapters to generate quizzes from a
large database of more than two thousand questions.)
■■ Sample exams. Most exams have four parts:
■■ Multiple-choice questions or short-answer questions
■■ Correct programming errors
■■ Trace programs
■■ Write programs
■■ Sample exams with ABET course assessment.
■■ Projects. In general, each project gives a description and asks students to analyze, design,
and implement the project.
Some readers have requested the materials from the Instructor Resource Center. Please
understand that these are for instructors only. Such requests will not be answered.

Online Practice and Assessment


with MyProgrammingLab
MyProgrammingLab helps students fully grasp the logic, semantics, and syntax of program-
ming. Through practice exercises and immediate, personalized feedback, MyProgrammingLab
improves the programming competence of beginning students who often struggle with the
basic concepts and paradigms of popular high-level programming languages.
A self-study and homework tool, a MyProgrammingLab course consists of hundreds of small
practice problems organized around the structure of this textbook. For students, the system auto-
matically detects errors in the logic and syntax of their code submissions and offers targeted hints
that enable students to figure out what went wrong—and why. For instructors, a comprehensive
gradebook tracks correct and incorrect answers and stores the code inputted by students for review.
MyProgrammingLab is offered to users of this book in partnership with Turing’s Craft, the
makers of the CodeLab interactive programming exercise system. For a full demonstration,
to see feedback from instructors and students, or to get started using MyProgrammingLab in
your course, visit www.myprogramminglab.com.

Video Notes
We are excited about the new Video Notes feature that is found in this new edition. These VideoNote

videos provide additional help by presenting examples of key topics and showing how
to solve problems completely from design through coding. Video Notes are available from
www.pearsonglobaleditions.com/Liang.
10 Preface

Algorithm Animations
Animation We have provided numerous animations for algorithms. These are valuable pedagogical tools
to demonstrate how algorithms work. Algorithm animations can be accessed from the Com-
panion Website.

Acknowledgments
I would like to thank Armstrong State University for enabling me to teach what I write and for
supporting me in writing what I teach. Teaching is the source of inspiration for continuing to
improve the book. I am grateful to the instructors and students who have offered comments,
suggestions, corrections, and praise. My special thanks go to Stefan Andrei of Lamar Univer-
sity and William Bahn of University of Colorado Colorado Springs for their help to improve
the data structures part of this book.
This book has been greatly enhanced thanks to outstanding reviews for this and previous edi-
tions. The reviewers are: Elizabeth Adams (James Madison University), Syed Ahmed (North
­Georgia College and State University), Omar Aldawud (Illinois Institute of Technology), Ste-
fan Andrei (Lamar University), Yang Ang (University of Wollongong, Australia), Kevin Bierre
(Rochester Institute of Technology), Aaron Braskin (Mira Costa High School), David Champion
(DeVry Institute), James Chegwidden (Tarrant County College), Anup Dargar (University of North
Dakota), Daryl Detrick (Warren Hills Regional High School), Charles Dierbach (Towson Univer-
sity), Frank Ducrest (University of Louisiana at Lafayette), Erica Eddy (University of Wisconsin at
Parkside), Summer Ehresman (Center Grove High School), Deena Engel (New York University),
Henry A. Etlinger (Rochester Institute of Technology), James Ten Eyck (Marist College), Myers
Foreman (Lamar University), Olac Fuentes (University of Texas at El Paso), Edward F. Gehringer
(North Carolina State University), Harold Grossman (Clemson University), Barbara Guillot (Loui-
siana State University), Stuart Hansen (University of Wisconsin, Parkside), Dan Harvey (Southern
Oregon University), Ron Hofman (Red River College, Canada), Stephen Hughes (Roanoke Col-
lege), Vladan Jovanovic (Georgia Southern University), Deborah Kabura Kariuki (Stony Point
High School), Edwin Kay (Lehigh University), Larry King (University of Texas at Dallas), Nana
Kofi (Langara College, Canada), George Koutsogiannakis (Illinois Institute of Technology), Roger
Kraft (Purdue University at Calumet), Norman Krumpe (Miami University), Hong Lin (DeVry
Institute), Dan Lipsa (Armstrong State University), James Madison (Rensselaer Polytechnic Insti-
tute), Frank Malinowski (Darton College), Tim Margush (University of Akron), Debbie Masada
(Sun Microsystems), Blayne Mayfield (Oklahoma State University), John McGrath (J.P. McGrath
Consulting), Hugh McGuire (Grand Valley State), Shyamal Mitra (University of Texas at Austin),
Michel Mitri (James Madison University), Kenrick Mock (University of Alaska Anchorage), Frank
Murgolo (California State University, Long Beach), Jun Ni (University of Iowa), Benjamin N ­ ystuen
(University of Colorado at Colorado Springs), Maureen Opkins (CA State University, Long Beach),
Gavin Osborne (University of Saskatchewan), Kevin Parker (Idaho State University), Dale Par-
son (Kutztown University), Mark Pendergast (Florida Gulf Coast University), Richard Povinelli
(Marquette University), Roger Priebe (University of Texas at Austin), Mary Ann Pumphrey (De
Anza Junior College), Pat Roth (Southern Polytechnic State University), Amr Sabry (Indiana Uni-
versity), Ben Setzer (Kennesaw State University), Carolyn Schauble (Colorado State University),
David Scuse (University of Manitoba), Ashraf Shirani (San Jose State University), Daniel Spiegel
(Kutztown University), Joslyn A. Smith (Florida Atlantic University), Lixin Tao (Pace University),
Ronald F. Taylor (Wright State University), Russ Tront (Simon Fraser University), Deborah ­Trytten
(University of Oklahoma), Michael Verdicchio (Citadel), Kent Vidrine (George Washington Uni-
versity), and Bahram Zartoshty (California State University at Northridge).
It is a great pleasure, honor, and privilege to work with Pearson. I would like to thank Tracy
Johnson and her colleagues Marcia Horton, Demetrius Hall, Yvonne Vannatta, Kristy Alaura,
Carole Snyder, Scott Disanno, Bob Engelhardt, Shylaja Gattupalli, and their colleagues for
organizing, producing, and promoting this project.
As always, I am indebted to my wife, Samantha, for her love, support, and encouragement.
Preface  11

Acknowledgments for the Global Edition


Pearson would like to thank and acknowledge Yvan Maillot (Univresite Haute-Alsace) and
Steven Yuwono (National ­University of Singapore) for contributing to this Global Edition,
and Arif Ahmed (National Institute of Technology, ­Silchar), Annette Bieniusa (University of
Kaiserslautern), Shaligram Prajapat (Devi Ahilya Vishwavidyalaya, Indore), and Ram Gopal
Raj (University of Malaya) for reviewing this Global Edition.
CONTENTS
Chapter 1 I ntroduction to Computers,
­Programs, and Java™ 23
1.1 Introduction 24
1.2 What Is a Computer? 24
1.3 Programming Languages 29
1.4 Operating Systems 31
1.5 Java, the World Wide Web, and Beyond 32
1.6 The Java Language Specification, API, JDK,
JRE, and IDE 33
1.7 A Simple Java Program 34
1.8 Creating, Compiling, and Executing a Java Program 37
1.9 Programming Style and Documentation 40
1.10 Programming Errors 42
1.11 Developing Java Programs Using NetBeans 45
1.12 Developing Java Programs Using Eclipse 47

Chapter 2 Elementary Programming 55


2.1 Introduction 56
2.2 Writing a Simple Program 56
2.3 Reading Input from the Console 59
2.4 Identifiers 62
2.5 Variables 62
2.6 Assignment Statements and Assignment Expressions 64
2.7 Named Constants 65
2.8 Naming Conventions 66
2.9 Numeric Data Types and Operations 67
2.10 Numeric Literals 70
2.11 Evaluating Expressions and Operator Precedence 72
2.12 Case Study: Displaying the Current Time 74
2.13 Augmented Assignment Operators 76
2.14 Increment and Decrement Operators 77
2.15 Numeric Type Conversions 79
2.16 Software Development Process 81
2.17 Case Study: Counting Monetary Units 85
2.18 Common Errors and Pitfalls 87

Chapter 3 Selections 97
3.1 Introduction 98
3.2 boolean Data Type 98
3.3 if Statements 100
3.4 Two-Way if-else Statements 102
3.5 Nested if and Multi-Way if-else Statements 103
3.6 Common Errors and Pitfalls 105
3.7 Generating Random Numbers 109
3.8 Case Study: Computing Body Mass Index 111
3.9 Case Study: Computing Taxes 112
3.10 Logical Operators 115
3.11 Case Study: Determining Leap Year 119
3.12 Case Study: Lottery 120
3.13 switch Statements 122
12
Contents  13
3.14 Conditional Operators 125
3.15 Operator Precedence and Associativity 126
3.16 Debugging 128

Chapter 4 Mathematical Functions,


Characters, and Strings 141
4.1 Introduction 142
4.2 Common Mathematical Functions 142
4.3 Character Data Type and Operations 147
4.4 The String Type 152
4.5 Case Studies 161
4.6 Formatting Console Output 167

Chapter 5 Loops 181


5.1 Introduction 182
5.2 The while Loop 182
5.3 Case Study: Guessing Numbers 185
5.4 Loop Design Strategies 188
5.5 Controlling a Loop with User Confirmation or a Sentinel Value 190
5.6 The do-while Loop 192
5.7 The for Loop 195
5.8 Which Loop to Use? 198
5.9 Nested Loops 200
5.10 Minimizing Numeric Errors 202
5.11 Case Studies 204
5.12 Keywords break and continue 208
5.13 Case Study: Checking Palindromes 211
5.14 Case Study: Displaying Prime Numbers 213

Chapter 6 Methods 227


6.1 Introduction 228
6.2 Defining a Method 228
6.3 Calling a Method 230
6.4 void vs. Value-Returning Methods 233
6.5 Passing Parameters by Values 236
6.6 Modularizing Code 239
6.7 Case Study: Converting Hexadecimals to Decimals 241
6.8 Overloading Methods 243
6.9 The Scope of Variables 246
6.10 Case Study: Generating Random Characters 247
6.11 Method Abstraction and Stepwise Refinement 249

Chapter 7 Single-Dimensional Arrays 269


7.1 Introduction 270
7.2 Array Basics 270
7.3 Case Study: Analyzing Numbers 277
7.4 Case Study: Deck of Cards 278
7.5 Copying Arrays 280
7.6 Passing Arrays to Methods 281
7.7 Returning an Array from a Method 284
7.8 Case Study: Counting the Occurrences of Each Letter 285
7.9 Variable-Length Argument Lists 288
7.10 Searching Arrays 289
7.11 Sorting Arrays 293
14 Contents
7.12 The Arrays Class 294
7.13 Command-Line Arguments 296

Chapter 8 Multidimensional Arrays 311


8.1 Introduction 312
8.2 Two-Dimensional Array Basics 312
8.3 Processing Two-Dimensional Arrays 315
8.4 Passing Two-Dimensional Arrays to Methods 317
8.5 Case Study: Grading a Multiple-Choice Test 318
8.6 Case Study: Finding the Closest Pair 320
8.7 Case Study: Sudoku 322
8.8 Multidimensional Arrays 325

Chapter 9 Objects and Classes 345


9.1 Introduction 346
9.2 Defining Classes for Objects 346
9.3 Example: Defining Classes and Creating Objects 348
9.4 Constructing Objects Using Constructors 353
9.5 Accessing Objects via Reference Variables 354
9.6 Using Classes from the Java Library 358
9.7 Static Variables, Constants, and Methods 361
9.8 Visibility Modifiers 366
9.9 Data Field Encapsulation 368
9.10 Passing Objects to Methods 371
9.11 Array of Objects 375
9.12 Immutable Objects and Classes 377
9.13 The Scope of Variables 379
9.14 The this Reference 380

Chapter 10 Object-Oriented Thinking 389


10.1 Introduction 390
10.2 Class Abstraction and Encapsulation 390
10.3 Thinking in Objects 394
10.4 Class Relationships 397
10.5 Case Study: Designing the Course Class 400
10.6 Case Study: Designing a Class for Stacks 402
10.7 Processing Primitive Data Type Values as Objects 404
10.8 Automatic Conversion between Primitive Types
and Wrapper Class Types 407
10.9 The BigInteger and BigDecimal Classes 408
10.10 The String Class 410
10.11 The StringBuilder and StringBuffer Classes 416

Chapter 11 Inheritance and


Polymorphism 433
11.1 Introduction 434
11.2 Superclasses and Subclasses 434
11.3 Using the super Keyword 440
11.4 Overriding Methods 443
11.5 Overriding vs. Overloading 444
11.6 The Object Class and Its toString() Method 446
11.7 Polymorphism 447
11.8 Dynamic Binding 447
11.9 Casting Objects and the instanceof Operator 451
11.10 The Object’s equals Method 455
Contents  15
11.11 The ArrayList Class 456
11.12 Useful Methods for Lists 462
11.13 Case Study: A Custom Stack Class 463
11.14 The protected Data and Methods 464
11.15 Preventing Extending and Overriding 467

Chapter 12 Exception Handling


and Text I/O 475
12.1 Introduction 476
12.2 Exception-Handling Overview 476
12.3 Exception Types 481
12.4 More on Exception Handling 484
12.5 The finally Clause 492
12.6 When to Use Exceptions 493
12.7 Rethrowing Exceptions 494
12.8 Chained Exceptions 495
12.9 Defining Custom Exception Classes 496
12.10 The File Class 499
12.11 File Input and Output 502
12.12 Reading Data from the Web 508
12.13 Case Study: Web Crawler 510

Chapter 13 Abstract Classes and Interfaces 521


13.1 Introduction 522
13.2 Abstract Classes 522
13.3 Case Study: the Abstract Number Class 527
13.4 Case Study: Calendar and GregorianCalendar 529
13.5 Interfaces 532
13.6 The Comparable Interface 535
13.7 The Cloneable Interface 540
13.8 Interfaces vs. Abstract Classes 545
13.9 Case Study: The Rational Class 548
13.10 Class-Design Guidelines 553

Chapter 14 JavaFX Basics 563


14.1 Introduction 564
14.2 JavaFX vs Swing and AWT 564
14.3 The Basic Structure of a JavaFX Program 564
14.4 Panes, Groups, UI Controls, and Shapes 567
14.5 Property Binding 570
14.6 Common Properties and Methods for Nodes 573
14.7 The Color Class 575
14.8 The Font Class 576
14.9 The Image and ImageView Classes 578
14.10 Layout Panes and Groups 580
14.11 Shapes 589
14.12 Case Study: The ClockPane Class 602

Chapter 15 Event-Driven Programming


and Animations 615
15.1 Introduction 616
15.2 Events and Event Sources 618
15.3 Registering Handlers and Handling Events 619
15.4 Inner Classes 623
15.5 Anonymous Inner Class Handlers 624
16 Contents
15.6 Simplifying Event Handling Using Lambda Expressions 627
15.7 Case Study: Loan Calculator 631
15.8 Mouse Events 633
15.9 Key Events 635
15.10 Listeners for Observable Objects 638
15.11 Animation 640
15.12 Case Study: Bouncing Ball 648
15.13 Case Study: US Map 652

Chapter 16 JavaFX UI Controls


and Multimedia 665
16.1 Introduction 666
16.2 Labeled and Label 666
16.3 Button 668
16.4 CheckBox 670
16.5 RadioButton 673
16.6 TextField 676
16.7 TextArea 677
16.8 ComboBox 681
16.9 ListView 684
16.10 ScrollBar 687
16.11 Slider 690
16.12 Case Study: Developing a Tic-Tac-Toe Game 693
16.13 Video and Audio 698
16.14 Case Study: National Flags and Anthems 701

Chapter 17 Binary I/O 713


17.1 Introduction 714
17.2 How Is Text I/O Handled in Java? 714
17.3 Text I/O vs. Binary I/O 715
17.4 Binary I/O Classes 716
17.5 Case Study: Copying Files 726
17.6 Object I/O 728
17.7 Random-Access Files 733

Chapter 18 Recursion 741


18.1 Introduction 742
18.2 Case Study: Computing Factorials 742
18.3 Case Study: Computing Fibonacci
Numbers 745
18.4 Problem Solving Using Recursion 748
18.5 Recursive Helper Methods 750
18.6 Case Study: Finding the Directory Size 753
18.7 Case Study: Tower of Hanoi 755
18.8 Case Study: Fractals 758
18.9 Recursion vs. Iteration 762
18.10 Tail Recursion 762

Chapter 19 Generics 773


19.1 Introduction 774
19.2 Motivations and Benefits 774
19.3 Defining Generic Classes and Interfaces 776
19.4 Generic Methods 778
19.5 Case Study: Sorting an Array of Objects 780
Contents  17
19.6 Raw Types and Backward Compatibility 782
19.7 Wildcard Generic Types 783
19.8 Erasure and Restrictions on Generics 786
19.9 Case Study: Generic Matrix Class 788

Chapter 20 L
 ists, Stacks, Queues, and
Priority Queues 797
20.1 Introduction 798
20.2 Collections 798
20.3 Iterators 802
20.4 Using the forEach Method 803
20.5 Lists 804
20.6 The Comparator Interface 809
20.7 Static Methods for Lists and Collections 813
20.8 Case Study: Bouncing Balls 816
20.9 Vector and Stack Classes 820
20.10 Queues and Priority Queues 821
20.11 Case Study: Evaluating Expressions 825

Chapter 21 Sets and Maps 837


21.1 Introduction 838
21.2 Sets 838
21.3 Comparing the Performance of Sets and Lists 846
21.4 Case Study: Counting Keywords 849
21.5 Maps 850
21.6 Case Study: Occurrences of Words 855
21.7 Singleton and Unmodifiable Collections and Maps 857

Chapter 22 Developing Efficient


Algorithms 861
22.1 Introduction 862
22.2 Measuring Algorithm Efficiency Using Big O Notation 862
22.3 Examples: Determining Big O 864
22.4 Analyzing Algorithm Time Complexity 868
22.5 Finding Fibonacci Numbers Using Dynamic
Programming 871
22.6 Finding Greatest Common Divisors Using Euclid’s
Algorithm 873
22.7 Efficient Algorithms for Finding Prime Numbers 877
22.8 Finding the Closest Pair of Points Using
Divide-and-Conquer 883
22.9 Solving the Eight Queens Problem Using Backtracking 886
22.10 Computational Geometry: Finding a Convex Hull 889

Chapter 23 Sorting 903


23.1 Introduction 904
23.2 Insertion Sort 904
23.3 Bubble Sort 906
23.4 Merge Sort 909
23.5 Quick Sort 912
23.6 Heap Sort 916
23.7 Bucket and Radix Sorts 923
23.8 External Sort 925
18 Contents

Chapter 24 I mplementing Lists, Stacks,


Queues, and Priority Queues 939
24.1 Introduction 940
24.2 Common Operations for Lists 940
24.3 Array Lists 944
24.4 Linked Lists 951
24.5 Stacks and Queues 965
24.6 Priority Queues 969

Chapter 25 Binary Search Trees 975


25.1 Introduction 976
25.2 Binary Search Trees 976
25.3 Deleting Elements from a BST 989
25.4 Tree Visualization and MVC 995
25.5 Iterators 998
25.6 Case Study: Data Compression 1000

Chapter 26 AVL Trees 1011


26.1 Introduction 1012
26.2 Rebalancing Trees 1012
26.3 Designing Classes for AVL Trees 1015
26.4 Overriding the insert Method 1016
26.5 Implementing Rotations 1017
26.6 Implementing the delete Method 1018
26.7 The AVLTree Class 1018
26.8 Testing the AVLTree Class 1024
26.9 AVL Tree Time Complexity Analysis 1027

Chapter 27 Hashing 1031


27.1 Introduction 1032
27.2 What Is Hashing? 1032
27.3 Hash Functions and Hash Codes 1033
27.4 Handling Collisions Using Open Addressing 1035
27.5 Handling Collisions Using Separate Chaining 1039
27.6 Load Factor and Rehashing 1039
27.7 Implementing a Map Using Hashing 1041
27.8 Implementing Set Using Hashing 1050

Chapter 28 Graphs and Applications 1061


28.1 Introduction 1062
28.2 Basic Graph Terminologies 1063
28.3 Representing Graphs 1064
28.4 Modeling Graphs 1070
28.5 Graph Visualization 1080
28.6 Graph Traversals 1083
28.7 Depth-First Search (DFS) 1084
28.8 Case Study: The Connected Circles Problem 1088
28.9 Breadth-First Search (BFS) 1090
28.10 Case Study: The Nine Tails Problem 1093
Contents  19

Chapter 29 W
 eighted Graphs and
Applications 1107
29.1 Introduction 1108
29.2 Representing Weighted Graphs 1109
29.3 The WeightedGraph Class 1111
29.4 Minimum Spanning Trees 1119
29.5 Finding Shortest Paths 1125
29.6 Case Study: The Weighted Nine Tails Problem 1134

Chapter 30 
Aggregate Operations
for Collection Streams 1145
30.1 Introduction 1146
30.2 Stream Pipelines 1146
30.3 IntStream, LongStream, and DoubleStream 1152
30.4 Parallel Streams 1155
30.5 Stream Reduction Using the reduce Method 1157
30.6 Stream Reduction Using the collect Method 1160
30.7 Grouping Elements Using the groupingby Collector 1163
30.8 Case Studies 1166

Chapter 31–44 are available from the Companion Website at


www.pearsonglobaleditions.com/Liang

Chapter 31 Advanced JavaFX and FXML


Chapter 32 Multithreading and Parallel
Programming
Chapter 33 Networking
Chapter 34 Java Database Programming
Chapter 35 Advanced Java Database Programming
Chapter 36 Internationalization
Chapter 37 Servlets
Chapter 38 JavaServer Pages
Chapter 39 JavaServer Faces
Chapter 40 Remote Method Invocation
Chapter 41 Web Services
Chapter 42 2-4 Trees and B-Trees
Chapter 43 Red-Black Trees
Chapter 44 Testing Using JUnit
20 Contents

Appendixes 1177
Appendix A Java Keywords 1179
Appendix B The ASCII Character Set 1180
Appendix C Operator Precedence Chart 1182
Appendix D Java Modifiers 1184
Appendix E Special Floating-Point Values 1186
Appendix F Number Systems 1187
Appendix G Bitwise Operations 1191
Appendix H Regular Expressions 1192
Appendix I Enumerated Types 1197

Quick Reference 1203


Index 1205
VideoNotes
Locations of VideoNotes
VideoNote
www.pearsonglobaleditions.com/Liang

Chapter 1 Introduction to Computers, Programs, Coupon collector’s problem 304


and Java™ 23 Consecutive four 306
Your first Java program 34
Compile and run a Java program 39 Chapter 8 Multidimensional Arrays 311
NetBeans brief tutorial 45 Find the row with the largest sum 316
Eclipse brief tutorial 47 Grade multiple-choice test 318
Sudoku 322
Chapter 2 Elementary Programming 55 Multiply two matrices 331
Obtain input 59 Even number of 1s 338
Use operators / and % 74
Software development Chapter 9 Objects and Classes 345
process 81 Define classes and objects 346
Compute loan payments 82 Use classes 358
Compute BMI 94 Static vs. instance 361
Data field encapsulation 368
Chapter 3 Selections 97 The this keyword 380
Program addition quiz 99 The Fan class 386
Program subtraction quiz 109
Use multi-way if-else Chapter 10 Object-Oriented Thinking 389
statements 112 The Loan class 391
Sort three integers 132 The BMI class 394
Check point location 134 The StackOfIntegers class 402
Process large numbers 408
Chapter 4 Mathematical Functions, Characters, The String class 410
and Strings 141 The MyPoint class 424
Introduce Math functions 142
Introduce strings and objects 152 Chapter 11 Inheritance and Polymorphism 433
Convert hex to decimal 165 Geometric class hierarchy 434
Compute great circle distance 173 Polymorphism and dynamic
Convert hex to binary 176 binding demo 448
The ArrayList class 456
Chapter 5 Loops 181 The MyStack class 463
Use while loop 182 New Account class 470
Guess a number 185
Multiple subtraction quiz 188 Chapter 12 Exception Handling and Text I/O 475
Use do-while loop 192 Exception-handling advantages 476
Minimize numeric errors 202 Create custom exception classes 496
Display loan schedule 219 Write and read data 502
Sum a series 220 HexFormatException 515

Chapter 6 Methods 227 Chapter 13 Abstract Classes and Interfaces 521


Define/invoke max method 230 Abstract GeometricObject class 522
Use void method 233 Calendar and Gregorian
Modularize code 239 Calendar classes 529
Stepwise refinement 249 The concept of interface 532
Reverse an integer 258 Redesign the Rectangle class 558
Estimate p 261
Chapter 14 JavaFX Basics 563
Chapter 7 Single-Dimensional Arrays 269 Getting started with JavaFX 564
Random shuffling 274 Understand property binding 570
Deck of cards 278 Use Image and ImageView 578
Selection sort 293 Use layout panes 580
Command-line arguments 297 Use shapes 589
21
22 VideoNotes
Display a tic-tac-toe board 608 Tic-Tac-Toe 693
Display a bar chart 610 Use Media, MediaPlayer,
and MediaView 698
Chapter 15 Event-Driven Programming Use radio buttons and text fields 705
and Animations 615 Set fonts 707
Handler and its registration 622
Anonymous handler 625 Chapter 17 Binary I/O 713
Move message using the Copy file 726
mouse 634 Object I/O 728
Animate a rising flag 640 Split a large file 738
Flashing text 646
Simple calculator 656 Chapter 18 Recursion 741
Check mouse-point location 658 Binary search 752
Display a running fan 661 Directory size 753
Fractal (Sierpinski triangle) 758
Chapter 16 JavaFX UI Controls and Multimedia 665 Search a string in a directory 769
Use ListView 684 Recursive tree 772
Use Slider 690

Animations

Chapter 7 Single-Dimensional Arrays 269 radix sort on Companion


linear search animation on Website 924
Companion Website 290
binary search animation on Chapter 24 Implementing Lists, Stacks,
Companion Website 290 Queues, and Priority Queues 939
selection sort animation on list animation on Companion
Companion Website 293 Website 940
stack and queue animation on
Chapter 8 Multidimensional Arrays 311 Companion Website 965
closest-pair animation on
the Companion Website 320 Chapter 25 Binary Search Trees 975
BST animation on
Chapter 22 Developing Efficient Algorithms 861 Companion Website 976
binary search animation on
the Companion Website 868 Chapter 26 AVL Trees 1011
selection sort animation on AVL tree animation on
the Companion Website 868 Companion Website 1012
closest-pair animation on
Companion Website 883 Chapter 27 Hashing 1031
Eight Queens animation on linear probing animation on
the Companion Website 886 Companion Website 1036
convex hull animation on quadratic probing animation on
the Companion Website 889 Companion Website 1037
separate chaining animation on
Chapter 23 Sorting 903 Companion Website 1040
insertion-sort animation on
Companion Website 904 Chapter 28 Graphs and Applications 1061
bubble sort animation on the graph learning tool on
Companion Website 907 Companion Website 1064
merge animation on Companion U.S. Map Search 1086
Website 911 Chapter 29 Weighted Graphs and
partition animation on Applications 1107
Companion Website 915 weighted graph learning tool
heap animation on Companion animation on Companion Website 1108
Website 917
Chapter

1
Introduction
to Computers,
Programs, and Java™
Objectives
■■ To understand computer basics, programs, and operating systems
(§§1.2–1.4).
■■ To describe the relationship between Java and the World Wide Web
(§1.5).
■■ To understand the meaning of Java language specification, API, JDK™,
JRE™, and IDE (§1.6).
■■ To write a simple Java program (§1.7).
■■ To display output on the console (§1.7).
■■ To explain the basic syntax of a Java program (§1.7).
■■ To create, compile, and run Java programs (§1.8).
■■ To use sound Java programming style and document programs properly
(§1.9).
■■ To explain the differences between syntax errors, runtime errors, and
logic errors (§1.10).
■■ To develop Java programs using NetBeans™ (§1.11).
■■ To develop Java programs using Eclipse™ (§1.12).
Another Random Scribd Document
with Unrelated Content
"No."
Kwan Luey looked disappointed.
"Maybe you likee see Big Sam, eh?" he said with an insinuating
air.
"Oh, Big Sam wants to see me, does he?"
"You likee see Big Sam," repeated Kwan Luey with the air of one
stating a recognized fact. "Maybe him show you how pick plenty
good ticket, eh?"
"Does he want to see me to-night?"
"I no know--him no say. Too many p'lice--too many hoodlum--
maybe you no likee," said Kwan Luey, with a judicial view of the
obstacles to an interview with the King of Chinatown.
I decided that I would take the chances, though it was
approaching midnight, when my attention was attracted by the voice
of Parks, and I turned to see him at the desk. My heart sank with
the thought of Mercy's disappointment, when it was buoyed up once
more by the discovery that he was not in custody. Instead of
standing there a prisoner, he was piling little stacks of gold before
the desk sergeant, and I divined that he was producing bail for those
followers who had been so unfortunate as to fall into the hands of
the police. As he shoved the last of the stacks across the desk and
took the receipt that was offered him, he caught sight of me.
"What brings you here?" he cried in surprise.
"I have come, like yourself, on an errand of mercy. But I am the
one who has the greater reason to be surprised." I marveled at his
rashness in daring to enter the prison, and marveled still more that
he was not put under arrest where he stood. Then I reflected that it
was most unlikely that the policemen on guard at the prison had
seen him at the Nob Hill meeting or at the rescue of Merwin; and if
his description was on the books it was not definite enough to serve
for identification.
"By heavens! They call this law!" he cried, waving his hand
around at the prison. "Do you know, sir, that they have set
Baumgartner's bail at five hundred dollars, and threaten to rearrest
him as he sets foot out of prison, if I secure his release with that
sum!"
"Then I think you had better save your five hundred," I replied.
"You can take it coolly, Hampden, but I can't. It makes my blood
boil. If I had my way, I'd be here taking these men out with ax and
sledge, instead of with gold. I'd have done it anyhow if they had had
the courage to arrest Kearney. They didn't dare!" And he looked
threateningly around the prison, and then counted the members of
his band for whom the authorities had accepted bail. "Pass out," he
said to them, and as he brought up the rear of his party, I followed
him. They were of the typical hoodlum class, their insolence curbed
for the moment by the shadow of the prison, and they slouched with
resentful fear from the watchful eyes of the police. One figure
among them stirred a dormant memory, and then, as the band
scattered in the street, I recalled to mind the spy whose gift of an
overcoat had opened the door of the fates. He was gone before I
could speak, and I turned to Parks.
"How did you escape arrest?" I asked.
"Escape!" cried Parks. "I courted arrest, but the coward hounds
of aristocracy had not the courage to lay hands on any of the
leaders. They know as well as I that the wrath of an outraged
people would not leave one stone of the jail upon another, if they
ventured to seize Kearney, or even so humble a person as I."
"To tell you the truth, I came down here expecting to find you in
custody, and to see what I could do toward getting you out. No, you
needn't thank me for it. Give your thanks to a young lady who is
paying you the compliment of more worry than you are worth. I
came to relieve her anxiety--not yours."
Parks halted as we reached the corner of Merchant and Kearny
Streets, and I saw the tense and angry lines soften on his face.
"Hampden, I won't pretend to misunderstand you. You're right.
I'm not worth her worry--nor is any man. I am grateful; but I tell
you, as I tell her, that our private interests, hopes, affections, are
nothing compared with the great cause of the people."
"Well, for her sake, I hope you'll keep out of jail."
Parks took off his hat, and shook his mane with an angry nod.
"A few more days," he cried, "and this cowardly set of time-
servers will be begging my protection instead of threatening my
liberty."
"Are you ready to strike a blow?" I asked with sudden interest.
"Never mind," he said darkly. "We await only the word from our
brethren in the East. You can see the crisis approaching there. The
railroad strikes have spread from the Atlantic to the Missouri. The
frightened bloodsuckers of society are calling out the troops in the
desperate hope of prolonging their hold on the labor and productive
resources of the country. When the hour strikes--"
Parks had gradually raised his voice in oratorical fervor, despite
the nearness of the police headquarters, but at this moment he was
interrupted by a tall, strong-faced man, who seized him by the
shoulder and whispered something in his ear.
"Hampden," said Parks, "I am called. Will you be kind enough to
send word that I am safe? I shall see your friend to-morrow." And
with a nod he plunged into the crowd that blocked Kearny Street
and disappeared.
At the drug store on the corner I scribbled a note that should
set Miss Fillmore's mind at rest, and with some difficulty found a
messenger who would deliver it. Then with misgivings I shouldered
my way through the crowd, crossed the Plaza, and entered
Chinatown.
The echoes of the Nob Hill meeting reverberated here as well as
about the Old City Hall, but with a far different note. In place of the
illuminated streets, the gay lanterns and the open doors of invitation
of other days, there were barred entrances everywhere; the lights,
where seen at all, flickered behind closed shutters, and the darkened
buildings were surrounded with an atmosphere of sullen
watchfulness. There was evident fear that the meeting on the hill
was but the prelude to an attack on Chinatown, and Chinatown was
prepared.
The entrance to Big Sam'e house was closed and barred, like
the other doors of Waverly Place, but lights shone through the
chinks in the shutters, and there were sounds of men stirring
behind; so without hesitation I gave a resounding rap on the panel.
The noises within ceased suddenly, but there was no response to my
summons. I rapped again, and then a third time, before a singsong
voice cried through the door:
"Wha' fo'? What you wan'?"
"I want to see Big Sam," I explained.
"No catch-em Big Sam," returned the voice harshly.
"You tell Big Sam Mr. Hampden here to see him," I cried. "He
send tell me come. You sabby tell him now--right away."
There was a sudden outbreak of Chinese voices in argument
and protest, and then silence followed for so long that I was about
to rap again, when the same voice called through the door:
"How many you come?"
"One man."
There were sounds of a barricade removed, and the door
opened cautiously for a few inches while its guardian reconnoitered.
Reassured by my solitary figure, he stood aside for me to pass.
At the last moment my lagging judgment suggested the folly of
putting myself as a hostage in the hands of the yellow men in such a
time of storm. But it was too late to retreat with honor, and I slipped
through the opening with all the boldness and self-possession I
could assume, and saw the door bolted and barricaded against other
intrusion. I looked narrowly about me.
Within the store that formed the entrance to Big Sam's
establishment were twenty or thirty Chinese, and in the smoky light
of the lamps I could distinguish the expression of suspicion and
hatred that had escaped from behind the "no-sabby" mask of the
coolie. The passions of the meeting on the hill had stirred an
answering passion in the breasts of the yellow man, and I saw that
in this place, at least, he was armed and ready for battle. The band
pretended to take no notice of me, but the running fire of
conversation that followed my entrance told me by its unmistakable
accents that my coming had roused the instincts of combat, as the
sight of the prey rouses the hunting instincts of the tiger.
Without a word a Chinaman beckoned me to follow him, and
with some trepidation I stumbled up the stair in his footsteps. He
stood aside at the entrance to Big Sam's room of state, motioned me
to enter, and as I stepped in, he closed the door behind me.
For a moment I was disturbed to find that I was the only person
in the room, and looked about with curiosity to know whether I was
spied upon from some hidden post of observation. After my
experience on the previous visit, I could not doubt that more than
one hidden entrance led to the room, and I suspected that more
than one pair of eyes watched me from hidden peep-holes. The dark
carved wood of the furniture and walls, and the figures in the
intricately embroidered hangings glowered at me with something of
the repressed hostility of the guards down-stairs. The life and
turmoil of the city from which I had just come seemed already at a
vast distance from that oriental hall, and I could not but reflect how
easy it would be to make certain that I never returned to the
modern San Francisco that seemed now to lie so far away.
With a discretion that would recommend me in the eyes of any
watcher, I took a chair far enough from the desk to avoid the
suspicion of a wish to pry into Big Sam's papers, and surveyed the
apartment as I impatiently awaited the coming of its owner.
Suddenly the voice of Big Sam sounded behind me.
"I am always glad to welcome Mr. Hampden--even when he is
the bearer of bad news."
I had heard no sound of his entry, and turned with a start at his
voice. Then I exclaimed in surprise. Instead of Big Sam, in his
Chinese costume, I saw an American gentleman regarding me with
an impassive face. His light plaid suit was of fashionable cut, and no
detail of costume was wanting. But for the voice, I should have
supposed, at first glance, that another visitor had followed me into
Big Sam's reception-room, and it was only a closer look that
revealed the features of Big Sam himself. A touch of art had
lightened the color of his skin, and only the eyes and cheek-bones
suggested his Asiatic origin.
"I hope it is no bad news that brings me," I said, as Big Sam
advanced to shake my hand. "I think I bring none myself."
Big Sam seated himself behind his desk, looking incongruously
out of place--a modern American as master of an oriental domain.
"In this time of broils and alarms, one's first thought must be of
sudden evil," he said gravely. "You may guess, by my disguise, I
have been observing how your people comport themselves when
they assemble to consider the interests of their race. I have been
much edified."
In his American dress, and with his perfect command of English,
I had no doubt that he might have brushed shoulders with Kearney
himself without rousing suspicion of his nationality.
"It has been an inspiring evening," I replied with a gravity equal
to his own. "I see you have prepared for trouble."
"I am not insensible to the advantages or rights of self-
defense," he said dryly. "But I trust that you have found nothing
incorrect in our attitude--if I may borrow a phrase from your
diplomats. I would be unwilling to take any course objectionable to
the country that is my host--possibly a somewhat unwilling host, if I
may judge by the words I have heard to-night." Big Sam looked at
me with the inscrutable irony of the Orient.
"I can see no ground for complaint," I replied. "I have come to
learn, not to reprove or to warn."
"I am, as ever, at your service."
"I was happy enough to meet our estimable friend Kwan Luey--
under somewhat difficult and depressing circumstances, I may add--
and he was so insistent in his assumption that I wished to see you
that I thought it wise to test his theory before I went to sleep."
The shadow of a smile swept across Big Sam's face.
"Kwan Luey has his moments of divination," he said, and then
fell silent.
"May I inquire what particularly I wished to see you about?" I
asked at last.
Big Sam's eyes studied me keenly.
"I warned you--not so long ago, Mr. Hampden--that strange
events were preparing in your city. May I ask what is now your
opinion on them? I am interested to hear."
"I must congratulate you on the accuracy of your information,
though I am still at a loss to surmise why you should have been
selected for the confidence. And as for the disorders, they are but a
temporary effervescence, which will die away, or be suppressed. But
there is one thing permanent about them. They are a crude
expression of the resolve of our race to hold the continent for itself."
"Crude indeed!" said Big Sam with energy. "And will destroy
itself by its own violence. I have here a paper showing the sentiment
of your people in the Eastern States. It makes a protest against the
policy that would exclude us."
"I shan't begrudge you the pleasure you can get out of that sort
of comment. But I can assure you that race feeling will prevail."
"Over private interest? I believe not. And the private interest of
your governing classes is with the free admission of my people. But
enough of that. Where is your charge--and mine--Moon Ying?"
He threw this question at me as though he hoped to surprise
some admission.
"She is still with Miss Kendrick."
"What arrangements have you made to protect her?"
"Protect her? From what? Are the highbinders so desperate as
to think of attacking Mr. Kendrick's house? I trust you will warn them
that this would be something far more serious than all Kearney's
oratory. It would mean the destruction of Chinatown."
"I understand you," said Big Sam suavely. "I have no doubt that
an attack by the tongs on Mr. Kendrick's house would bring a terrible
reprisal. Fortunately there are few among my people who do not
understand that quite as well as you."
"Nevertheless there is something you fear," I said, as Big Sam
hesitated.
"You must understand, Mr. Hampden, that this girl is a very
desirable piece of property. There is her money value, which is
considerable. And there is the further consideration that the
possession of her would give a tong a certain power and distinction.
The contest has come to be a point of honor--or perhaps you would
say dishonor. At all events the tongs have not ceased to plan to
recover her, and I have information that the Hop Sing Tong has
devised a plan to seize her by force. It would, of course, be suicide
for them to carry out the plan themselves. But what they can not do
themselves can be done by white men. Your race is not more
scrupulous than mine, Mr. Hampden. I have reason to believe that
the Hop Sing Tong has found a gang of white men who are ready,
for a money consideration, to break into Mr. Kendrick's house and
carry off the girl."
This warning struck me with the force of a physical blow. It was
scarcely possible that Big Sam could be mistaken, and I must reckon
on the attack as an imminent danger. And in swift imagination I
could hear the screams of Laura Kendrick and Mercy Fillmore joining
those of Moon Ying, as they struggled in the grasp of ruffians, and
could see the crackling flames as the raiders left destruction behind
them.
"I have had reason to-night to surmise that something was
afoot," I said, "but I did not suspect this." And then I retailed to Big
Sam the story of the visit of the old Chinaman, the attack of the
three raiders of the early morning, and the questioning of the
mysterious tramp.
"The old man is Chung Toy, sometimes known to your people as
'Little John.' He was, you will remember, the custodian of the girl. He
is now in the employ of the Hop Sings. The white men I can suppose
were spies, sent to reconnoiter, though I am puzzled about the
morning raiders."
"Does your information go so far as to suggest when the attack
will be made?"
"No."
"And have you any word of advice?"
"Advice? Yes. I should advise that you return the girl to my
custody. I confess that she would be an embarrassment--"
"You will not be put in any such awkward position," I
interrupted. "I can speak for Miss Kendrick, and say that she will
keep the girl till the conditions are fulfilled."
"Then," said Big Sam composedly, "I leave to your best
judgment the way to meet the danger." And with a bow that
signified the end of the interview, he clapped his hands, and a young
Chinaman appeared to conduct me down the stairs. And as I passed
the sullen guards, and heard the door bolted and barred behind me,
I admired the diplomacy with which Big Sam had washed his hands
of his responsibilities, and left them to me.

CHAPTER XVIII
LITTLE JOHN AS A MAN OF ACTION

Big Sam's warning was enough to drive me once more to the


Kendrick house to make certain that all was secure. I could suppose,
from his words, that he did not expect an immediate attack, yet it
was by no means unlikely that Little John's ruffians would take
advantage of the disorders of the night to make their attack. But all
was quiet in the neighborhood, and Andrews reported nothing more
threatening than a few disorderly hoodlums who had gone shouting
past an hour or two before.
I confided to Andrews the warning of an intended attack, and
directed him to engage six men instead of the two I had previously
ordered.
"I think I can find the right sort," he said. "There's some boys I
used to know up in Nevada when we were holding down some
claims against big odds. Six of 'em would chew up a hundred of
these cigarette-smoking hoods." And he told with keen enjoyment of
the adventurous days of the claim-jumpers, when a man's life and
property depended on his strength and courage and sureness of
aim.
I paced the watch with him till the stars began to pale before
the coming day, and then gladly sought home and bed. My sleep
was troubled with vague, indefinable dreams of coming danger, and
it was late when I rose with the presentiment that a crisis was
approaching.
It was a Sunday morning, yet the apprehensions roused by my
dreams found abundant reinforcement when I was once more astir.
The echoes from the Nob Hill meeting were still to be heard in the
city, rousing apprehension among the orderly. The newspapers
treated it as the sensation of the day, yet, from their comments, I
saw that they had no conception of the real designs that lay behind
the activity of the anti-coolie agitators. Clark reported to me that the
Council of Nine had been in session till long after midnight, and that
the anti-coolie clubs had been ordered to hold daily drills. One of the
two spies who were detailed to keep watch on Peter Bolton came at
noon with the report that Bolton had reached his office before seven
o'clock in the morning, where he had received a visit from Waldorf,
Parks and Reddick, the three most active members of the Council. As
they left Bolton's office, Reddick had been heard to say, "Before the
week ends, we shall be masters of the city." And as a final fillip to
anxiety, I found at my office a tangle-worded letter, which I
recognized as the product of Kwan Luey's pen, that recalled the
warnings I had received from Big Sam.
With this accumulation of mental disturbance, I took my way at
last to the Kendrick house, to lay the tale of impending dangers
before my client, and to give hint to the young ladies of the need for
caution.
On my arrival, I found the house in confusion. There was sound
of excited voices within, and, as I touched the bell, a servant rushed
out and down the steps without taking time to close the door. I
entered without ceremony, and a moment later met Laura Kendrick
coming down the stairs, her face clouded with fear and indignation.
"Oh, I'm so glad you've come!" she said with a gasp of relief,
and the look of fear faded out of her eyes. "We've been scared out
of a year's growth, and it's one of the mercies of Providence that we
haven't lost Moon Ying. It's not often I've wanted to be a policeman,
but I did to-day."
"Well, I'll be your policeman, if you'll only tell me what it's all
about."
"It's a comfort to have you say so, but I'm afraid you're too late.
He must be ever so far away by this time."
"Who is it? What has happened?" I demanded eagerly.
"Somebody tried to steal Moon Ying--that's what has
happened," said Laura Kendrick indignantly.
"Who did it? When? Did they attack the house?" I cried, startled
at the promptness with which my warnings had been fulfilled.
"Come right up-stairs," said Laura, impulsively seizing my arm
and leading me. "You shall hear at first-hand for yourself."
This sudden captivity gave me so pleasant a thrill that for a
moment I forgot Moon Ying and my responsibilities, and betrayed
such inclination to loiter that I was sharply ordered to "walk faster."
So in a minute or two I found myself entering a room where Moon
Ying, with pale and frightened face, leaned back among the pillows
that covered a reclining chair, and Mercy Fillmore, at Moon Ying's
side, looked at us with anxious eyes.
"This is Mr. Hampden, Moon Ying--the man who rescued you
from Chinatown," said Laura. "Tell him what happened to you."
Moon Ying's resources of English were scant at best, and
between fright, excitement and shyness, it took much prompting and
explanation from Laura and Mercy before her story was fairly begun.
But when all the tangled threads were straightened out the tale ran
thus:
Moon Ying had of late spent an hour or two in the middle of the
day, taking the air and the sun, on the lawn behind the house. An
hour before she had been assisted to her sunny corner by Mercy,
who had, after a time, returned to the house. Suddenly the back
gate had opened, and a Chinaman had slipped in.
"How many?" I demanded.
"One--jus' one," replied Moon Ying.
"How him look?"
"Him small man--old man--all same Chung Toy you one time
see," said Moon Ying in her plaintive voice.
The picture of Little John with his wizened face, his white,
horse-hair mustache and his scant chin-whiskers, rose before me.
"Did he come alone?" I asked, incredulous of his boldness in
venturing thus by himself.
"Him say two men come 'longside him, but I no see. Him talk
velly soft--say I come Chinatown, him makee me velly nice dless--
get velly fine house--find me velly good husband. I tell him go 'way,
I too muchee sabby him. One time I thlink him good man--now I
heap sabby him tell big lie--no got nice dless--no got fine house--no
got good husband--I all time stlay Miss Kenlick. Him get velly mad--
him say velly bad thling. Then him say I no go alongside him, two
men come takee me so--" and Moon Ying raised her pretty little
hands and gripped fiercely at the air, with the motion of one
throttling a victim.
"What you do then?"
"I cly velly loud--likee so--" and Moon Ying let out a feminine
screech that caused Laura and Mercy to cover their ears. "Then
Chung Toy catchee me, so--," and she seized her arm roughly,--"put
hand so--," and she covered her mouth with her palm. "I cly one
time again. Miss Kenlick come. Miss Muh See come. One man come.
Chung Toy him lun away."
"Did you see him?" I asked of Laura.
"Indeed I did; and I could have caught him, too, if I hadn't been
such a goose as to be scared into a graven image. But by the time I
came to life he was out of the gate. But it was the same man who
was here last evening; and if he had any one with him, they took
precious good care not to show themselves. He went in such a hurry
that he left behind him a peddler's basket. It had a few silk
handkerchiefs in it. I suppose he was going to make them an
excuse, if he had been stopped on coming in."
"Where were my men? There should have been two of them on
hand to stop such fellows. I must look into this." And the spirit of
judgment rose stern within me.
"Well," said Laura, "there was one of your men here, and the
other was sick, so you needn't look so cross. This one was at the
front of the house, and he ran around to the back at Moon Ying's
scream. When he got there that awful creature was out of the yard,
so I got him to help us carry Moon Ying into the house. Then he
went out the back gate, but by that time there was no heathen in
sight anywhere. But I've sent one of the servants for the police and
the doctor, and I want your miserable Chung Toy put in jail where
he'll be out of mischief." And she gave her head a determined nod,
as though his fate were settled beyond recall.
"I'll have a warrant out before night," I said, with anger tingling
in my nerves, "and he'll be laid by the heels in the City Prison if he
dares show himself on the street."
"I don't think jail is a very good place, even for bad people,"
said Mercy, "for it makes them worse; but I shall feel easier if that
man is locked up. It is too dangerous to have him at large."
"I suppose you don't need any instructions," I said, "but I'll
venture to suggest that Moon Ying had better take the air from an
up-stairs window for a few days."
"I hope we have sense enough to know that much," returned
Laura soberly, "though I don't blame you for thinking we haven't. I
shan't dare let her out of doors unless there's a regiment of soldiers
about the house."
"I'll have a few more men here to-morrow; but you'd better
keep her in till I give the word that all is safe."
Laura Kendrick looked sharply at me.
"You needn't try to hide it," she said. "I see in your face that
there's something more you're afraid of, and you'd better tell it now
rather than later."
"I wasn't intending to conceal it. In fact, I was going to warn
you against letting strange white men into the house. I've had a
warning that leads me to believe that the fellow who was here
asking questions yesterday is one of a gang hired by the highbinders
to recover Moon Ying. They are much more dangerous than Little
John, but if we don't give them a chance they won't hurt us."
Moon Ying had followed our conversation with eager attention;
and though many of the words were beyond her understanding, she
had caught the meaning of what we said.
"Too bad--too velly bad," she said, with sudden resolution
evident in her face. "Bad man come, makee you 'flaid, maybe shoot.
I go 'way, bad man no come."
"Indeed you shan't go away," cried Laura. "There's no place on
earth you could be safe, even if we did let you go."
"I go Big Sam. Him velly big man. No bad man catch-em me in
Big Sam's house. No bad man catch-em you when me-gone."
At these words, Laura impulsively flung her arms about Moon
Ying.
"You dear creature!" she cried. "Nobody shall hurt you here--
and nobody will hurt us, either. My uncle can protect you much
better than Big Sam, and Big Sam himself has said so."
Moon Ying tried to express more fully her fear that her presence
brought danger to the household, but her language was unequal to
her thought, and Laura and Mercy both talked at once to assure her
that they feared nothing, and would refuse to give her up, even
though all the tongs of Chinatown should come in force to demand
her; so Moon Ying at last with a sigh of grateful content said:
"I likee stay--I likee you." And Laura on one side, and Mercy on
the other, twined their arms about her with a laugh that was almost
a sob.
It was a pretty picture of the sisterhood of Occident and Orient,
and I admired it, with something of the feminine emotions raising a
lump in my throat, when I was observed by the lady of the house.
"Go away," she said. "This is no place for men." And in spite of
my remonstrance that I was in perfect harmony with my
surroundings, I was driven forth, and went down-stairs to find
Wharton Kendrick taking a Sunday afternoon nap in his den.
He gave me a sleepy greeting, but roused himself to attention
at my account of the Nob Hill meeting, the midnight session of the
Council of Nine, the morning meeting in Bolton's office, and the
warning from Big Sam.
"Hm-m! Well, put on enough watchmen to see that we don't
wake up to find our throats cut," he said. "I dare say P. Bolton is
egging them on all around to do something for their money. But so
far as the business goes, I think I've got everything shipshape and
ready for storm. The syndicate is strong enough to protect the
market, and the police can handle the Cheap John revolution, and I
don't believe anybody is going to attack the house; so there's
nothing to worry about. But you'd better keep in touch with your
anarchist friends a little closer than you've been doing. If we can get
warning over night of any particular deviltry they are going to start,
it might be worth a hundred thousand dollars. Hallo! what's this?" he
cried as a servant brought him a card. "Show him in." And before I
could escape, General Wilson bustled through the door, his ruddy
face aglow in the frame of his bristling yellow-gray side-whiskers,
and his short stout frame radiating energy at every step.
"Why, God bless my soul! Kendrick--Hampden--I find you with
your heads together like a pair of conspirators in the theater. Hope I
don't interrupt. It does me good, Hampden, to see you youngsters
pulling along in double harness with the war-horses like Kendrick
and me; and you can't find a better one to pull with than Kendrick;
he's the salt of the earth."
I professed myself glad to see the general, and Wharton
Kendrick greeted him jovially.
"I don't believe in doing business on Sunday," said General
Wilson. "In fact, I lost a million-dollar trade with Jim Fisk once,
because I wouldn't sign the contract on the Sabbath, and on Monday
Jim was chasing after something else. But I thought you'd like to
know that I got a telegram from my people about that swamp-land
deal. Here it is, and you see they'll come up to that eight hundred
thousand dollar offer. That's the limit, and it won't last long at that. I
don't like to boast, Kendrick, but I'll tell you that there isn't another
man on the footstool that could have got 'em up to that point--I'm
the only one that could do it; and, by George, I'm astonished at my
own success, the way things are looking in the East with those
confounded railroad strikes and rumors of riot. Now, I want you to
understand that I'm not asking you to take up with the offer to-day,
for of course you remember the Sabbath just as I do. But you can
have a good chance to think it over. You know well enough that
you're going to take the offer, so I'll warn you that I'll drop around in
the morning and get your acceptance."
"Hold on, hold on, Wilson. You're running as wild as a mustang
colt. I'm not so sure about this thing. I've got to have more time to
consider it. I said I'd let you have the land for eight hundred and
fifty thousand, but I believe I'm a fool to let it go for any such figure.
However, I'll let it stand for a couple of days. I've got some affairs
booked for to-morrow that will take all my time. But if you'll come in
on Tuesday with your eight hundred and fifty thousand you can have
the land. After that it'll cost you more."
"Kendrick, I'll wait another day for you, if I have to telegraph
that I've broken a leg. Business, sir, is, next to war, man's most
important pursuit; but even business must give way to the call of
friendship. You'll see me coming into your office on Tuesday
morning, Kendrick, like a conquering hero, ready to receive your
sword--or your pen, which is mightier yet--but at eight hundred
thousand, mind you."
"Come, come, Wilson, you're getting ahead of your horses," said
Kendrick with a laugh. "I'm thinking of getting up a company to
reclaim those lands, and if I conclude to do it, I won't sell for double
the money."
"Talk as long as you like, Kendrick; but I've got a sixth sense
that tells me when a bargain's made, and it never fails me. I can tell,
nine times out of ten, when the other fellow has concluded to take
my figures before he knows it himself, and that gift has saved me a
pretty penny more than once. Why, when the Ohio Midland was
enlarging its Chicago terminal, there was one piece we had to have--
but the story's too long to tell. However, I made a hundred thousand
dollars the best of the bargain by knowing what the other fellow was
going to do before he knew it himself."
Wharton Kendrick gave a hearty laugh at General Wilson's
diplomacy.
"Well, I shall take warning by that and hold out for my hundred
thousand--or, I should say, fifty thousand, as I've given you a price."
"You're getting your extra hundred thousand with the price I'm
offering you," said the general testily, "and I know well enough you'll
not be fool enough to refuse it, especially after such a row as you
had on Nob Hill last night. I hope my New York clients don't hear of
it, or everything will be off. I was there, sir, and of all the howling
mobs I ever saw, this beat anything since the draft riots. Why, sir,
that blatant beast, Kearney, shouted arson and manslaughter, and
another fellow called for the overturn of society, and if it hadn't been
for the police, I believe they would have worked up the crowd to the
point of blood-letting." Then General Wilson went at such length into
the proper methods of handling mobs that I seized upon a favorable
moment to slip out the door.
As I left the boom-boom of General Wilson's voice behind me, I
caught sight of Mercy Fillmore's perplexed and anxious face.
"Oh, I thought you had gone," she said, "but I'm glad you
haven't, for I want to thank you for your thoughtful note of last
night. And now Mr. Parks has sent me word that he is too busy to
come up this afternoon, and I was wondering how I could get a few
lines to him. I am so afraid he is planning something very reckless--
something that will get him into trouble. If I did not fear that he
would be angry, I should go down and speak to him myself."
"If that is all that's worrying you, I'll see that he gets your
letter--that is, if you can give me any idea where he is to be found."
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about testbank and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebooksecure.com

You might also like