0% found this document useful (0 votes)
31 views

Java Programming From Problem Analysis to Program Design 4th Edition D. S. Malik - Download the ebook today and own the complete content

The document provides information about various programming ebooks available for instant download at ebookgate.com, including titles by D.S. Malik and others. It features books on Java and C programming, data structures, and programming design, with links to access each title. The content also includes details about the structure and topics covered in the Java Programming: From Problem Analysis to Program Design, Fourth Edition by D.S. Malik.

Uploaded by

pulockcairus
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
0% found this document useful (0 votes)
31 views

Java Programming From Problem Analysis to Program Design 4th Edition D. S. Malik - Download the ebook today and own the complete content

The document provides information about various programming ebooks available for instant download at ebookgate.com, including titles by D.S. Malik and others. It features books on Java and C programming, data structures, and programming design, with links to access each title. The content also includes details about the structure and topics covered in the Java Programming: From Problem Analysis to Program Design, Fourth Edition by D.S. Malik.

Uploaded by

pulockcairus
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/ 82

Instant Ebook Access, One Click Away – Begin at ebookgate.

com

Java Programming From Problem Analysis to Program


Design 4th Edition D. S. Malik

https://ebookgate.com/product/java-programming-from-problem-
analysis-to-program-design-4th-edition-d-s-malik/

OR CLICK BUTTON

DOWLOAD EBOOK

Get Instant Ebook Downloads – Browse at https://ebookgate.com


Click here to visit ebookgate.com and download ebook now
Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

C Programming From Problem Analysis to Program Design 5th


5th Edition D. S. Malik

https://ebookgate.com/product/c-programming-from-problem-analysis-to-
program-design-5th-5th-edition-d-s-malik/

ebookgate.com

C Programming From Problem Analysis to Program Design 4th


Edition Barbara Doyle

https://ebookgate.com/product/c-programming-from-problem-analysis-to-
program-design-4th-edition-barbara-doyle/

ebookgate.com

C Programming Program Design Including Data Structures 7th


Edition D. S. Malik

https://ebookgate.com/product/c-programming-program-design-including-
data-structures-7th-edition-d-s-malik/

ebookgate.com

C Programming Program Design Including Data Structures 6th


Edition D. S. Malik

https://ebookgate.com/product/c-programming-program-design-including-
data-structures-6th-edition-d-s-malik/

ebookgate.com
C Programming Program design including data structures
5ed. Edition Malik D.S.

https://ebookgate.com/product/c-programming-program-design-including-
data-structures-5ed-edition-malik-d-s/

ebookgate.com

Java Foundations Introduction to Program Design and Data


Structures 2nd Edition John Lewis

https://ebookgate.com/product/java-foundations-introduction-to-
program-design-and-data-structures-2nd-edition-john-lewis/

ebookgate.com

Data Structures Problem Solving Using Java 4th Edition


Mark Allen Weiss

https://ebookgate.com/product/data-structures-problem-solving-using-
java-4th-edition-mark-allen-weiss/

ebookgate.com

Introduction to Analysis 4th Edition Edward D. Gaughan

https://ebookgate.com/product/introduction-to-analysis-4th-edition-
edward-d-gaughan/

ebookgate.com

Java How To Program Fourth Edition Harvey M. Deitel

https://ebookgate.com/product/java-how-to-program-fourth-edition-
harvey-m-deitel/

ebookgate.com
Apago PDF Enhancer
JAVA PROGRAMMING
FROM PROBLEM ANALYSIS TO PROGRAM DESIGN

FOURTH EDITION

D.S. MALIK

Apago PDF Enhancer

Australia  Brazil  Japan  Korea  Mexico  Singapore  Spain  United Kingdom  United States
Java Programming: From Problem Analysis
For product information and technology assistance, contact us at
to Program Design, Fourth Edition
Cengage Learning Customer & Sales Support, 1-800-354-9706
D.S. Malik For permission to use material from this text or product, submit
all requests online at cengage.com/permissions
Executive Editor: Marie Lee
Further permissions questions can be emailed to
Acquisitions Editor: Amy Jollymore [email protected]
Senior Product Manager: Alyssa Pratt
Editorial Assistant: Julia Leroux-Lindsey
ISBN-13: 978-1-4390-3566-5
Marketing Manager: Bryant Chrzan
ISBN-10: 1-4390-3566-0
Senior Content Project Manager: Catherine
Course Technology
DiMassa
20 Channel Center
Art Director: Marissa Falco Boston, MA 02210
Compositor: Integra USA
Cengage Learning is a leading provider of customized
learning solutions with office locations around the globe,
including Singapore, the United Kingdom, Australia, Mexico,
ª 2010 Course Technology, Cengage Brazil, and Japan. Locate your local office at:
Learning international.cengage.com/region
ALL RIGHTS RESERVED. No part of this work Cengage Learning products are represented in Canada
covered by the copyright herein may be by Nelson Education, Ltd.
reproduced, transmitted, stored or used in any
form or by any means graphic, electronic, or For your lifelong learning solutions, visit
mechanical, including but not limited to course.cengage.com
photocopying, recording, scanning, digitizing, Visit our corporate website at cengage.com
Apago Some
taping, Web distribution, information PDF Enhancer
of the product names and company names used in this
networks, or information storage and retrieval book have been used for identification purposes only and may
systems, except as permitted under Section be trademarks or registered trademarks of their respective
107 or 108 of the 1976 United States Copyright manufacturers and sellers.
Act, without the prior written permission of
the publisher. Any fictional data related to persons or companies or URLs used
throughout this book is intended for instructional purposes only.
At the time this book was printed, any such data was fictional
and not belonging to any real persons or companies.
Course Technology, a part of Cengage Learning, reserves the
right to revise this publication and make changes from time to
time in its content without notice.
The programs in this book are for instructional purposes only.
They have been tested with care, but are not guaranteed for any
particular intent beyond educational purposes. The author and
the publisher do not offer any warranties or representations, nor
do they accept any liabilities with respect to the programs.

Printed in Canada
1 2 3 4 5 6 7 12 11 10 09
TO

Apago My Daughter
PDF Enhancer

Shelly Malik
This page intentionally left blank

Apago PDF Enhancer


BRIEF CONTENTS

PREFACE xix

1. An Overview of Computers and Programming Languages 1

2. Basic Elements of Java 25

3. Introduction to Objects and Input/Output 107

4. Control Structures I: Selection 165

5. Control Structures II: Repetition 225

6. Graphical User Interface (GUI) and Object-Oriented Design (OOD) 295

7. User-Defined Methods 351

Apago PDF Enhancer


8. User-Defined Classes and ADTs 425

9. Arrays 509

10. Inheritance and Polymorphism 591

11. Handling Exceptions and Events 673

12. Advanced GUIs and Graphics 733

13. Recursion 823

14. Searching and Sorting 855

APPENDIX A Java Reserved Words 891

APPENDIX B Operator Precedence 893

APPENDIX C Character Sets 897

APPENDIX D Additional Java Topics 901

APPENDIX E Answers to Odd-Numbered Exercises 949

INDEX 973
TABLE OF CONTENTS

Preface xix

AN OVERVIEW OF COMPUTERS AND PROGRAMMING


1 LANGUAGES 1
Introduction 2
An Overview of the History of Computers 2

Elements of a Computer System 3


Hardware 4
Software 6
Language of a Computer 6

Evolution of Programming Languages 8


Apago
Processing PDF Enhancer
a Java Program 10
Internet, World Wide Web, Browser, and Java 13

Programming with the Problem Analysis–Coding–


Execution Cycle 13
Programming Methodologies 19
Structured Programming 19
Object-Oriented Programming 19
Quick Review 21

Exercises 23

BASIC ELEMENTS OF JAVA 25


2 A Java Program 26
Basics of a Java Program 28
Comments 29
Special Symbols 30
Reserved Words (Keywords) 30
Identifiers 31
Table of Contents | vii

Data Types 32
Primitive Data Types 32

Arithmetic Operators and Operator Precedence 36


Order of Precedence 39

Expressions 40
Mixed Expressions 41

Type Conversion (Casting) 43

class String 45
Strings and the Operator + 46

Input 48
Allocating Memory with Named Constants and Variables 48
Putting Data into Variables 51
Declaring and Initializing Variables 55
Input (Read) Statement 56
Reading a Single Character 61

Increment and Decrement Operators 63


Apago PDF Enhancer
Output 66

Packages, Classes, Methods, and the import Statement 71

Creating a Java Application Program 72

Programming Style and Form 77


Syntax 77

Avoiding Bugs: Consistent, Proper Formatting 81


Debugging—Code Walk-throughs 81

More on Assignment Statements (Optional) 82

Programming Example: Convert Length 84

Programming Example: Make Change 88

Debugging: Understanding Error Messages 91

Quick Review 91

Exercises 94

Programming Exercises 102


viii | Java Programming: From Problem Analysis to Program Design, Fourth Edition

INTRODUCTION TO OBJECTS AND INPUT/OUTPUT 107


3 Objects and Reference Variables 108

Using Predefined Classes and Methods in a Program 112


Dot Between Class (Object) Name and Class Member:
A Precaution 114

class String 115

Input/Output 123
Formatting Output with printf 123
Using Dialog Boxes for Input/Output 132
Formatting the Output Using the String Method format 139

File Input/Output 142


Storing (Writing) Output to a File 145

Programming Example: Movie Ticket Sale and


Donation to Charity 147

Programming Example: Student Grade 153


Apago PDF Enhancer
Debugging—Understanding Error Messages 156

Quick Review 156

Exercises 158

Programming Exercises 161

CONTROL STRUCTURES I: SELECTION 165


4 Control Structures 166

Relational Operators 168

Relational Operators and Primitive Data Types 169

Logical (Boolean) Operators and Logical Expressions 172

Order of Precedence 174


Short-Circuit Evaluation 178
boolean Data Type and Logical (Boolean) Expressions 179
Table of Contents | ix

Selection: if and if...else 180


One-Way Selection 180
Two-Way Selection 183
Compound (Block of) Statements 187
Multiple Selections: Nested if 188
Comparing if...else Statements with a Series
of if Statements 191
Conditional Operator (? :) (Optional) 192

switch Structures 193

Avoiding Bugs by Avoiding Partially Understood


Concepts and Techniques 199

Programming Example: Cable Company Billing 201


Comparing Strings 207
Strings, the Assignment Operator, and the Operator new 211

Quick Review 213


Exercises 215
Apago PDF Enhancer
Programming Exercises 221

CONTROL STRUCTURES II: REPETITION 225


5 Why Is Repetition Needed? 226

while Looping (Repetition) Structure 227


Designing while Loops 230
Counter-Controlled while Loops 231
Sentinel-Controlled while Loops 233
Flag-Controlled While Loops 239
EOF-Controlled while Loops 243
More on Expressions in while Statements 247

Programming Example: Fibonacci Number 248


for Looping (Repetition) Structure 254

Programming Example: Classify Numbers 259


do...while Looping (Repetition) Structure 263
Choosing the Right Looping Structure 268
x | Java Programming: From Problem Analysis to Program Design, Fourth Edition

break and continue Statements 268

Avoiding Bugs by Avoiding Patches 270


Nested Control Structures 272
Quick Review 277

Exercises 279
Programming Exercises 289

GRAPHICAL USER INTERFACE (GUI) AND OBJECT-


6 ORIENTED DESIGN (OOD) 295
Graphical User Interface (GUI) Components 296
Creating a Window 300
JFrame 300
Getting Access to the Content Pane 306
JLabel 307
JTextField 311
JButton 315
Apago PDF Enhancer
Programming Example: Temperature Conversion 323

Object-Oriented Design 331


A Simplified OOD Methodology 332

Implementing Classes and Operations 338


Primitive Data Types and the Wrapper Classes 338

Quick Review 345

Exercises 346

Programming Exercises 349

USER-DEFINED METHODS 351


7
Predefined Methods 352
Using Predefined Methods in a Program 356

User-Defined Methods 359


Value-Returning Methods 359
return Statement 363
Final Program 366
Table of Contents | xi

Flow of Execution 372

Programming Example: Largest Number 373

Void Methods 375

Primitive Data Type Variables as Parameters 379

Reference Variables as Parameters 382


Parameters and Memory Allocation 382
Reference Variables of the String Type as Parameters:
A Precaution 382
The class StringBuffer 386

Primitive Type Wrapper Classes as Parameters 389

Scope of an Identifier Within a Class 390

Method Overloading: An Introduction 393

Programming Example: Data Comparison 395

Avoiding Bugs: One-Piece-at-a-Time Coding 406


Apago PDF
Avoiding Bugs: Enhancer
Using ‘‘Stubs’’ as Appropriate 407

Quick Review 407

Exercises 410

Programming Exercises 418

USER-DEFINED CLASSES AND ADTs 425


8 Classes and Objects 426
Constructors 431
Unified Modeling Language Class Diagrams 432
Variable Declaration and Object Instantiation 433
Accessing Class Members 435
Built-in Operations on Classes 436
Assignment Operator and Classes: A Precaution 436
Class Scope 438
Methods and Classes 439
Definitions of the Constructors and Methods
of the class Clock 439
xii | Java Programming: From Problem Analysis to Program Design, Fourth Edition

Classes and the Method toString 452

Copy Constructor 458


Static Members of a Class 459
static Variables (Data Members) of a Class 461
Finalizers 465

Accessor and Mutator Methods 465


Debugging—Designing a Class and Documenting
the Design 468
Debugging—Design Walk-Throughs 471
Reference this (Optional) 472
Cascaded Method Calls (Optional) 474

Inner Classes 477

Abstract Data Types 477

Programming Example: Candy Machine 479

Quick Review 497


Apago PDF Enhancer
Exercises 498

Programming Exercises 505

ARRAYS 509
9 Why Do We Need Arrays? 510

Arrays 511
Alternate Ways to Declare an Array 513
Accessing Array Elements 513
Specifying Array Size during Program Execution 515
Array Initialization during Declaration 516
Arrays and the Instance Variable length 516
Processing One-Dimensional Arrays 517
Array Index Out of Bounds Exception 522
Declaring Arrays as Formal Parameters to Methods 522
Assignment Operator, Relational Operators, and Arrays:
A Precaution 523
Arrays as Parameters to Methods 525
Table of Contents | xiii

Searching an Array for a Specific Item 530

Arrays of Objects 532


Arrays of string Objects 532
Arrays of Objects of Other Classes 534

Arrays and Variable Length Parameter List (Optional) 539

Two-Dimensional Arrays 547


Accessing Array Elements 549
Two-Dimensional Array Initialization During Declaration 552
Processing Two-Dimensional Arrays 553
Passing Two-Dimensional Arrays as Parameters to Methods 557

Multidimensional Arrays 561

Programming Example: Code Detection 563

Programming Example: Text Processing 567

class Vector (Optional) 574


Primitive Data Types and the class Vector 578
Apago PDFandEnhancer
Vector Objects the foreach Loop 578

Quick Review 579

Exercises 581

Programming Exercises 586

INHERITANCE AND POLYMORPHISM 591


10 Inheritance 592
Using Methods of the Superclass in a Subclass 594
Constructors of the Superclass and Subclass 600
Protected Members of a Class 609
class object 612

Java Stream Classes 614


Polymorphism 615
Operator instanceof 621

Abstract Methods and Classes 626


Interfaces 632
xiv | Java Programming: From Problem Analysis to Program Design, Fourth Edition

Polymorphism Via Interfaces 634

Composition (Aggregation) 636

Programming Example: Grade Report 641

Quick Review 661

Exercises 663

Programming Exercises 668

HANDLING EXCEPTIONS AND EVENTS 673


11 Handling Exceptions Within a Program 674
Java’s Mechanism of Exception Handling 677
try/catch/finally Block 678

Java Exception Hierarchy 683

Java’s Exception Classes 686

Checked and Unchecked Exceptions 691


Apago PDF Enhancer
More Examples of Exception Handling 693
class Exception and the Operator instanceof 696

Rethrowing and Throwing an Exception 699

Method printStackTrace 703

Exception-Handling Techniques 706


Terminate the Program 706
Fix the Error and Continue 706
Log the Error and Continue 708

Creating Your Own Exception Classes 708

Event Handling 710

Programming Example: Calculator 716

Quick Review 726

Exercises 728

Programming Exercises 731


Table of Contents | xv

ADVANCED GUIs AND GRAPHICS 733


12 Applets 737

class Font 741

class Color 744

class Graphics 750


Converting an Application Program to an Applet 758

Additional GUI Components 761


JTextArea 761
JCheckBox 766
JRadioButton 773
JComboBox 778
JList 783

Layout Managers 789


FlowLayout 790
BorderLayout 793
Apago
Menus PDF Enhancer 794

Key and Mouse Events 797


Key Events 798
Mouse Events 800

Programming Example: Java Kiosk 807

Quick Review 815

Exercises 816

Programming Exercises 818

RECURSION 823
13 Recursive Definitions 824
Direct and Indirect Recursion 826
Infinite Recursion 827
Designing Recursive Methods 827
Problem Solving Using Recursion 828
Tower of Hanoi: Analysis 837
xvi | Java Programming: From Problem Analysis to Program Design, Fourth Edition

Recursion or Iteration? 838


Programming Example: Decimal to Binary
Conversion 839

Programming Example: Sierpinski Gasket 842

Quick Review 846

Exercises 847

Programming Exercises 850

SEARCHING AND SORTING 855


14 List Processing 856
Searching 856
Selection Sort 857
Insertion Sort 861
Binary Search 867
Avoiding Bugs: Developing Test Suites in Advance 871
Apago PDF Enhancer
Programming Example: Election Results 874

Quick Review 887

Exercises 887

Programming Exercises 888

APPENDIX A: JAVA RESERVED WORDS 891

APPENDIX B: OPERATOR PRECEDENCE 893

APPENDIX C: CHARACTER SETS 897


ASCII (American Standard Code for Information
Interchange), the First 128 Characters of the
Unicode Character Set 897
EBCDIC (Extended Binary Coded Decimal
Interchange Code) 898
Table of Contents | xvii

APPENDIX D: ADDITIONAL JAVA TOPICS 901


Binary (Base 2) Representation of a Nonnegative Integer 901
Converting a Base 10 Number to a Binary Number (Base 2) 901
Converting a Binary Number (Base 2) to Base 10 903
Converting a Binary Number (Base 2) to Octol (Base 8)
and Hexdecimal (Base 16) 904

Executing Java Programs Using the Command-Line


Statements 906
Setting the Path in Windows (XP) 906
Executing Java Programs 911

Java Style Documentation 915

Creating Your Own Packages 918


Multiple File Programs 921

Formatting the Output of Decimal Numbers Using


the class DecimalFormat 921

Packages and
Apago PDFUser-Defined
EnhancerClasses 924
PrimitiveType Classes 924
Class: IntClass 924
Class: LongClass 928
Class: CharClass 929
Class: FloatClass 929
Class: DoubleClass 930
Class: BooleanClass 931
Using PrimitiveType Classes in a Program 932

Enumeration Types 933

Programming Example: The Rock, Paper,


and Scissors Game 939

APPENDIX E: ANSWERS TO ODD-NUMBERED


EXERCISES 949
Chapter 1 949

Chapter 2 950
xviii | Java Programming: From Problem Analysis to Program Design, Fourth Edition

Chapter 3 952

Chapter 4 953

Chapter 5 955

Chapter 6 957

Chapter 7 962

Chapter 8 963

Chapter 9 965

Chapter 10 966

Chapter 11 968

Chapter 12 970

Chapter 13 971

Chapter 14 971

Apago
INDEX PDF Enhancer 973
P REFACE TO THE F OURTH E DITION

Welcome to Java Programming: From Problem Analysis to Program Design, Fourth Edition. Designed
for a first Computer Science (CS1) Java course, this text will provide a breath of fresh air to you
and your students. The CS1 course serves as the cornerstone of the Computer Science curricu-
lum. My primary goal is to motivate and excite all programming students, regardless of their level.
Motivation breeds excitement for learning. Motivation and excitement are critical factors that
lead to the success of the programming student. This text is the culmination and development of
my classroom notes throughout more than fifty semesters of teaching successful programming.
Warning: This text can be expected to create a serious reduction in the demand for program-
ming help during your office hours. Other side effects include significantly diminished student
dependency on others while learning to program.

The primary focus in writing this text is on student learning. Therefore, in addition to clear
explanations, we address the key issues that otherwise impede student learning. For example, a
common question that arises naturally during an early programming assignment is: ‘‘How
Apago PDF Enhancer
many variables and what kinds are needed in this program?’’ We illustrate this important and
crucial step by helping students learn why variables are needed and how data in a variable is
manipulated. Next students learn that the analysis of the problem will spill the number and
types of the variables. Once students grasp this key concept, control structures, (selection and
loops) become easier to learn. The second major impediment in learning programming is
parameter passing. We pay special attention to this topic. First students learn how to use
predefined methods and how actual and formal parameters relate. Next students learn about
user-defined methods. They see visual diagrams that help them learn how methods are called
and how formal parameters affect actual parameters. Once students have a clear understanding
of these two key concepts, they readily assimilate advanced topics.
The topics are introduced at a pace that is conducive to learning. The writing style is friendly,
engaging, and straightforward. It parallels the learning style of the contemporary CS1 student.
Before introducing a key concept, the student learns why the concept is needed, and then sees
examples illustrating the concept. Special attention is paid to topics that are essential in
mastering the Java programming language and in acquiring a foundation for further study
of computer science.
Other important topics include debugging techniques and techniques for avoiding program-
ming bugs. When a beginner compiles his/her first program and sees that the number of
errors exceeds the length of this first program, he/she becomes frustrated by the plethora of
errors, only some of which can be interpreted. To ease this frustration and help students learn
to produce correct programs, debugging and bug avoidance techniques are presented system-
atically throughout the text.
xx | Java Programming: From Problem Analysis to Program Design, Fourth Edition

Changes In The Fourth Edition


In the fourth edition, the main changes are:
• In the fourth edition, throughout the text sections on debugging techniques and
techniques on avoiding programming bugs are included.
• Chapter 10 of the third edition, which includes searching and sorting algorithms, is
now Chapter 14. Sequential search algorithm and the class Vector, which were
covered in Chapter 10, have been moved to Chapter 9. The additional methods of
the class String, which were covered in Chapter 10 of the third edition, are
now covered in Chapter 3. The OOD version of the programming example of
Chapter 14 is available on the Web site and the CD accompanying this book.
Furthermore, Chapter 14 also contains bubble sort and quick sort algorithms, which
are provided on the Web site and the CD accompanying this book.
• Chapters 11, 12, 13, and 14 in the third edition are now Chapters 10, 11, 12, and 13,
respectively, in the fourth edition.
• In the third edition, Chapter 7 contains user-defined classes so that primitive type values
can be passed as objects and methods can manipulate and pass those values back to the
calling environment. In the fourth edition, this discussion is taken out of Chapter 7 and
put in a separate section, entitled ‘‘Chapter_7_PassingPrimitiveTypeAsObjects’’. This
section is available on the Web site and the CD accompanying this book. Furthermore,
Apago PDF Enhancer
as suggested by the reviewers, additional examples are included in this chapter.
• The fourth addition contains more than 30 new programming exercises.
• In Chapter 5, the Programming Example, Checking Account Balance, is available on
the Web site and the CD accompanying this book.
• In Appendix D, a new section on how to create Java style documentation of user-
defined classes has been added.
These changes were implemented based on comments from the text reviewers of the third
edition. The source code and the programming exercises are developed and tested using Java
6.0 and the version of Java 7.0 available at the time the book was being typeset.

Approach
Once conceived as a Web programming language, Java slowly but surely found its way into
classrooms where it now serves as a first programming language in computer science curricula
(CS1). Java is a combination of traditional style programming—programming with a non-
graphical user interface—and modern style programming with a graphical user interface
(GUI). This book introduces you to both styles of programming. After giving a brief
description of each chapter, we discuss how to read this book.
Chapter 1 briefly reviews the history of computers and programming languages. The reader
can quickly skim and become familiar with some of the hardware and software components of
the computer. This chapter also gives an example of a Java program and describes how a Java
Preface to the Fourth Edition | xxi

program is processed. The two basic problem-solving techniques, structured programming


and object-oriented design, are also presented.
After completing Chapter 2, students become familiar with the basics of Java and are ready to
write programs that are complicated enough to do some computations.
The three terms that you will encounter throughout the book are—primitive type variables,
reference variables, and objects. Chapter 3 makes clear distinctions between these terms and sets
the tone for the rest of the book. An object is a fundamental entity in an object-oriented
programming language. This chapter further explains how an object works. The class String
is one of the most important classes in Java. This chapter introduces this class and explains how
various methods of this class can be used to manipulate strings. Because input/output is funda-
mental to any programming language, it is introduced early, and is covered in detail in Chapter 3.
Chapters 4 and 5 introduce control structures used to alter the sequential flow of execution.
Java is equipped with powerful yet easy-to-use graphical user interface (GUI) components to
create user-friendly graphical programs. Chapter 6 introduces various GUI components and
gives examples of how to use these components in Java application programs. Because Java is
an object-oriented programming language, the second part of Chapter 6 discusses and gives
examples of how to solve various problems using object-oriented design methodology.
Chapter 7 discusses user-defined methods. Parameter passing is a fundamental concept in any
programming language. Several examples, including visual diagrams, help readers understand
Apago PDF Enhancer
this concept. It is recommended that readers with no prior programming background spend
extra time on this concept.
Chapter 8 discusses user-defined classes. In Java, a class is an important and widely used
element. It is used to create Java programs, group related operations, and it allows users to
create their own data types. This chapter uses extensive visual diagrams to illustrate how
objects of classes manipulate data.
Chapter 9 describes arrays. This chapter also introduces variable length formal parameter lists.
In addition, this chapter introduces foreach loops and explains how this loop can be used to
process the elements of an array. This chapter also discusses the sequential searching algorithm
and the class Vector.
Inheritance is an important principle of object-oriented design. It encourages code reuse.
Chapter 10 discusses inheritance, and gives various examples to illustrate how classes are
derived from existing classes. In addition, this chapter also discusses polymorphism, abstract
classes, inner classes, and composition.
An occurrence of an undesirable situation that can be detected during program execution is
called an exception. For example, division by zero is an exception. Java provides extensive
support for handing exceptions. Chapter 11 shows how to handle exceptions in a program.
Chapter 11 also discusses event handling, which was introduced in Chapter 6. Chapter 12
picks up the discussion of GUI components started in Chapter 6. This chapter introduces
additional GUI components and discusses how to create applets.
xxii | Java Programming: From Problem Analysis to Program Design, Fourth Edition

Chapter 13 introduces recursion. Several examples illustrate how recursive methods execute.
Chapter 14 discusses a binary search algorithm as well as bubble sort, selection sort, insertion
sort, and quick sort algorithms. The sorting algorithms: bubble sort and quick sort are
provided on the Web site and the CD accompanying this book.
Appendix A lists the reserved words in Java. Appendix B shows the precedence and
associativity of the Java operators. Appendix C lists the ASCII (American Standard Code
for Information Interchange) portion of the Unicode character set as well as the EBCDIC
(Extended Binary Code Decimal Interchange) character set.
Appendix D contains additional topics in Java. The topics covered are converting a base 10
number to binary (base 2) number and vice versa, converting a number from base 2 to base 8
(base 16) and vice versa, how to compile and execute a Java program using command line
statements, how to create Java style documentation of the user-defined classes, how to create
packages, how to use user-defined classes in a Java program, and enum type. Appendix E
gives answers to all the odd-numbered exercises in the text.

How To Use This Book


Java is a complex and very powerful language. In addition to traditional (non-GUI) program-
ming, Java provides extensive support for creating programs that use a graphical user interface
(GUI). Chapter 3 introduces graphical input and output dialog boxes. Chapter 6 introduces
Apago PDF Enhancer
most commonly used GUI components such as labels, buttons, and text fields. More extensive
coverage of GUI components is provided in Chapter 12.
This book can be used in two ways. One way is an integrated approach in which readers learn
how to write both non-GUI and GUI programs as they learn basic programming concepts
and skills. The other approach focuses on illustrating fundamental programming concepts
with non-GUI programming first, and later incorporating GUI components. The recom-
mended chapter sequence for each of these approaches is as follows:
• Integrated approach: Study all chapters in sequence.
• Non-GUI first, then GUI: Study Chapters 1–5 in sequence. Then study Chapters
7–11 and Chapters 13 and 14. This approach initially skips Chapters 6 and 12, the
primary GUI chapters. After studying Chapters 1–5, 7–11, 13, and 14, the reader can
come back to study Chapters 6 and 12, the GUI chapters. Also note that Chapter 14
can be studied after Chapter 9.
If you choose the second approach, it should also be noted that the Programming Examples in
Chapters 8 and 10 are developed first without any GUI components, and then the programs
are extended to incorporate GUI components. Also, if Chapter 6 is skipped, the reader can skip
the event handling part of Chapter 11. Chapter 13 (recursion) contains two Programming
Examples: one creates a non-GUI application program, while the other creates a program that
uses GUI. If you skip Chapters 6 and 12, you can skip the GUI part of the Programming
Examples in Chapters 8, 10, 11, and 13. Once you have studied Chapter 6 and 12, you can
study the GUI part of the Programming Examples of Chapters 8, 10, 11, and 13.
Preface to the Fourth Edition | xxiii

Figure 1 shows a chapter dependency diagram for this book. Solid arrows indicate that the
chapter at the beginning of the arrow is required before studying the chapter at the end of the
arrow. A dotted arrow indicates that the chapter at the beginning of the arrow is not essential
to studying the chapter at the end of the dotted arrow.

Chapter 1

Chapter 2

Chapter 3

Chapter 4

Chapter 5

Chapter 6 Chapter 7

Chapter 8 Chapter 9
Apago PDF Enhancer
Chapter 10 Chapter 14

Chapter 11

Chapter 12

Chapter 13

A dotted arrow means that the chapter is not essential to studying the following chapter.

FIGURE 1 Chapter dependency diagram

All source code and solutions have been written, compiled, and quality assurance tested
with Java 6.0 and the version of Java 7.0 available at the time the book was being typeset.
FEATURES OF THE BOOK

Apago PDF Enhancer

Four-color
interior design
shows
accurate code
and related
comments.
More than
Apago PDF Enhancer
250 visual
diagrams,
both
extensive and
exhaustive,
illustrate difficult
concepts.
Apago PDF Enhancer

Numbered Examples
illustrate the key
concepts with their
relevant code. The
programming code in
these examples is
followed by a Sample
Run. An explanation
then follows that
describes what each
line in the code does.
Apago PDF Enhancer

Notes highlight
important facts
about the concepts
introduced in the
chapter.
Programming
Examples are
complete programs
featured in each
chapter. These
examples include the
accurate, concrete
stages of Input,
Output, Problem
Analysis and Algorithm
Design, and a
Complete Program
Listing.

Apago PDF Enhancer


Apago PDF Enhancer

Exercises further
reinforce learning
and ensure that
students have, in
fact, mastered the
material.
Programming
Exercises challenge
students to write
Java programs with
a specified
outcome.

Apago PDF Enhancer


SUPPLEMENTAL RESOURCES

The following supplemental materials are available when this book is used in a classroom
setting.
All instructor teaching tools, outlined below, are available with this book on a single
CD-ROM.

Electronic Instructor’s Manual


The Instructor’s Manual that accompanies this textbook includes:
• Additional instructional material to assist in class preparation, including suggestions
for lecture topics.
• Solutions to all the end-of-chapter materials, including the Programming Exercises.

Ò
ExamView
Apago PDF Enhancer
This textbook is accompanied by ExamView, a powerful testing software package that
allows instructors to create and administer printed, computer (LAN-based), and Internet
exams. ExamView includes hundreds of questions that correspond to the topics covered in
this text, enabling students to generate detailed study guides that include page references for
further review. These computer-based and Internet testing components allow students to
take exams at their computers, and save the instructor time because each exam is graded
automatically.

PowerPoint Presentations
This book comes with Microsoft PowerPoint slides for each chapter. These slides are included as
a teaching aid for classroom presentations, either to make available to students on the network
for chapter review, or to be printed for classroom distribution. Instructors can add their own
slides for additional topics that they introduce to the class.

Distance Learning
Cengage Course Technology is proud to present online courses in WebCT and Blackboard
to provide the most complete and dynamic learning experience possible. For more informa-
tion on how to bring distance learning to your course, contact your local Cengage Course
Technology sales representative.
xxxii | Java Programming: From Problem Analysis to Program Design, Fourth Edition

Source Code
The source code is available at http://www.cengage.com/highered/, and is also available on the
Instructor Resources CD-ROM and the CD accompanying this text. The input files needed
to run some of the programs are also included with the source code.

Solution Files
The solution files for all programming exercises are available at http://www.cengage.com/highered/,
and are also available on the Instructor Resources CD-ROM. The input files needed to run some
of the programming exercises are also included with the solution files.

Apago PDF Enhancer


ACKNOWLEDGMENTS

There are many people I must thank who, one way or another, contributed to the success of
this book. First, I would like to thank those who e-mailed numerous comments to improve
on the third edition. I am thankful to Professors S.C. Cheng, Randall Crist, and John N.
Mordeson, for constantly supporting this project.
I owe a great deal to the following reviewers, who patiently read each page of every chapter
of the current version and made critical comments to improve on the book: Atef Bader,
DePaul University; Rajwant Gill, Anne Arundel Community College; Gerard Gordon,
DePaul University; Jenneth Honeycutt, Fayetteville Technical Community College; and
John Mill, Spokane Falls Community College. Additionally, I would like to thank the
reviewers of the proposal package: Lemond Hall, South Georgia Technical College and
Hemand Pendharkar, Worcester State College. The reviewers will recognize that their
suggestions have not been overlooked and, in fact, made this a better book.
Next, I express thanks to Amy Jollymore, Acquisitions Editor, for recognizing the importance
Apago PDF Enhancer
and uniqueness of this project. All this would not have been possible without the careful
planning of Senior Product Manager Alyssa Pratt. I extend my sincere thanks to Alyssa, as well
as to Senior Content Project Manager, Catherine DiMassa. I also thank Tintu Thomas of
Integra Software Services for assisting us in keeping the project on schedule. I would like to
thank Chris Scriver and Serge Palladino of the QA department of Course Technology for
patiently and carefully proofreading the text, testing the code, and discovering typos and erros.
I am thankful to my parents for their blessings.
Finally, I am thankful to the support of my wife Sadhana, and especially my daughter Shelly,
to whom this book is dedicated. They cheered me up whenever I was overwhelmed during
the writing of this book.
We welcome any comments concerning the text. Comments may be forwarded to the
following e-mail address: [email protected].
D.S. Malik
This page intentionally left blank

Apago PDF Enhancer


CHAPTER

1
A N OApago
VERVIEW OF C
PDF Enhancer
OMPUTERS
AND P ROGRAMMING L ANGUAGES
IN THIS CHAPTER, YOU WILL:

n Learn about different types of computers


n Explore the hardware and software components of a computer
system
n Learn about the language of a computer
n Learn about the evolution of programming languages
n Examine high-level programming languages
n Discover what a compiler is and what it does
n Examine how a Java program is processed
n Learn about the Internet and World Wide Web
n Learn what an algorithm is and explore problem-solving
techniques
n Become familiar with structured and object-oriented
programming design methodologies
2 | Chapter 1: An Overview of Computers and Programming Languages

Introduction
Terms such as ‘‘the Internet,’’ which was unfamiliar just a few years ago, are now
common. Elementary school students regularly ‘‘surf’’ the Internet and use computers
to design their classroom projects. Many people use the Internet to look up information
and to communicate with others. These Internet activities are all made possible by the
availability of different software, also known as computer programs. Software is devel-
oped by using programming languages. The programming language Java is especially well
suited for developing software to accomplish specific tasks. Our main objective is to teach
you how to write programs in the Java programming language. Before you begin
programming, it is useful if you understand some of the basic terminology and different
components of a computer. We begin with an overview of the history of computers.

An Overview of the History of Computers


The first device known to carry out calculations was the abacus. The abacus was invented
in Asia but was used in ancient Babylon, China, and throughout Europe until the late
middle ages. The abacus uses a system of sliding beads on a rack for addition and
subtraction. In 1642, the French philosopher and mathematician Blaise Pascal invented
the calculating device called the Pascaline. It had eight movable dials on wheels that could
calculate sums up to eight figures long. Both the abacus and Pascaline could perform only
addition and subtraction operations. Later in the seventeenth century, Gottfried von
Apago PDF Enhancer
Leibniz invented a device that was able to add, subtract, multiply, and divide. In 1819,
Joseph Jacquard, a French weaver, discovered that the weaving instructions for his looms
could be stored on cards with holes punched in them. While the cards moved throughout the
loom in sequence, needles passed through the holes and picked up threads of the correct color
and texture. A weaver could rearrange the cards and change the pattern being woven. In
essence, the cards programmed a loom to produce patterns in cloth. The weaving industry
seems to have little in common with the computer industry. However, the idea of storing
information by punching holes on a card turned out to be of great importance in the later
development of computers.
In the early and mid-1800s, Charles Babbage, an English mathematician and physical
scientist, designed two calculating machines—the difference engine and the analytical
engine. The difference engine could automatically perform complex operations, such as
squaring numbers. Babbage built a prototype of the difference engine, but the actual
device was never produced. The analytical engine’s design included input device,
memory storage, a control unit that allowed processing instructions in any sequence,
and output devices. However, the designs remained in blueprint stage. Most of Babbage’s
work is known through the writings of the colleague Ada Augusta, Countess of Lovelace.
Augusta is considered to be the first computer programmer.
At the end of the 19th century, U.S. Census officials needed help in accurately tabulating
the census data. Herman Hollerith invented a calculating machine that ran on electricity
and used punched cards to store data. Hollerith’s machine was immensely successful.
Elements of a Computer System | 3

Hollerith founded the Tabulating Machine Company, which later became the computer
and technology corporation known as IBM. 1
The first computer-like machine was the Mark I. It was built, in 1944, jointly by IBM and
Harvard University under the leadership of Howard Aiken. Punched cards were used to
feed data into the machine. Mark I was 52 feet long, weighed 50 tons, and had 750,000
parts. In 1946, ENIAC (Electronic Numerical Integrator and Calculator) was built at the
University of Pennsylvania. It contained 18,000 vacuum tubes and weighed some 30 tons.
The computers that we know today use the design rules given by John von Neumann in
the late 1940s. His design included components such as arithmetic logic unit, control
unit, memory, and input/output devices. These components are described in the next
section. Von Neumann computer design makes it possible to store the programming
instruction and the data in the same memory space. In 1951, the UNIVAC (Universal
Automatic Computer) was built and sold to the U.S. Census Bureau.
In 1956, the invention of the transistors resulted in smaller, faster, more reliable, and more
energy-efficient computers. This era also saw the emergence of the software development
industry with the introduction of FORTRAN and COBOL, two early programming
languages. In the next major technological advancement, transistors were replaced by tiny
integrated circuits or ‘‘chips.’’ Chips are smaller and cheaper than transistors and can
contain thousands of circuits on a single chip. They give computers tremendous proces-
sing speed.
Apago PDF Enhancer
In 1970, the microprocessor, an entire CPU on a single chip, was invented. In 1977,
Stephen Wozniak and Steven Jobs designed and built the first Apple computer in their
garage. In 1981, IBM introduced its personal computer (PC). In the 1980s, clones of the
IBM PC made the personal computer even more affordable. By the mid-1990s, people
from many walks of life were able to afford them. Computers continue to become faster
and less expensive as technology advances.
Modern-day computers are very powerful, reliable, and easy to use. They can accept
spoken-word instructions and imitate human reasoning through artificial intelligence.
Expert systems assist doctors in making diagnoses. Mobile computing applications are
growing significantly. Using hand-held devices, delivery drivers can access global posi-
tioning satellites (GPS) to verify customer locations for pickups and deliveries. Cell
phones can check your e-mail, make airline reservations, see how stocks are performing,
and access your bank accounts.
Although there are several categories of computers, such as mainframe, midsize, and
micro, all computers share some basic elements.

Elements of a Computer System


A computer is an electronic device capable of performing commands. The basic com-
mands that a computer performs are input (get data), output (display results), storage, and
performance of arithmetic and logical operations.
4 | Chapter 1: An Overview of Computers and Programming Languages

In today’s market, personal computers are sold with descriptions such as a Pentium 4
Processor 2.80 GHz, 1 GB RAM, 100 GB HD, VX750 17’’ Silver Flat CRT Color Monitor,
preloaded with software such as an operating system, games, encyclopedias, and application
software such as word processors or money management programs. These descriptions
represent two categories: hardware and software. Items such as ‘‘Pentium 4 Processor 2.80
GHz, 1 GB RAM, 100 GB HD, VX750 17’’ Silver Flat CRT Color Monitor’’ fall into the
hardware category; items such as ‘‘operating system, games, encyclopedias, and application
software’’ fall into the software category. Let’s look at the hardware first.

Hardware
Major hardware components include the central processing unit (CPU); main memory
(MM), also called random access memory (RAM); input/output devices; and secondary
storage. Some examples of input devices are the keyboard, mouse, and secondary storage.
Examples of output devices are the monitor, printer, and secondary storage.

CENTRAL PROCESSING UNIT AND MAIN MEMORY


The central processing unit (CPU) is the ‘‘brain’’ of the computer and the single most
expensive piece of hardware in a computer. The more powerful the CPU, the faster the
computer. Arithmetic and logical operations are carried out inside the CPU. Figure 1-1(a)
shows some hardware components.
Apago PDF Enhancer
. .
. .
Input
Central . .
Device
Processing 1000 54
Unit (CPU) 1001 A
Output
Device . .
. .
. .
Main Memory 2000
2001
. .
. .
. .
Secondary Storage Main Memory

(a) (b)

FIGURE 1-1 Hardware components of a computer and main memory

Main memory, or random access memory (RAM), is connected directly to the CPU.
All programs must be loaded into main memory before they can be executed. Similarly,
Elements of a Computer System | 5

all data must be brought into main memory before a program can manipulate it. When
the computer is turned off, everything in main memory is lost. 1
Main memory is an ordered sequence of cells, called memory cells. Each cell has a unique
location in main memory, called the address of the cell. These addresses help you access
the information stored in the cell. Figure 1-1(b) shows main memory with some data.
Today’s computers come with main memory consisting of millions to billions of cells.
Although Figure 1-1(b) shows data stored in cells, the content of a cell can be either a
programming instruction or data. Moreover, this figure shows the data as numbers and
letters. However, as explained later in this chapter, main memory stores everything as
sequences of 0s and 1s. The memory addresses are also expressed as sequences of 0s and 1s.

SECONDARY STORAGE
Because programs and data must be stored in main memory before processing, and
because everything in main memory is lost when the computer is turned off, information
stored in main memory must be transferred to some other device for longer-term storage.
A device that stores longer-term information (unless the device becomes unusable or you
change the information by rewriting it) is called secondary storage. To be able to
transfer information from main memory to secondary storage, these components must be
connected directly to each other. Examples of secondary storage are hard disks, floppy
disks, flash memory, ZIP disks, CD-ROMs, and tapes.
Apago PDF Enhancer
INPUT/OUTPUT DEVICES
For a computer to perform a useful task, it must be able to take in data and programs and
display the results of the manipulation of the data. The devices that feed data and
programs into computers are called input devices. The keyboard, mouse, and secondary
storage are examples of input devices. The devices that the computer uses to display and
store results are called output devices. A monitor, printer, and secondary storage are
examples of output devices. Figure 1-2 shows some input and output devices.

Input devices Output devices

FIGURE 1-2 Some input and output devices


6 | Chapter 1: An Overview of Computers and Programming Languages

Software
Software consists of programs written to perform specific tasks. For example, you use
word-processing programs to write letters, papers, and books. The two types of programs
are system programs and application programs.
System programs control the computer. The system program that loads first when
you turn on your PC is called the operating system. Without an operating system,
the computer is useless. The operating system monitors the overall activity of the
computer and provides services, such as memory management, input/output activities,
and storage management. The operating system has a special program that organizes
secondary storage so that you can access information conveniently. The operating
system is the program that runs the application programs. Application programs
perform specific tasks. Word processors, spreadsheets, and games are examples of
application programs. Both operating systems and application programs are written in
programming languages.

Language of a Computer
When you press A on your keyboard, the computer displays A on the screen, but what is
actually stored inside the computer’s main memory? What is the language of the
Apago PDF Enhancer
computer? How does it store whatever you type on the keyboard?
Remember that a computer is an electronic device. Electrical signals move along channels
inside the computer. There are two types of electrical signals: analog and digital. Analog
signals are continuous waveforms used to represent things, such as sound. Audio tapes,
for example, store data in analog signals. Digital signals represent information with a
sequence of 0s and 1s. A 0 represents a low voltage, and a 1 represents a high voltage.
Digital signals are more reliable carriers of information than analog signals and can be
copied from one device to another with exact precision. You might have noticed that
when you make a copy of an audio tape, the sound quality of the copy is not as good as
that on the original tape. Computers use digital signals.
Because digital signals are processed inside a computer, the language of a computer, called
machine language, is a sequence of 0s and 1s. The digit 0 or 1 is called a binary digit,
or bit. Sometimes a sequence of 0s and 1s is referred to as a binary code or a binary
number.
Bit: A binary digit 0 or 1.
A sequence of eight bits is called a byte. Moreover, 210 ¼ 1024 bytes and is called a
kilobyte (KB). Table 1-1 summarizes the terms used to describe the various numbers of
bytes.
Language of a Computer | 7

TABLE 1-1 Binary Units


1
Unit Symbol Bits/Bytes
Byte 8 bits

Kilobyte KB 210 bytes ¼ 1024 bytes

Megabyte MB 1024 KB ¼ 210 KB ¼ 220 bytes ¼ 1,048,576 bytes

Gigabyte GB 1024 MB ¼ 210 MB ¼ 230 bytes ¼ 1,073,741,824 bytes

1024 GB ¼ 210 GB ¼ 240 bytes ¼ 1,099,511,627,776


Terabyte TB
bytes

1024 TB ¼ 210 TB ¼ 250 bytes ¼ 1,125,899,906,842,624


Petabyte PB
bytes

1024 PB ¼ 210 PB ¼ 260 bytes ¼


Exabyte EB
1,152,921,504,606,846,976 bytes

1024 EB ¼ 210 EB ¼ 270 bytes ¼


Zettabyte ZB
1,180,591,620,717,411,303,424 bytes

Apago PDF Enhancer


Every letter, number, or special symbol (such as * or {) on your keyboard is encoded as a
sequence of bits, each having a unique representation. The most commonly used
encoding scheme on personal computers is the seven-bit American Standard Code
for Information Interchange (ASCII). The ASCII data set consists of 128 characters,
numbered 0 through 127. (Note that 27 ¼ 128 and 28 ¼ 256.) That is, in the ASCII data
set, the position of the first character is 0, the position of the second character is 1, and so
on. In this scheme, A is encoded as 1000001. In fact, A is the 66th character in the ASCII
character code, but its position is 65 because the position of the first character is 0.
Furthermore, 1000001 is the binary representation of 65. The character 3 is encoded as
0110011. For a complete list of the printable ASCII character set, refer to Appendix C.

The number system that we use in our daily life is called the decimal system or base 10.
Because everything inside a computer is represented as a sequence of 0s and 1s, that
is, binary numbers, the number system that a computer uses is called binary or base 2.
We indicated in the preceding paragraph that the number 1000001 is the binary
representation of 65. Appendix D describes how to convert a number from base 10 to
base 2 and vice versa. Appendix D also describes how to convert a number between
base 2 and base 16 (hexadecimal) and between base 2 and base 8 (octal).

Inside the computer, every character is represented as a sequence of eight bits, that is, as a
byte. Because ASCII is a seven-bit code, you must add 0 to the left of the ASCII
encoding of a character. Hence, inside the computer, the character A is represented as
01000001, and the character 3 is represented as 00110011.
8 | Chapter 1: An Overview of Computers and Programming Languages

Other encoding schemes include Unicode, which is a more recent development.


Unicode consists of 65,536 characters. To store a Unicode character, you need two
bytes. Java uses the Unicode character set. Therefore, in Java, every character is repre-
sented as a sequence of 16 bits, that is, 2 bytes. In Unicode, the character A is represented
as 0000000001000001.
The ASCII character set is a subset of Unicode; the first 128 characters of Unicode are the
same as the characters in ASCII. If you are dealing with only the English language, the
ASCII character set is sufficient to write Java programs. The advantage of the Unicode
character set is that symbols from languages other than English can be handled easily.

Evolution of Programming Languages


The most basic computer language, machine language, provides program instructions in
bits. Even though most computers perform the same kinds of operations, the designers of
different CPUs sometimes choose different sets of binary codes to perform those opera-
tions. Therefore, the machine language of one computer is not necessarily the same as the
machine language of another computer. The only consistency among computers is that in
any computer, all data are stored and manipulated as a binary code.
Early computers were programmed in machine language. To see how instructions are
written in machine language, suppose you want to use the equation:
Apago PDF Enhancer
wages = rate  hours
to calculate weekly wages. Assume that the memory locations of rate, hours, and
wages are 010001, 010010, and 010011, respectively. Further suppose that the binary
code 100100 stands for load, 100110 stands for multiplication, and 100010 stands for
store. In machine language, you might need the following sequence of instructions to
calculate the weekly wages:
100100 010001
100110 010010
100010 010011

To represent the weekly wages equation in machine language, the programmer had to
remember the machine language codes for various operations. Also, to manipulate data,
the programmer had to remember the locations of the data in main memory. Remem-
bering specific codes made programming difficult and error prone.
Assembly languages were developed to make the programmer’s job easier. In assembly
language, an instruction is an easy-to-remember form called a mnemonic. Table 1-2
shows some examples of instructions in assembly language and their corresponding
machine language code.
Evolution of Programming Languages | 9

TABLE 1-2 Examples of Instructions in Assembly Language and Machine Language


1
Assembly Language Machine Language
LOAD 100100

STOR 100010

MULT 100110

ADD 100101

SUB 100011

Using assembly language instructions, you can write the equation to calculate the weekly
wages as follows:
LOAD rate
MULT hours
STOR wages

As you can see, it is much easier to write instructions in assembly language. However, a
computer cannot execute assembly language instructions directly. The instructions first
have to be translated into machine language. A program called an assembler translates
the assembly language instructions into machine language.
Apago PDF Enhancer
Assembler: A program that translates a program written in assembly language into an
equivalent program in machine language.
Moving from machine language to assembly language made programming easier, but a
programmer was still forced to think in terms of individual machine instructions. The
next step toward making programming easier was to devise high-level languages that
were closer to spoken languages, such as English and Spanish. Basic, FORTRAN,
COBOL, Pascal, C, C++, and Java are all high-level languages. You will learn the
high-level language Java in this book.
In Java, you write the weekly wages equation as follows:
wages = rate * hours;

The instruction written in Java is much easier to understand and is self-explanatory to a


novice user who is familiar with basic arithmetic. As in the case of assembly language,
however, the computer cannot directly execute instructions written in a high-level
language. To run on a computer, these Java instructions first need to be translated into
an intermediate language called bytecode and then interpreted into a particular machine
language. A program called a compiler translates instructions written in Java into
bytecode.
Compiler: A program that translates a program written in a high-level language into the
equivalent machine language. (In the case of Java, this machine language is the bytecode.)
10 | Chapter 1: An Overview of Computers and Programming Languages

Recall that the computer understands only machine language. Moreover, different types
of CPUs use different machine languages. To make Java programs machine indepen-
dent, that is, able to run on many different types of computer platforms, the designers of
Java introduced a hypothetical computer called the Java Virtual Machine (JVM). In
fact, bytecode is the machine language for the JVM.

In languages such as C and C++, the compiler translates the source code directly into the
machine language of your computer’s CPU. For such languages, a different compiler is
needed for each type of CPU. Therefore, programs in these languages are not easily
portable from one type of machine to another. The source code must be recompiled for
each type of CPU. To make Java programs machine independent and easily portable, and
to allow them to run on a Web browser, the designers of Java introduced the Java Virtual
Machine (JVM) and bytecode as the (machine) language of this machine. It is easier to
translate a bytecode into a particular type of CPU. This concept is covered further in the
following section, Processing a Java Program.

Processing a Java Program


Java has two types of programs—applications and applets. The following is an example of
Apago PDF Enhancer
a Java application program:
public class MyFirstJavaProgram
{
public static void main(String[] args)
{
System.out.println("My first Java program.");
}
}
At this point you need not be too concerned with the details of this program. However, if
you run (execute) this program, it will display the following line on the screen:
My first Java program.

Recall that a computer can understand only machine language. Therefore, in order to run
this program successfully, the code must first be translated into the machine language. In
this section we review the steps required to execute programs written in Java.
To process a program written in Java, you carry out the following steps, as illustrated in
Figure 1-3.
1. You use a text editor, such as Notepad, to create (that is, type) a
program in Java following the rules, or syntax, of the language. This
program is called the source program. The program must be saved in
a text file named ClassName.java, where ClassName is the name of
the Java class contained in the file. For example, in the Java program
Exploring the Variety of Random
Documents with Different Content
The magazine relates further, that “scarcity at
home” had induced a greater number of Highlanders
than usual to come to Edinburgh for “harvest work.”
The harvest, however, was not ready. They had
nothing to live upon. “Contributions were set on foot,
to give them two meals a day at the poorhouse; and,
on the evening of September 21, after a sermon
suitable to the occasion by Mr. Whitefield, a
collection was made for them, in the Orphan Hospital
Park, which amounted to £60 11s. 4d. sterling, of
which half a guinea was given by Mr. Whitefield
himself” (p. 465).

To these items of intelligence may be added the


following from the Edinburgh Courant: “During his
stay, Mr. Whitefield preached, morning and evening,
in the Orphan Hospital Park, not excepting the
evening of the day on which he arrived, or the
morning of that on which he departed. As he was
frequently very explicit in opening the miseries of
popish tyranny and arbitrary power, and very warm
in exhorting his hearers to loyalty and courage at
home, and in stirring them up to pray for the success
of his Majesty’s forces, we have reason to believe
that his visit, at this juncture, has been particularly
useful.”
In 1756, a considerable number of Wesley’s
preachers and Societies were strongly inclined to
declare themselves Dissenters. Charles Wesley was
excessively annoyed; and, as soon as his brother’s
annual conference was ended, he set out to entreat
the Methodists “to continue steadfast in the
communion of the Church of England.” Throughout
life, Whitefield was a peace-maker, and, on his return
from Scotland, he rendered service for which Charles
Wesley was profoundly thankful. Under the date of
Friday, October 8, Charles wrote:—
“Returning to Leeds, I met my brother Whitefield, and
was much refreshed by the account of his abundant
labours. I waited on him in our Room, and gladly sat under
his word.”

Again: “Sunday, October 10. At Birstal, my congregation


was less by a thousand or two, through George Whitefield
preaching to-day at Haworth.”

“Monday, October 11. Hearing Mr. Whitefield and


Mr. Grimshaw were returning to our watch-night, I waited
for them at their lodgings, with zealous, humble, loving
Mr. Crook. It rained so hard, that Mr. Whitefield was
agreeably surprised, at eight, to find our House as full as it
could cram. They forced me to preach first; which I did
from Zech. xiii.: ‘The third part I will bring through the fire.’
My brother George seconded me in the words of our Lord:
‘I say unto all, Watch.’ The prayers and hymns were all
attended with a solemn power. Few, if any, went
unawakened away.”
“Manchester, Monday, October 25. Here I rejoiced to
hear of the great good Mr. Whitefield has done in our
Societies. He preached as universally as my brother. He
warned them everywhere against apostacy; and strongly
insisted on the necessity of holiness after justification,
illustrating it with this comparison: ‘What good will the
king’s pardon do a poor malefactor dying of a fever? So,
notwithstanding you have received forgiveness, unless the
disease of your nature be healed by holiness, ye can never
be saved.’ He beat down the separating spirit, highly
commended the prayers and services of our Church,
charged our people to meet their bands and classes
constantly, and never to leave the Methodists, or God would
leave them. In a word, he did his utmost to strengthen our
hands, and deserves the thanks of all the churches, for his
abundant labour of love.” 411

The author of “The Life and Times of the


Countess of Huntingdon” states, that, in his
itinerancy through Lancashire, Whitefield was
accompanied by the Revs. Messrs. Grimshaw,
Ingham, and Milner, and that, among other places,
they visited Manchester, Stockport, and Chinley. 412
From an old manuscript ‘History of Methodism in
Leigh,’ it appears, that Whitefield also visited
Shackerley, where, at that time, a large number of
Unitarians were located, the disciples of Dr. Taylor,
the divinity tutor of the Unitarian Academy at
Warrington. The writer relates, that, Whitefield
preached on Shackerley Common, and that a man, a
mile distant, leaning upon a gate, distinctly heard
many of his sentences, was convinced of sin, and
soon converted.

Whitefield’s own account of his labours in


Yorkshire, Lancashire, and Cheshire, is extremely
meagre. On his return to London, from what he calls
his “thousand miles’ northern circuit,” 413 he wrote to
the Countess of Huntingdon, as follows:—
“London, October 27, 1756.

“I wrote you a few lines, not long ago, from Leeds.


Since then, I have been in honest Mr. Grimshaw’s and
Mr. Ingham’s rounds, preaching upon the mountains to
many thousands. One, who was awakened three years ago,
is gone to heaven, and desired to be buried in the spot
where she was converted. The sacrament at Mr. Grimshaw’s
was awful; and the watch-night at Leeds exceeding solemn.
I would have continued my circuit, but I found that
preaching so frequently in those cold districts was bringing
on my last year’s disorder. Being, therefore, grown very
prudent, I am come to open our new chapel in Tottenham
Court Road. Lord, what am I, that Thou shouldest suffer
me to put a pin in Thy tabernacle! Never did I know the
fields more ready unto harvest, than I have seen them in
the north.”

Builders, in former days, were more expeditious


than at present. Whitefield’s chapel was neither a
small nor a flimsy structure, and yet, only half a year
after its commencement, it was ready for being
opened!
Whitefield was now in his “winter quarters,”
where he remained for the next six months;—an
unusually long period for him to spend in London.
The following extracts from his letters will, it is
hoped, interest the reader:—
“London, November 17, 1756. At Tottenham Court
chapel, we have had some glorious earnests of future
blessings. My constant work now is preaching about fifteen
times a week. This, with a weak appetite, want of rest, and
much care lying upon my mind, enfeebles me. But the joy
of the Lord is my strength; and my greatest grief is, that I
can do no more for Him, who has done and suffered so
much for me.”

The Rev. Henry Venn was now one of the most


active clergymen of the Church of England. Besides
being curate of Clapham, he held three lectureships
in the city. His regular duties consisted of a full
service at Clapham on the Sunday morning; a
sermon, in the afternoon, at St. Alban’s, Wood
Street; and another, in the evening, at St. Swithin’s,
London-stone. On Tuesday morning, a sermon at
St. Swithin’s; on Wednesday morning, at seven
o’clock, at St. Antholin’s; and, on Thursday evening,
at Clapham. 414 Whitefield had become acquainted
with him, and wrote to Hervey, at Weston-Favel, as
follows:—
“London, December 9, 1756. I hope that my dear friend
prospers both in soul and body. Conviction and conversion
work goes on here. Lord, keep us from tares! All is well at
Clapham. I have expounded there twice. God has met with
us in our new building.”

To the Rev. Aaron Burr, the President of New


Jersey College, for whom he had done his best to
obtain a D.D. degree from the Edinburgh University,
Whitefield wrote:—
“London, December 9, 1756. Night and day, our hands
are lifted up for dear America; but, I fear, we are to be
brought into far greater extremity, both at home and
abroad, ere deliverance comes. I am sorry you have not
your degree. It is ready, if testimonials were sent from
those who know you. This not being done, it looks as
though the character given you on this side the water was
not justly founded. I wish you would write oftener. How
glad would I be to see America, but my way is hedged up.
The awakening both in town and country continues. More
ministers are coming out to preach the gospel. I am
strengthened to preach fourteen times a week, and I trust
it is not in vain.”

“London, December 15, 1756. Last Sunday, in the new


chapel, there was a wonderful stirring among the dry
bones. Some great people came, and begged they might
have a constant seat: an earnest this, I believe, of more
good things to come.”

“London, December 30, 1756. God is doing wonders in


the new chapel. Hundreds went away last Sunday morning,
who could not come in. On Christmas Day, and last Tuesday
night (the first time of burning candles), the power of the
Lord was present, both to wound and to heal. A
neighbouring doctor has baptized the place, calling it
‘Whitefield’s Soul-Trap.’ I pray that it may be a soul-trap
indeed, to many wandering sinners. Abundance of people
round about, I hear, are much struck. O for humility! O for
gratitude! O for faith! Wherefore should I doubt? Surely
Jesus will carry me through, and help me to pay the
workmen.”

In such a spirit, Whitefield ended another year of


his eventful life. He was now attracting to his
meeting-house some of the “great people” of the
western parts of the metropolis; and, yet, his
preaching was as faithful as ever. Let the following
serve as a specimen:—
“Woe unto you, who are at ease in Zion, and, instead of
staying to be tempted by the devil, by idleness, self-
indulgence, and making continual provision for the flesh
even tempt the devil to tempt you! Woe unto you, who, not
content with sinning yourselves, turn factors for hell, and
make a trade of tempting others to sin! Woe unto you, who
either deny Divine revelation, or never use it, but to serve a
bad turn! Woe unto you, who sell your consciences, and
pawn your souls, for a little worldly wealth or honour! Woe
unto you, who climb up to high places, in Church or State,
by corruption, bribery, extortion, cringing, flattery, or
bowing down to, and soothing the vices of those by whom
you expect to rise! Woe unto you! for, whether you will own
the relation or not, you are of your father the devil; for the
works of your father you do. I tremble for you. How can
you escape the damnation of hell?” 415
Such preaching was needed in the days of
Whitefield, and it is equally needed now. For lack of
it, thousands, even in churches and chapels, are
dreaming elysian dreams, while in the utmost danger
of perishing.

In more respects than one, the year 1756 was a


year of turmoil; but the Methodists were not without
their friends. One pamphlet, published during the
year, undesignedly in Whitefield’s favour, had the
following inordinately long title: “The Great Secret
Disclosed; or an Infallible Salve for Opening the Eyes
of all such as the God of this World has Blinded; by
once applying which, the Person will be able to see
the true cause why Religion decays amongst us, and
why Methodism started up, and daily increases; and,
with it, all that train of Vice and Immorality so
common to be met with in every corner of the
Nation; with an effectual method for bringing about a
Reformation by destroying Methodism.” (8vo. 52 pp.)

The title shews that the pamphlet was not


intended to promote the interests of Methodism. Like
Balaam, the writer purposed to curse his enemies,
and, yet, he blessed them. Two extracts must suffice.
“It is generally reported that Mr. Whitefield has a
hundred thousand followers, most of whom, before his
preaching, were the vilest of mankind, but are now sober
and religious persons, good members of society, and good
subjects of the king. It is also said that Mr. Wesley’s
preaching has had as good an effect on the like numbers;
most of whom have been brought to be members of the
Church of England; namely, to baptize their children, and to
receive the sacrament there: for, as he and his brother
preach only betimes in a morning and in the evening, and
order their followers to go, the other parts of the day, to
their respective places of worship; and, as most of them
went to no place of worship before, and as such always
looked upon themselves as Church people, they go,
forenoon and afternoon, to its services. Thus, instead of
weakening the Church, by taking members from it, the
Methodists have strengthened it, by adding thousands of
members to it; for the Methodists, properly speaking, are
no Church, having no ordinances administered among
them. 416

“Mr. Whitefield seems to have been the first whom the


clergy of a whole nation agreed to prevent preaching,
without ever proving that he had broken either the
ecclesiastical, moral, or national law. His chief crime was
that he appeared to be in earnest both in reading prayers
and preaching.”

The author’s “effectual method” to destroy


Methodism was: 1. That the clergy should “treat the
Methodists as Church members, and not molest them
in performing the duties of religion;” and, 2. They
should “out-pray and preach them.”

Another pamphlet, of the same Balaam-like


character, was published in 1756, with the title,
“Methodism Displayed, and Enthusiasm Detected;
intended as an Antidote against, and a Preservative
from, the delusive Principles and unscriptural
Doctrines of a Modern Sett of seducing Preachers;
and as a Defence of our Regular and Orthodox
Clergy, from their unjust Reflections.” (8vo. 36 pp.)

This was an enigmatical production. After giving


to the “Modern Sett of seducing Preachers” a number
of hard names, the author writes as follows:—
“If for a steady adherence and firm attachment to the
doctrines of the Church of England I am accounted a
Methodist, I am content. May I live and die a Church of
England Methodist! A Methodist! Why, really it is a simple
and inoffensive name, and I do not see much reason to be
ashamed of it. The world does not usually fix this apellation
upon persons of an openly wicked and scandalously sinful
life. A gaming, pleasure-taking, playhouse-frequenting
person, who lives in debauchery and excess of drinking, is
sure to escape the name of Methodist. Nor has a minister
that name given him, who, notwithstanding his solemn
declarations, subscriptions, and oaths to assent to and to
abide by the Articles of our Church, preaches contrary to
them,—denies the fall of man,—original sin,—contends for
justification by works, instead of by faith,—is an enemy to
the doctrine of imputed righteousness,—from whose
sermons you seldom hear the name of Jesus, or the agency
and influence of the Holy Spirit, unless utterly to deny,
inveigh against, and explode all spiritual inspiration and
inward feelings: these and such-like preachers escape from
the imputation of Methodism. So, again, that decent,
regular person, who, freed from the irksome care of souls,
comfortably lolls in his chariot, thinks it is time for him to
have done with praying and preaching, and, therefore, has
left off trade, and is content with a bare £1000 per annum
Church preferment; he, who loves the Church, rails at your
popular, mob-driving preachers, and is sure they would not
take half the pains they do, if views of money-getting were
not at the bottom,—this sort of gentleman stands very clear
of being deemed a Methodist.”

Another extract must be given. The picture it


draws was not a caricature.
“Take knowledge of that thing. He is parson of St――’s
church. Lest the people should be seduced and deceived by
hearing the doctrines of the Church of England preached,
he denies these true ministers 417 the pulpit, and says they
are Enthusiasts; and the people, as ignorant as himself, join
the cry. An enthusiast! What is that? Oh, ’tis the cant word
of the day for the many-headed monster, the bugbear of
the times. ‘Ah,’ says a constant church-goer, ‘I heard one of
those preachers at our church. He preached such a sermon!
It was almost an hour long, and he said downright, that all
unconverted people were in a state of damnation, and
would go to hell, if they did not believe on the Lord Jesus!
Truly, he set the parish in an uproar, for we are not used to
such sort of preaching. Thank God for a good parson, say I;
for the Sunday after our parson (God bless him!) preached
a sermon against such doctrine; and, though he was no
longer than a quarter of an hour, he made us all easy
again. He told us we were in no danger of going to hell,
and that there was no fear of our being damned, for we
were all good Christians, if we paid every one their own,
and did as we would be done by.’”
Whitefield began the year 1757 with mingled
feelings. He rejoiced because of the prosperity of the
work of God; he was distressed by political and
Church contentions; and he was full of care
respecting his distant Orphan House. Hence the
following selections from his letters:—
“London, January 12, 1757.

“A wide door seems to be opening at Tottenham Court


chapel. The word flies like lightning in it. O that it may
prove a Bethel—a house of God—a gate of heaven! I
believe it will. As the awakening continues, I have some
hopes that we are not to be given up. Alas! alas! we are
testing and contesting, while the nation is bleeding to
death. We are condemning this and that; but sin, the great
mischief-maker, lies unmolested, or rather encouraged by
every party.”

To his housekeeper at Bethesda, Whitefield


wrote:—
“London, February 5, 1757.

“Tottenham Court chapel is made a Bethel, and the


awakening increases every day. O that it were so in
Georgia! Surely the great Shepherd and Bishop of souls will
bless you, for taking care of the lambs in that distant
wilderness. Mr. P.’s leaving Bethesda sadly distresses me. I
desire that all, who are capable, may be put out, and the
family reduced as low as possible, till the war is over, and
the institution out of debt. Lord, remember me and all my
various concerns! God bless and direct you in every step!
He will, He will. What is to become of us here, God only
knows. A year perhaps may determine. The best sign is,
that the awakening continues.”

Four years ago, Whitefield had published his


pamphlet against Zinzendorf and the Moravians.
Things since then had altered for the better. Hence
the following:—
“London, February 17, 1757.

“O to be an Israelite indeed, in whom there is no guile!


Simplicity and godly sincerity are all in all. A want of this, I
fear, has led the Count into all his mistakes. With great
regret, I speak or write of any people’s weaknesses; but I
thought Divine Providence called me to publish what you
mention. The Redeemer gave it His blessing. I do not find
that their fopperies are continued, and I hear also that they
have discharged many debts.”

At this period, one of the most popular of the


metropolitan actors was a young man of twenty-
seven—Edward Shuter, born in a cellar adjoining
Covent Garden—“the offspring of a chairman on the
one side, and of an oyster-woman on the other.” He
had been a marker at a billiard table, and a tapster
at a public-house. He had joined a company of
strolling players, among whom, by his drolleries and
good nature, he soon acquired the appellation of
Comical Ned. At length, Garrick engaged him at
Drury Lane. “He was so thoroughly acquainted,” says
a critical authority, “with the vis comica, that he
seldom called in those common auxiliaries, grimace
and buffoonery, but rested entirely on genuine
humour. He had strong features, and a peculiar turn
of face, which, without any natural deformity, he
threw into the most ridiculous shapes.” His
facetiousness was irresistible. Being in disgrace, on
one occasion, for some irregularity in his
performance, the audience demanded an apology,
and vehemently called for him, after he had made
his exit. At the time they were vociferating “Shuter!
Shuter!” an actress happened to be the only person
on the stage, when Shuter, poking out his comical
face, from behind one of the scenes, called out,
“Don’t shoot her!” which restored the good temper of
the spectators for the rest of the evening.

It is a strange fact, that, this remarkable man


—“the greatest comic genius I ever saw,” said
Garrick 418—was now one of Whitefield’s constant
hearers. Hence the following to the Countess of
Huntingdon:—
“London, March 2, 1757.

“Not many mighty, not many noble, are called; but some
come to hear at Tottenham Court. Shuter, the player,
always makes one of the auditory, and, as I hear, is much
impressed, and brings others with him.”
The good Countess, from this, was led to take an
interest in Shuter’s welfare. In a letter, to Lady Fanny
Shirley, she says:—
“I have had a visit from Shuter, the comedian, whom I
saw in the street, and asked to call on me. He was
wonderfully astonished when I announced my name. We
had much conversation; but he cannot give up his
profession for another more reputable. He spoke of
Mr. Whitefield with great affection, and with admiration of
his talents. He promised to come some other time, when he
had more leisure for conversation. Poor fellow! I think he is
not far from the kingdom.” 419

It is related that on one occasion, when Shuter


was in the height of his reputation, as the
representative of “Ramble,” and while he was seated
in a pew exactly in front of the pulpit of Tottenham
Court chapel, Whitefield was inviting sinners to the
Saviour, with his accustomed earnestness, and, at
the moment, caught Shuter’s eye, and exclaimed,
“And thou, poor Ramble, who hast long rambled
from Him, come thou also. Oh, end thy ramblings by
coming to Jesus!” 420 This, certainly, was more
personal than polite; but poor Shuter bore it. Long
after, when his friends used to rate him as a
Methodist, he would say, “A precious method is mine!
No, I wish I were; for if any be right, the Methodists
are.” 421

On Monday, April 25, Whitefield set out for


Scotland. Sixteen days afterwards, he arrived in
Edinburgh, where he at once commenced preaching
in his old open-air cathedral, the Orphan Hospital
Park, and, for nearly a month, preached twice a day,
morning and evening, “to very numerous
audiences.” 422

In all respects, this was a memorable visit. A


week after Whitefield’s arrival, the General Assembly
of the Church of Scotland met at Edinburgh, Charles,
the ninth Baron of Cathcart, being his Majesty’s
commissioner,—“a nobleman no less distinguished
for the virtues which adorn private life, than he was
eminent for all those which exalt a public character.
In the capacity of father, husband, and friend, his
lordship had few equals, and was exceeded by none
in discharging, with dignity and ability, the duties of
the high stations in which he had been placed by his
sovereign.” 423 The Rev. William Leechman, D.D.,
Professor of Divinity in the University of Glasgow,
was chosen moderator. Leechman was a celebrated
preacher, a popular lecturer, “a man,” says Sir Henry
Moncreiff, “of primitive and apostolic manners,
equally distinguished by his love of literature and his
liberal opinions.” 424 The sessions of the Assembly
were continued from the 19th to the 30th of May,
and Whitefield attended every one of them. “On
Saturday, the 28th, he dined, by invitation, with the
commissioner, (though not at the same table,) and
said grace after dinner.” 425 Much important business
was transacted. A committee was appointed “to
consider the laws relating to the election and
qualifications of members of Assembly.” An act of the
Synod of Argyle, “that the use of sermons on the
Saturday before, and Monday after, dispensing the
sacrament of the Lord’s supper, be discontinued in all
time coming,” occasioned a long debate, but was
ultimately approved. A minister was arraigned for
attending a theatre. A second minister, accused of
the same offence, pleaded “that he had gone to the
playhouse only once, and endeavoured to conceal
himself in a corner.” Lengthened discussions
followed, and a resolution was passed, “earnestly
recommending the several Presbyteries to take care
that none of their ministers do, upon any account,
attend the theatre.” Another resolution was
approved, forbidding “simoniacal practices.” Several
cases of “double presentation” to livings had to be
decided. A scandal respecting the Rev. William Brown
occupied considerable time; but the result was, the
Assembly “assoilzied Mr. Brown.” Appeals and
petitions from ministers were heard, and resolutions
were passed respecting the fund for ministers’
widows, and “anent ministers making agreements
with their heritors concerning the extent of their
stipends.”
Listening to learned and long debates on these
and kindred subjects was Whitefield’s daily recreation
between his morning and evening preachings.

On June 6, he set out for Glasgow, where he


continued several days. 426 An extract from the Scots’
Magazine for 1757, page 322, may be welcome:—
“In a letter from Glasgow, of June 19, we have the
following account: ‘On Monday last, the Rev. Mr. Whitefield,
at the desire of several of our magistrates, preached a
sermon for the benefit of the poor of this city, from Mark
vi. 34. At the conclusion of his discourse, he pressed the
charity with many solid arguments. A number of the
magistrates and elders stood up to collect at the outside of
the congregation; who went away with regularity, and gave
their contributions very cheerfully. The whole amounted to
£58 sterling, which is all to be applied to the relief of our
poor. After the sermon, the magistrates waited on
Mr. Whitefield, and thanked him for this good office, which
has given great and general satisfaction.’”

At Whitefield’s farewell sermon in the Orphan


Hospital Park, Edinburgh, there was a young
Scotchman present, who afterwards became one of
Wesley’s most faithful and sturdy itinerants. Thomas
Rankin, born at Dunbar, was now resident at Leith,
and came to Edinburgh to hear the great preacher.
He writes:—
“I had often before had thoughts of hearing
Mr. Whitefield; but so many things had been said to me of
him, that I was afraid I should be deceived. He preached in
the field adjoining the Orphan House yard. His text was
Isaiah xxxiii. 13–17. The sermon exceeded all the sermons I
ever heard. About the middle of it, I ventured to look up,
and saw all the crowds around Mr. Whitefield bathed in
tears. I listened with wonder and surprise, and had such a
discovery of the plan of salvation as I had never known
before. I was astonished at myself that I had listened to the
idle tales concerning him, and thereby have been kept from
hearing a burning and shining light, who had been
instrumental in the hand of God for the good of so many
thousands of souls. When I understood he was about to
leave Edinburgh, I was distressed. I remembered more of
that sermon than of all the sermons I had ever heard. I had
a discovery of the unsearchable riches of the grace of God
in Christ Jesus; as also of how a lost sinner was to come to
God, and obtain mercy through the Redeemer. From this
time, I was truly convinced of the necessity of a change of
heart.” 427

As already stated, Thomas Rankin became one of


Wesley’s most valuable preachers. His labours, both
in England and in America, were of great
importance; and, if no other end had been
accomplished by Whitefield’s present visit to the
Scotch metropolis, the conversion of Rankin was an
ample compensation for all his toil and travelling.

Whitefield’s account of his visit is brief and


imperfect. He writes on May 31st: “Attendance upon
the Assembly, and preaching, have engrossed all my
time.” In another letter, dated Glasgow, June 9, 1757,
he remarks:—
“At Edinburgh, I was so taken up all day, and kept up so
late at night, that writing was almost impracticable. Surely,
my going thither was of God. I came there on the 12th of
May, and left the 6th of June, and preached just fifty times.
To what purpose, the great day will discover. I have reason
to believe to very good purpose. Being the time of the
General Assembly, (at which I was much pleased,) many
ministers attended, perhaps a hundred at a time. Thereby
prejudices were removed, and many of their hearts were
deeply impressed. About thirty of them, as a token of
respect, invited me to a public entertainment. The Lord
High Commissioner also invited me to his table; and many
persons of credit and religion did the same in a public
manner. Thousands and thousands, among whom were a
great many of the best rank, daily attended on the word
preached; and the longer I stayed, the more the
congregations and Divine influence increased. Twice I
preached in my way to Glasgow; and, last night, opened
my campaign here. The cloud seems to move towards
Ireland. How the Redeemer vouchsafes to deal with me
there, you shall know hereafter.”

Whitefield’s previous visit to Ireland had been


greatly blessed. The people longed to give him
another welcome. One section of his converts had
laid the foundation of a prosperous Moravian church.
Another had formed a Baptist congregation. A
number of others were scattered, and needed
encouragement. 428 He went to help them, and his
visit was memorable. To the day of his death, a deep
scar in his head was a memento of it. 429 He shall tell
his own story.
“Dublin, June 30, 1757.

“The door is open, and indeed the poor Methodists want


help. Here, in Dublin, the congregations are very large, and
very much impressed. The Redeemer vouchsafes to me
great freedom in preaching, and arrows of conviction fly
and fasten. One of the bishops told a nobleman, he was
glad I was come to rouse the people. The nobleman himself
told me this yesterday. Alas! that so few have the ambition
of coming out to the help of the Lord against the mighty.
Not one clergyman, in all Ireland, is as yet stirred up to
come out singularly for God. Pity, Lord, for Thy mercy’s
sake! I think God will yet appear for the Protestant interest.
My route now is to Athlone, Limerick, and Cork; and to
return here about July 21st.”

“Dublin, July 3, 1757.

“The infinitely condescending Jesus still vouchsafes to


follow the chief of sinners with His unmerited blessing. In
Scotland, His almighty arm was most powerfully revealed;
and here, in Dublin, many have begun to say, ‘What shall
we do to be saved?’ Congregations are large, and very
much impressed. All sorts attend, and all sorts seem to be
affected. I should be glad to come to London, but cannot in
conscience as yet. Not one minister, either in the Church or
among the Dissenters, in this kingdom, as far as I can hear,
appears boldly for God. To-morrow, therefore, I purpose to
set out for Athlone, Limerick, and Cork. God only knows
where, after that, will be the next remove. Perhaps to
London; perhaps to the north of Ireland, which, I hear, lies
open for the gospel. Winter must be the London harvest. O
for more labourers, who will account the work itself the
best wages!

“July 5. Since writing the above, I have been in the


wars; but, blessed be God, am pretty well recovered, and
going on my way rejoicing. Pray hard.”

“July 9, 1757.

“You have heard of my being in Ireland, and of my


preaching to large and affected auditories in Mr. Wesley’s
spacious room. When here last, I preached in a more
confined place on the week-days, and once or twice
ventured out to Oxmanton Green, a large place like
Moorfields, situated very near the barracks, where the
Ormond 430 and Liberty (that is, high and low party) Boys
generally assemble every Sunday, to fight with each other.
The congregations then were very numerous, the word
seemed to come with power, and no noise or disturbance
ensued. This encouraged me to give notice, that I would
preach there again last Sunday afternoon.

“I went through the barracks, the door of which opens


into the Green, and pitched my tent near the barrack walls,
not doubting of the protection, or at least interposition, of
the officers and soldiery, if there should be occasion. But
how vain is the help of man! Vast was the multitude that
attended. We sang, prayed, and preached, without much
molestation; only, now and then, a few stones and clods of
dirt were thrown at me. It being war time, I exhorted my
hearers, as is my usual practice, not only to fear God, but
to honour the best of kings; and, after the sermon, I
prayed for success to the Prussian arms. 431
“All being over, I thought to return home the way I
came; but, to my great surprise, access to the barracks was
denied, so that I had to go near half a mile, from one end
of the Green to the other, through hundreds and hundreds
of papists, etc. Finding me unattended, (for a soldier and
four Methodist preachers, 432 who came with me, had
forsook me and fled,) I was left to their mercy. Their mercy,
as you may easily guess, was perfect cruelty. Vollies of hard
stones came from all quarters, and every step I took, a
fresh stone struck, and made me reel backwards and
forwards, till I was almost breathless, and was covered all
over with blood. My strong beaver hat served me, as it
were, for a skullcap for a while; but, at last, that was
knocked off, and my head left quite defenceless. I received
many blows and wounds; one was particularly large near
my temples. Providentially, a minister’s house stood next
door to the Green. With great difficulty I staggered to the
door, which was kindly opened to, and shut upon me. Some
of the mob, in the meantime, broke part of the boards of
the pulpit into splinters, and beat and wounded my servant
grievously in his head and arms, and then came and drove
him from the door of the house where I had found a
refuge.

“For a while, I continued speechless, expecting every


breath to be my last. Two or three of my friends, by some
means, got admission, and kindly washed my wounds. I
gradually revived, but soon found the lady of the house
desired my absence, for fear the house should be pulled
down. What to do, I knew not, being near two miles from
Mr. Wesley’s place. Some advised one thing, and some
another. At length, a carpenter, one of the friends who
came in, offered me his wig and coat, that I might go off in
disguise. I accepted of them, and put them on, but was
soon ashamed of not trusting my Master to secure me in
my proper habit, and threw them off in disdain.
Immediately, deliverance came. A Methodist preacher, with
two friends, brought a coach; I leaped into it, and rode, in
gospel triumph, through the oaths, curses, and
imprecations of whole streets of papists, unhurt.

“None but those who were spectators of the scene can


form an idea of the affection with which I was received by
the weeping, mourning, but now joyful Methodists. A
Christian surgeon was ready to dress my wounds, which
being done, I went into the preaching place, and, after
giving a word of exhortation, joined in a hymn of praise and
thanksgiving to Him, who makes our extremity His
opportunity, and who stills the noise of the waves, and the
madness of the most malignant people.

“The next morning, I set out for Port Arlington, and left
my persecutors to His mercy, who out of persecutors has
often made preachers.” 433

The hard knocks Whitefield received from the


Dublin papists did not prevent the carrying out of his
plan to visit the towns already mentioned. Hence the
following:—
“Cork, July 15, 1757.

“Everywhere the glorious Emmanuel so smiles upon my


feeble labours, that it is hard to get away from Ireland. At
Port-Arlington, Athlone, Limerick, and this place, the word
has run and been glorified. Arrows of conviction seem to
fly; and the cup of many has been made to run over. I have
met with some hard blows from the Dublin rabble; but,
blessed be God! they have not destroyed me.”
In another letter, addressed to the Rev. John
Gillies, of Glasgow, and dated, “Wednesbury,
Staffordshire, August 7, 1757,” he wrote:—
“Though Mr. Hopper promised to write you an historical
letter, from Dublin, I cannot help dropping you a few lines
from this place. At Athlone, Limerick, Cork, and especially
at Dublin, where I preached near fifty times, we had
Cambuslang seasons. With the utmost difficulty, I came
away. The blows I received were like to send me where all
partings would have been over. But, I find, we are immortal
till our work is done.”

Whitefield found it difficult to get away; but it is a


notable fact that he never went again. This was his
last visit to Ireland! He went but twice, and both of
his visits put together were not of three months’
continuance. Wesley made twenty visits, most of
them of long duration. Ireland’s debt to Whitefield is
but small; but to Wesley great.

After an absence of about four months, Whitefield


got back to London. One of the first things that
claimed his attention was the business of his Orphan
House, which had recently been visited by the
governor of Georgia. The following was addressed to
his housekeeper:—
“London, August 26, 1757.
“I think myself happy, in finding you are satisfied in your
present situation. I would rather have you to preside over
the orphan family than any woman I know. I do not love
changes. Sometimes I wish for wings to fly over; but
Providence detains me here. 434 I fear a dreadful storm is at
hand. Lord Jesus, be Thou our refuge! At Dublin, I was like
to be sent beyond the reach of storms. A most blessed
influence attended the word in various parts of Ireland; and
here, in London, the prospect is more and more promising.
As to outward things, all is gloomy. I hope Bethesda will be
kept in peace. I am glad the governor has been to visit the
house. May God make him a blessing to the colony! I wish
you would let me know how the English children are
disposed of. I would fain have a list of black and white,
from time to time. Blessed be God for the increase of the
negroes! I entirely approve of reducing the number of
orphans as low as possible; and I am determined to take in
no more than the plantation will maintain, till I can buy
more negroes. Never was I so well satisfied with my
assistants as now.”

Whitefield’s stay in London was short.


Accompanied by the Revs. Martin Madan and Henry
Venn, he soon set out, on a six weeks’ journey, to
the west of England. Extracts from two of his letters
will furnish an idea of his spirit and his work.
“Exeter, September 28, 1757.

“Blessed be God! I can send you good news concerning


Plymouth. The scene was like that of Bristol, only more
extraordinary. Officers, soldiers, sailors, and the dockmen
attended, with the utmost solemnity, upon the word
preached. Arrows of conviction flew and fastened; and I left
all God’s people upon the wing for heaven. Blessed be the
Lord Jesus for ordering me the lot of a cast-out! I am glad
that Mr. Madan and Mr. Venn returned safe. May an
effectual door be opened for both! If so, they will have
many adversaries. If the weather should alter, I may be in
town before long; if not, I may range farther. This spiritual
hunting is delightful sport, when the heart is in the work.”

The next is taken from a letter to the Rev. John


Gillies. The “Counsellor” mentioned was Mr. Madan,
who, before his ordination, practised at the bar.
“London, October 16, 1757.

“Reverend and very dear Sir,—I thank you for your


sympathising letter sent to Ireland. The Friend of sinners
stood by me, or I had been stoned to death. Stones were
thrown at me, not for speaking against the papists in
particular, but, for exciting all ranks to be faithful to King
Jesus, and to our dear sovereign King George, for His great
name’s sake.

“Seven gospel ministers were together at Bristol, when


the Counsellor preached. We have had blessed seasons, for
these six weeks last past, at Plymouth, Exeter, Bristol,
Gloucester, and Gloucestershire. This comes from my winter
quarters.”

Whitefield was again in London, where he


continued for seven months.

The “Counsellor,” the Rev. Martin Madan, was


now a red-hot evangelist. He had preached through
Hertfordshire, Bedfordshire, Buckinghamshire,
Warwickshire, Worcestershire, and
Gloucestershire. 435 The number of Methodist
clergymen was rather rapidly increasing. Besides
Whitefield, the Wesleys, Hervey, Grimshaw, Romaine,
Madan, Venn, Walker, and others already mentioned
in this biography, there were now the Rev. James
Stillingfleet, ultimately rector of Hotham, in
Yorkshire; the Rev. Mr. Downing, chaplain to the Earl
of Dartmouth; and the Rev. William Talbot, LL.D.,
vicar of Kineton, in Warwickshire, a man of
aristocratic family. 436 In this year, 1757, not fewer
than five of these earnest clergymen, Messrs. Walker,
Talbot, Downing, Stillingfleet, and Madan, at the
request of Lord Dartmouth, 437 had preached at
Cheltenham. 438 On three or four occasions,
Mr. Downing obtained the pulpit of the parish church;
but the rector and the churchwardens interposed,
and the zealous Methodist was excluded. Lord
Dartmouth then opened his own house for
preaching, twice a week; and, sometimes, the
seminary of Mr. Samuel Wells was used for the same
purpose. 439 In a letter to the Countess of
Huntingdon, his lordship wrote:—
“I wish your ladyship would use your influence with
Mr. Whitfield and Mr. Romaine to pay us a visit.
Mr. Stillingfleet has been obliged to return to Oxford, and I
know not where to direct to Mr. Madan or Mr. Venn.
Mr. Talbot has promised to come as soon as possible; and,
next month, I expect good Mr. Walker, of Truro. The rector
was so displeased with Mr. Downing preaching, and the
great crowds who flocked to hear him, that he excluded
him from the pulpit after three or four sermons, and
refused to admit Mr. Stillingfleet, though I said everything I
could to induce him to do so. Since then, I have opened my
house, but find it too small for the numbers who solicit
permission to attend. I have no hopes of again obtaining
the use of the parish church.”

Just at this time, Madan came to Cheltenham,


and was soon after joined by Venn, and by Maddock,
the latter the curate of Hervey, of Weston-Favel.
Contrary to the expectations of Lord Dartmouth, both
Madan and Venn were several times admitted to the
parish pulpit. Then came Whitefield, and an immense
crowd collected, expecting that he also would preach
in the church. Attended by Lord and Lady
Dartmouth, and by Messrs. Madan, Venn, Talbot, and
Downing, the renowned preacher proceeded to the
church door. They found it closed against them.
Whitefield, never at a loss for pulpits, mounted a
neighbouring tombstone, and preached. The Rev.
Henry Venn shall tell the remainder of the story. In a
letter to Lady Huntingdon, he wrote:—
“Under Mr. Whitefield’s sermon, many, among the
immense crowd that filled every part of the burial ground,
were overcome with fainting. Some sobbed deeply; others
wept silently; and a solemn concern appeared on the
countenance of almost the whole assembly. When he came
to impress the injunction in the text (Isaiah li. 1) his words
seemed to cut like a sword, and several in the congregation
burst out into the most piercing bitter cries. Mr. Whitefield,
at this juncture, made a pause, and then burst into a flood
of tears. During this short interval, Mr. Madan and myself
stood up, and requested the people to restrain themselves,
as much as possible, from making any noise. Twice
afterwards, we had to repeat the same counsel. O with
what eloquence, energy, and melting tenderness, did
Mr. Whitefield beseech sinners to be reconciled to God!
When the sermon was ended, the people seemed chained
to the ground. Mr. Madan, Mr. Talbot, Mr. Downing, and
myself found ample employment in endeavouring to
comfort those broken down under a sense of guilt. We
separated in different directions among the crowd, and
each was quickly surrounded by an attentive audience, still
eager to hear all the words of this life.

“The next day, a like scene was witnessed, when dear


Mr. Whitefield preached to a prodigious congregation from
Isaiah lv. 6. In the evening, Mr. Talbot preached at Lord
Dartmouth’s, to as many as the rooms would hold.
Hundreds crowded round his lordship’s residence, anxiously
expecting Mr. Whitefield to preach. Exhausted as he was
from his exertions in the morning, when he heard that
there were multitudes without, he stood upon a table near
the front of the house, and proclaimed the efficacy of the
Saviour’s blood to cleanse the vilest of the vile.

“Intelligence of the extraordinary power attending the


word soon spread, and the next day we had Mr. Charles
Wesley and many friends from Bristol, Gloucester,
Tewkesbury, Rodborough, and the villages in the
neighbourhood; but all loud weeping and piercing cries had
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books 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!

ebookgate.com

You might also like