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

Java Programming (MindTap Course List), 10th Edition Joyce Farrell - eBook PDF instant download

The document provides information about the 10th edition of the 'Java Programming' textbook by Joyce Farrell, available for download as an eBook PDF. It includes links to other related programming and educational resources, as well as details about the content structure of the textbook. The textbook covers various fundamental programming concepts, including methods, classes, data types, and exception handling.

Uploaded by

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

Java Programming (MindTap Course List), 10th Edition Joyce Farrell - eBook PDF instant download

The document provides information about the 10th edition of the 'Java Programming' textbook by Joyce Farrell, available for download as an eBook PDF. It includes links to other related programming and educational resources, as well as details about the content structure of the textbook. The textbook covers various fundamental programming concepts, including methods, classes, data types, and exception handling.

Uploaded by

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

Java Programming (MindTap Course List), 10th

Edition Joyce Farrell - eBook PDF download

https://ebooksecure.com/download/java-programming-mindtap-course-
list-10th-edition-ebook-pdf/

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


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

Java Programming 9th Edition Joyce Farrell - eBook PDF

https://ebooksecure.com/download/java-programming-ebook-pdf/

Programming Logic & Design, Comprehensive 9th edition


Joyce Farrell - eBook PDF

https://ebooksecure.com/download/programming-logic-design-
comprehensive-9th-edition-ebook-pdf/

Programming Logic and Design, Comprehensive 9th Edition


Joyce Farrell - eBook PDF

https://ebooksecure.com/download/programming-logic-and-design-
comprehensive-9th-edition-ebook-pdf/

Introduction to Java Programming, Comprehensive Version


10th edition- eBook PDF

https://ebooksecure.com/download/introduction-to-java-
programming-comprehensive-version-ebook-pdf/
Physics for Scientists and Engineers (MindTap Course
List) 10th Edition Serway - eBook PDF

https://ebooksecure.com/download/physics-for-scientists-and-
engineers-mindtap-course-list-ebook-pdf/

Business Law: Text & Exercises (MindTap Course List)


10th Edition Roger Leroy Miller - eBook PDF

https://ebooksecure.com/download/business-law-text-exercises-
mindtap-course-list-ebook-pdf/

Your Career: How to Make it Happen (MindTap Course


List) 10th Edition Lisa Owens - eBook PDF

https://ebooksecure.com/download/your-career-how-to-make-it-
happen-mindtap-course-list-ebook-pdf/

Interpersonal Conflict 10th Edition Joyce L. Hocker -


eBook PDF

https://ebooksecure.com/download/interpersonal-conflict-ebook-
pdf/

(eBook PDF) Murach's Java Programming 5th Edition by


Joel Murach

http://ebooksecure.com/product/ebook-pdf-murachs-java-
programming-5th-edition-by-joel-murach/
Java
Programming
Tenth Edition

Joyce Farrell

Australia • Brazil • Canada • Mexico • Singapore • United Kingdom • United States

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
This is an electronic version of the print textbook. Due to electronic rights restrictions,
some third party content may be suppressed. Editorial review has deemed that any suppressed
content does not materially affect the overall learning experience. The publisher reserves the right
to remove content from this title at any time if subsequent rights restrictions require it. For
valuable information on pricing, previous editions, changes to current editions, and alternate
formats, please visit www.cengage.com/highered to search by ISBN#, author, title, or keyword for
materials in your areas of interest.

Important Notice: Media content referenced within the product description or the product
text may not be available in the eBook version.

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
JavaTM Programming, Tenth Edition © 2023, © 2019, © 2016 Cengage Learning, Inc. WCN: 02-300
Joyce Farrell ALL RIGHTS RESERVED. No part of this work covered by the copyright herein
may be reproduced or distributed in any form or by any means, except as
SVP, Higher Education Product Management: Erin
permitted by U.S. copyright law, without the prior written permission of the
Joyner
copyright owner.
VP, Product Management, Learning Experiences: Unless otherwise noted, all content is Copyright © Cengage Learning, Inc.
Thais Alencar
Unless otherwise noted, all screenshots are courtesy of Microsoft Corporation.
Product Director: Mark Santee
Microsoft is a registered trademark of Microsoft Corporation in the U.S.
Associate Product Manager: Tran Pham and/or other countries.

The names of all products mentioned herein are used for identification
Product Assistant: Ethan Wheel
purposes only and may be trademarks or registered trademarks of their
Learning Designer: Mary Convertino respective owners. Cengage Learning disclaims any affiliation, association,
connection with, sponsorship, or endorsement by such owners.
Senior Content Manager: Maria Garguilo

Associate Digital Delivery Quality Partner: David For product information and technology assistance, contact us at
O’Connor Cengage Customer & Sales Support, 1-800-354-9706
or support.cengage.com.
Technical Editor: John Freitas
For permission to use material from this text or product, submit all
Developmental Editor: Dan Seiter
requests online at www.copyright.com.

VP, Product Marketing: Jason Sakos


Library of Congress Control Number: 2021925780
Director, Product Marketing: April Danaë
ISBN: 978-0-357-67342-3
Portfolio Marketing Manager: Mackenzie Paine
Cengage
IP Analyst: Ann Hoffman
200 Pier 4 Boulevard
IP Project Manager: Integra Software Services Boston, MA 02210
USA
Production Service: Straive
Cengage is a leading provider of customized learning solutions with
Senior Designer: Erin Griffin employees residing in nearly 40 different countries and sales in more than
125 countries around the world. Find your local representative at
Cover Image Source: iStock.com/gremlin
www.cengage.com.

To learn more about Cengage platforms and services, register or access


your online learning solution, or purchase materials for your course, visit
www.cengage.com.

Notice to the Reader


Publisher does not warrant or guarantee any of the products described herein or perform any independent analysis in connection with
any of the product information contained herein. Publisher does not assume, and expressly disclaims, any obligation to obtain and
include information other than that provided to it by the manufacturer. The reader is expressly warned to consider and adopt all safety
precautions that might be indicated by the activities described herein and to avoid all potential hazards. By following the instructions
contained herein, the reader willingly assumes all risks in connection with such instructions. The publisher makes no representations
or warranties of any kind, including but not limited to, the warranties of fitness for particular purpose or merchantability, nor are any
such representations implied with respect to the material set forth herein, and the publisher takes no responsibility with respect to
such material. The publisher shall not be liable for any special, consequential, or exemplary damages resulting, in whole or part, from
the readers’ use of, or reliance upon, this material.

Printed in the United States of America


Print Number: 01   Print Year: 2022

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
BRIEF CONTENTS
PREFACEXI

CHAPTER 1 Creating Java Programs�������������������������������������������������������������������������������� 1


CHAPTER 2 Using Data���������������������������������������������������������������������������������������������������� 39
CHAPTER 3 Using Methods�������������������������������������������������������������������������������������������� 83
CHAPTER 4 Using Classes and Objects����������������������������������������������������������������������� 115
CHAPTER 5 Making Decisions�������������������������������������������������������������������������������������� 161
CHAPTER 6 Looping������������������������������������������������������������������������������������������������������� 201
CHAPTER 7 Characters, Strings, and the StringBuilder�������������������������������������� 237
CHAPTER 8 Arrays��������������������������������������������������������������������������������������������������������� 267
CHAPTER 9 Inheritance and Interfaces����������������������������������������������������������������������� 329
CHAPTER 10 Exception Handling��������������������������������������������������������������������������������� 393
CHAPTER 11 File Input and Output����������������������������������������������������������������������������� 441
CHAPTER 12 Recursion������������������������������������������������������������������������������������������������� 487
CHAPTER 13 Collections and Generics����������������������������������������������������������������������� 511
CHAPTER 14 Introduction to Swing Components���������������������������������������������������� 545
APPENDIX A Working with the Java Platform ����������������������������������������������������������� 587

APPENDIX B Data Representation ����������������������������������������������������������������������������� 591

APPENDIX C Formatting Output �������������������������������������������������������������������������������� 595

APPENDIX D Generating Random Numbers ������������������������������������������������������������ 603

APPENDIX E Javadoc ���������������������������������������������������������������������������������������������������� 607

APPENDIX F Using JavaFX and Scene Builder ����������������������������������������������������������� 613

GLOSSARY 625
INDEX 641

iii

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CONTENTS
PREFACEXI Key Terms 32
Review Questions 33
CHAPTER 1 Programming Exercises 34
Debugging Exercises 36
CREATING JAVA PROGRAMS 1
Game Zone 36
1.1 Learning Programming Terminology 1 Case Problems 37
1.2 Comparing Procedural and Object-
Oriented Programming Concepts 4
CHAPTER 2
Procedural Programming 4
Object-Oriented Programming 5 USING DATA 39
Understanding Classes, Objects, and Encapsulation 6
2.1 Declaring and Using Constants
Understanding Inheritance and Polymorphism 7
and Variables 39
1.3 Features of the Java Programming Declaring Variables 40
Language8
Declaring Named Constants 42
1.4 Analyzing a Java Application That The Scope of Variables and Constants 43
Produces Console Output 10
Concatenating Strings to Variables and
Understanding the Statement That Produces the Constants 43
Output10
Pitfall: Forgetting That a Variable Holds One
Understanding the First Class 12 Value at a Time 45
Understanding the main() Method 14
2.2 Learning About Integer Data
Indent Style 15
Types47
Saving a Java Class 16
2.3 Using the boolean Data Type 51
1.5 Compiling a Java Class and
Correcting Syntax Errors 18 2.4 Learning About Floating-Point
Compiling a Java Class 18 Data Types 52
Correcting Syntax Errors 19 2.5 Using the char Data Type 53
1.6 Running a Java Application and 2.6 Using the Scanner Class to
Correcting Logic Errors 23 Accept Keyboard Input 57
Running a Java Application 23 Pitfall: Using nextLine() Following One of the
Modifying a Compiled Java Class 23 Other Scanner Input Methods 59
Correcting Logic Errors 24
2.7 Using the JOptionPane Class to
1.7 Adding Comments to a Java Class 25 Accept GUI Input 64
1.8 Creating a Java Application That Using Input Dialog Boxes 64
Produces GUI Output 27 Using Confirm Dialog Boxes 66
1.9 Finding Help 29 2.8 Performing Arithmetic Using
Variables and Constants 68
Don’t Do It 30 Associativity and Precedence 69
Summary31 Writing Arithmetic Statements Efficiently 69

iv

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Contents v

Pitfall: Not Understanding Imprecision in Game Zone 113


Floating-Point Numbers 70 Case Problems 114
2.9 Understanding Type Conversion 72
Automatic Type Conversion 73 CHAPTER 4
Explicit Type Conversion 73
USING CLASSES AND OBJECTS 115
Don’t Do It 76 4.1 Learning About Classes
Summary 77 and Objects 115
Key Terms 77 4.2 Creating a Class 117
Review Questions 78
Programming Exercises 80
4.3 Creating Instance Methods
in a Class 119
Debugging Exercises 81
Game Zone 81 4.4 Declaring Objects and
Case Problems 82 Using Their Methods 124
Understanding Data Hiding 126

CHAPTER 3 4.5 Understanding That Classes


Are Data Types 128
USING METHODS 83 4.6 Creating and Using Constructors 131
3.1 Understanding Method Calls and Creating Constructors with Parameters 132
Placement83
4.7 Learning About the this
3.2 Understanding Method Reference134
Construction86 Using the this Reference to Make
Access Specifiers 86 Overloaded Constructors More Efficient 137
The static Modifier 87
4.8 Using static Fields 139
Return Type 87
Using Constant Fields 140
Method Name 87
Parentheses 88 4.9 Using Imported, Prewritten
Constants and Methods 143
3.3 Adding Parameters to Methods 91
The Math Class 144
Creating a Method That Receives a Single
Importing Classes That Are Not Imported
Parameter 91
Automatically 145
Creating a Method That Requires Multiple
Using the LocalDate Class 146
Parameters 94

3.4 Creating Methods That 4.10 U


 nderstanding Composition
Return Values 95 and Nested Classes 150
Composition 150
3.5 Understanding Blocks and Scope 99
Nested Classes 151
3.6 Overloading a Method 104
3.7 Learning about Ambiguity 107 Don’t Do It 153
Summary 153
Don’t Do It 108 Key Terms 154
Summary 108 Review Questions 154
Key Terms 109 Programming Exercises 156
Review Questions 109 Debugging Exercises 158
Programming Exercises 111 Game Zone 158
Debugging Exercises 113 Case Problems 159

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
vi Contents

CHAPTER 5 CHAPTER 6
MAKING DECISIONS 161 LOOPING201
5.1 Planning Decision-Making Logic 161 6.1 Learning About the Loop
5.2 The if and if…else Statements 163 Structure201
The if Statement 163 6.2 Creating while Loops 202
Pitfall: Misplacing a Semicolon in an if Statement 164 Writing a Definite while Loop 202
Pitfall: Using the Assignment Operator Instead Pitfall: Failing to Alter the Loop Control Variable
of the Equivalency Operator 165 Within the Loop Body 204
Pitfall: Attempting to Compare Objects Using Pitfall: Unintentionally Creating a Loop with
the Relational Operators 165 an Empty Body 204
The if…else Statement 166 Altering a Definite Loop’s Control Variable 206
Writing an Indefinite while Loop 206
5.3 Using Multiple Statements in
if and if…else Clauses 168 Validating Data 208

5.4 Nesting if and if…else 6.3 Using Shortcut Arithmetic


Statements172 Operators210
5.5 Using Logical AND and OR 6.4 Creating a for Loop 214
Operators174 Variations in for Loops 215
The AND Operator 174 6.5 Learning How and When to Use
The OR Operator 175 a do…while Loop 217
Short-Circuit Evaluation 175 6.6 Learning About Nested Loops 220
5.6 Making Accurate and Efficient 6.7 Improving Loop Performance 223
Decisions178 Avoiding Unnecessary Operations 223
Making Accurate Range Checks 178 Considering the Order of Evaluation of
Making Efficient Range Checks 180 Short-Circuit Operators 224
Using && and || Appropriately 180 Comparing to Zero 224
5.7 Using switch  181 Employing Loop Fusion 226
Using the switch Expression 183 A Final Note on Improving Loop Performance 226

5.8 Using the Conditional and NOT


Operators186 Don’t Do It 228
Summary 228
Using the NOT Operator 187
Key Terms 229
5.9 Understanding Operator
Review Questions 229
Precedence187
Programming Exercises 232
5.10 M
 aking Constructors More Debugging Exercises 233
Efficient by Using Decisions in
Game Zone 234
Other Methods 189
Case Problems 235

Don’t Do It 193


Summary 193 CHAPTER 7
Key Terms 194
CHARACTERS, STRINGS, AND
Review Questions 194
THE StringBuilder 237
Programming Exercises 197
Debugging Exercises 198 7.1 Understanding String Data
Game Zone 199
Problems237
Case Problems 200 7.2 Using Character Class Methods 238

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Contents vii

7.3 Declaring and Comparing 8.8 Using Two-Dimensional and Other


String Objects 241 Multidimensional Arrays 300
Comparing String Values 241 Passing a Two-Dimensional Array to a Method 302
Empty and null Strings 245 Using the length Field with a Two-Dimensional
Array303
7.4 Using a Variety of String
Methods246 Understanding Jagged Arrays 304
Using Other Multidimensional Arrays 304
Converting String Objects to Numbers 249

7.5 Learning About the StringBuilder 8.9 Using the Arrays Class 307
and StringBuffer Classes 253 8.10 Creating Enumerations 311

Don’t Do It 257 Don’t Do It 316


Summary 258 Summary 317
Key Terms 258 Key Terms 318
Review Questions 258 Review Questions 318
Programming Exercises 260 Programming Exercises 320
Debugging Exercises 262 Debugging Exercises 323
Game Zone 263 Game Zone 323
Case Problems 264 Case Problems 327

CHAPTER 8 CHAPTER 9
ARRAYS267 INHERITANCE AND INTERFACES 329
8.1 Declaring an Array 267 9.1 Learning About the Concept of
8.2 Initializing an Array 271 Inheritance329
Inheritance Terminology 331
8.3 Using Variable Subscripts with an
Array273 9.2 Extending Classes 332
Using the Enhanced for Loop 275 9.3 Overriding Superclass Methods 336
Using Part of an Array 275 Using the @Override Annotation 337
8.4 Declaring and Using Arrays 9.4 Calling Constructors During
of Objects 277 Inheritance339
Using the Enhanced for Loop with Objects 279 Using Superclass Constructors That Require
Manipulating Arrays of Strings 279 Arguments 340

8.5 Searching an Array and Using 9.5 Accessing Superclass Methods 344
Parallel Arrays 284 Comparing this and super 345
Using Parallel Arrays 284
9.6 Employing Information Hiding 346
Searching an Array for a Range Match 286
9.7 Methods You Cannot Override 348
8.6 Passing Arrays to and Returning
Arrays from Methods 289 A Subclass Cannot Override static Methods
in Its Superclass 348
Returning an Array from a Method 291
A Subclass Cannot Override final Methods
8.7 Sorting Array Elements 292 in Its Superclass 350
Using the Bubble Sort Algorithm 293 A Subclass Cannot Override Methods in a final
Improving Bubble Sort Efficiency 295 Superclass 351
Sorting Arrays of Objects 295 9.8 Creating and Using Abstract
Using the Insertion Sort Algorithm 296 Classes352

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
viii Contents

9.9 Using Dynamic Method Binding 359 10.7 T


 racing Exceptions Through the
Using a Superclass as a Method Parameter Type 360 Call Stack 415
9.10 C
 reating Arrays of Subclass 10.8 C
 reating Your Own Exception
Objects361 Classes419
9.11 U
 sing the Object Class and Its 10.9 Using Assertions 421
Methods364 10.10 Displaying the Virtual Keyboard 430
Using the toString() Method 364
Using the equals() Method 366 Don’t Do It 433
Overloading equals() 367 Summary 434
Overriding equals() 369 Key Terms 434
9.12 Creating and Using Interfaces 371 Review Questions 435
Creating Interfaces to Store Related Constants 374 Programming Exercises 437
Debugging Exercises 439
9.13 U
 sing records, Anonymous Inner
Classes, and Lambda Expressions 377 Game Zone 439

Using records 377 Case Problems 440

Using Anonymous Inner Classes 379


Using Lambda Expressions 380 CHAPTER 11
FILE INPUT AND OUTPUT 441
Don’t Do It 381
Summary 381
11.1 Understanding Computer Files 441
Key Terms 383 11.2 U
 sing the Path and Files
Review Questions 383 Classes443
Programming Exercises 385 Creating a Path 443
Debugging Exercises 389 Retrieving Information About a Path 444
Game Zone 390 Converting a Relative Path to an Absolute One 445
Case Problems 391 Checking File Accessibility 446
Deleting a Path 447
Determining File Attributes 448
CHAPTER 10
11.3 F
 ile Organization, Streams, and
EXCEPTION HANDLING 393 Buffers450
10.1 Learning About Exceptions 393 11.4 Using Java’s IO Classes 452
10.2 T
 rying Code and Catching Writing to a File 454
Exceptions397 Reading from a File 454
Using a try Block to Make Programs “Foolproof” 400 11.5 C
 reating and Using Sequential
Declaring and Initializing Variables in try…catch Data Files 457
Blocks 402
11.6 L
 earning About Random Access
10.3 T
 hrowing and Catching Multiple Files461
Exceptions404
11.7 W
 riting Records to a Random
10.4 Using the finally Block 408 Access Data File 463
10.5 U
 nderstanding the Advantages 11.8 R
 eading Records from a Random
of Exception Handling 410 Access Data File 468
10.6 S
 pecifying the Exceptions That Accessing a Random Access File Sequentially 468
a Method Can Throw 412 Accessing a Random Access File Randomly 470

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Contents ix

Don’t Do It 479 13.4 Using the LinkedList Class 524


Summary 479
13.5 Using Iterators 528
Key Terms 480
Review Questions 480
13.6 Creating Generic Classes 530
Programming Exercises 482 13.7 Creating Generic Methods 532
Debugging Exercises 484 Creating a Generic Method with More than One
Game Zone 484 Type Parameter 533

Case Problems 485


Don’t Do It 537

CHAPTER 12 Summary 538


Key Terms 538
RECURSION487 Review Questions 539

12.1 Understanding Recursion 487 Programming Exercises 541


Debugging Exercises 542
12.2 U
 sing Recursion to Solve
Game Zone 542
Mathematical Problems 489
Case Problems 543
Computing Sums 490
Computing Factorials 491
12.3 U
 sing Recursion to Manipulate CHAPTER 14
Strings495
INTRODUCTION TO Swing
Using Recursion to Separate a Phrase into Words 495
Using Recursion to Reverse the Characters in a
COMPONENTS545
String 496 14.1 U
 nderstanding Swing
12.4 U
 sing Recursion to Create Visual Components545
Patterns499 14.2 Using the JFrame Class 547
12.5 R
 ecursion’s Relationship to Customizing a JFrame’s Appearance 549
Iterative Programming 500 14.3 Using the JLabel Class 552
Changing a JLabel’s Font 553
Don’t Do It 503
14.4 Using a Layout Manager 555
Summary 503
Key Terms 504 14.5 Extending the JFrame Class 557
Review Questions 504 14.6 A
 dding JTextFields and
Programming Exercises 506 JButtons to a JFrame 559
Debugging Exercises 508 Adding JTextFields to a JFrame 559
Game Zone 509 Adding JButtons to a JFrame 560
Case Problems 510 14.7 L
 earning About Event-Driven
Programming563
CHAPTER 13 Preparing Your Class to Accept Event Messages 564
Telling Your Class to Expect Events to Happen 564
COLLECTIONS AND GENERICS 511 Telling Your Class How to Respond to Events 564
13.1 U
 nderstanding the Collection Writing an Event-Driven Program 565
Interface511 Using Multiple Event Sources 566
13.2 U
 nderstanding the List Using the setEnabled() Method 567
Interface513
14.8 U
 nderstanding Swing Event
13.3 Using the ArrayList Class 514 Listeners569

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
x Contents

14.9 U
 sing the JCheckBox, APPENDIX C
ButtonGroup, and JComboBox
Classes572 FORMATTING OUTPUT  595
The JCheckBox Class 572
The ButtonGroup Class 574 APPENDIX D
The JComboBox Class 575
GENERATING RANDOM
Don’t Do It 580 NUMBERS 603
Summary 581
Key Terms 581 APPENDIX E
Review Questions 582
JAVADOC  607
Programming Exercises 584
Debugging Exercises 585
Game Zone 585
APPENDIX F
Case Problems 586 USING JAVAFX AND SCENE
BUILDER613
APPENDIX A
GLOSSARY 625
WORKING WITH THE INDEX 641
JAVA PLATFORM 587

APPENDIX B
DATA REPRESENTATION 591

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
PREFACE
Java Programming, Tenth Edition provides the beginning programmer with a guide to developing applications
using the Java programming language. Java is popular among professional programmers because it is object-
oriented, making complex problems easier to solve than in some other languages. Java is used for desktop
computing, mobile computing, game development, Web development, and numerical computing.

This course assumes that you have little or no programming experience. It provides a solid background in
good object-oriented programming techniques and introduces terminology using clear, familiar language. The
programming examples are business examples; they do not assume a mathematical background beyond high
school business math. In addition, the examples illustrate only one or two major points; they do not contain so
many features that you become lost following irrelevant and extraneous details. Complete, working programs
appear frequently in each chapter; these examples help students make the transition from the theoretical
to the practical. The code presented in each chapter also can be downloaded from the Cengage website, so
students easily can run the programs and experiment with changes to them.

The student using Java Programming, Tenth Edition builds applications from the bottom up rather than
starting with existing objects. This facilitates a deeper understanding of the concepts used in object-oriented
programming and engenders appreciation for the existing objects students use as their knowledge of the
language advances. When students complete this course, they will know how to modify and create simple Java
programs, and they will have the tools to create more complex examples. They also will have a fundamental
knowledge of object-oriented programming, which will serve them well in advanced Java courses or in studying
other object-oriented languages such as C++, C#, and Visual Basic.

Organization and Coverage


Java Programming, Tenth Edition presents Java programming concepts, enforcing good style, logical thinking,
and the object-oriented paradigm. Objects are covered right from the beginning, earlier than in many other
Java courses. You create your first Java program in Chapter 1. Chapters 2, 3, and 4 increase your understanding
about how data, classes, objects, and methods interact in an object-oriented environment.

Chapters 5 and 6 explore input and repetition structures, which are the backbone of programming logic and
essential to creating useful programs in any language. You learn the special considerations of string and array
manipulation in Chapters 7 and 8.

Chapters 9 and 10 thoroughly cover inheritance, interfaces, and exception handling. Inheritance is the object-
oriented concept that allows you to develop new objects quickly by adapting the features of existing objects,
interfaces define common methods that must be implemented in all classes that use them, and exception
handling is the object-oriented approach to handling errors. All of these are important concepts in object-
oriented design. Chapter 11 provides information about handling files so you can store and retrieve program
output.

Chapter 12 explains recursion, and Chapter 13 covers Java collections and generics. Both are important
programming concepts, and Java provides excellent ways to implement and learn about them. Chapter 14
introduces GUI Swing components, which are used to create visually pleasing, user-friendly, interactive
applications.

xi

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
xii Preface

New in This Edition


The following features are new for the Tenth Edition:

❯❯Java: All programs have been tested using Java 16.

❯❯Java help: Instructions on searching for Java help have been updated to avoid using specific URLs because new
Java versions are now being released twice a year.
❯❯Text blocks: Chapter 2 introduces text blocks—a new feature since Java 13.

❯❯Methods: Methods are covered thoroughly in Chapter 3, including topics such as overloading methods and
avoiding ambiguity. In previous editions, the material was split between chapters.
❯❯Classes and objects: Classes and objects are covered thoroughly in Chapter 4. In previous editions, the material
was split between chapters.
❯❯The switch expression: Chapter 5 includes the switch expression, which became a new feature in Java 14.

❯❯Arrays: Chapter 8 covers beginning and advanced array concepts. In previous editions, this content was split
between chapters.
❯❯Inheritance and interfaces: Chapter 9 covers inheritance and interfaces. In previous editions, this content was
split between chapters.
❯❯The record keyword: Chapter 9 also introduces the record keyword, which allows simple classes to be
developed more quickly because a constructor and methods to get and set fields are created automatically
based on field definitions.
❯❯Recursion: Chapter 12 is a new chapter on recursion. The chapter presents techniques to use to solve
mathematical problems, manipulate strings, and create visual patterns using recursion.
❯❯Collections and generics: Chapter 13 is a new chapter on collections and generics. The chapter covers the
Collection and List interfaces, the ArrayList and LinkedList classes, Iterators, and generic
classes and methods.

Additionally, Java Programming, Tenth Edition includes the following features:

❯❯Objectives: Each chapter begins with a list of objectives so you know the topics that will be presented in the
chapter. In addition to providing a quick reference to topics covered, this feature provides a useful study aid.
❯❯You Do It: In each chapter, step-by-step exercises help students create multiple working programs that
emphasize the logic a programmer uses in choosing statements to include. These sections provide a means for
students to achieve success on their own—even those in online or distance learning classes.
❯❯Notes: These highlighted tips provide additional information—for example, an alternative method of performing
a procedure, another term for a concept, background information about a technique, or a common error to
avoid.
❯❯Emphasis on student research: The student frequently is advised to use the Web to investigate Java classes,
methods, and techniques. Computer languages evolve, and programming professionals must understand how to
find the latest language improvements.
❯❯Figures: Each chapter contains many figures. Code figures are most frequently 25 lines or fewer, illustrating one
concept at a time. Frequent screenshots show exactly how program output appears. Callouts appear where
needed to emphasize a point.
❯❯Color: The code figures in each chapter contain all Java keywords in blue. This helps students identify keywords
more easily, distinguishing them from programmer-selected names.
❯❯Files: More than 200 student files can be downloaded from the Cengage website. Most files contain the code
presented in the figures in each chapter; students can run the code for themselves, view the output, and make

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Preface xiii

changes to the code to observe the effects. Other files include debugging exercises that help students improve
their programming skills.
❯❯Two Truths & a Lie: A short quiz reviews almost every chapter section, with answers provided. This quiz
contains three statements based on the preceding section of text—two statements are true, and one is false.
Over the years, students have requested answers to problems, but we have hesitated to distribute them in case
instructors want to use problems as assignments or test questions. These true-false quizzes provide students
with immediate feedback as they read, without “giving away” answers to the multiple-choice questions and
programming exercises.
❯❯Don’t Do It: This section at the end of each chapter summarizes common mistakes and pitfalls that plague new
programmers while learning the current topic.
❯❯Summary: Following each chapter is a summary that recaps the programming concepts and techniques covered
in the chapter. This feature provides a concise means for students to check their understanding of the main
points in each chapter.
❯❯Key Terms: Each chapter includes a list of newly introduced vocabulary, shown in alphabetical order. The list of
key terms provides a short review of the major concepts in the chapter.
❯❯Review Questions: Each chapter includes 20 multiple-choice questions that serve as a review of chapter topics.

❯❯Programming Exercises: Multiple programming exercises are included with each chapter. These challenge
students to create complete Java programs that solve real-world problems.
❯❯Debugging Exercises: Four debugging exercises are included with each chapter. These are programs that
contain logic or syntax errors that the student must correct. Besides providing practice in deciphering error
messages and thinking about correct logic, these exercises provide examples of complete and useful Java
programs after the errors are repaired.
❯❯Game Zone: Each chapter provides one or more exercises in which students can create interactive games
using the programming techniques learned up to that point; 50 game programs are suggested in the course.
The games are fun to create and play; writing them motivates students to master the necessary programming
techniques. Students might exchange completed game programs with each other, suggesting improvements and
discovering alternate ways to accomplish tasks.
❯❯Cases: Each chapter contains two running case problems. These cases represent projects that continue to
grow throughout a semester using concepts learned in each new chapter. Two cases allow instructors to assign
different cases in alternate semesters or to divide students in a class into two case teams.
❯❯Glossary: A glossary contains definitions for all key terms in the course.

❯❯Appendices: This edition includes useful appendices on working with the Java platform, data representation,
formatting output, generating random numbers, creating Javadoc comments, and JavaFX.
❯❯Quality: Every program example, exercise, and game solution was tested by the author and then tested again by
a quality assurance team.

MindTap Instructor Resources


MindTap activities for Java Programming, Tenth Edition are designed to help students master the skills they need in
today’s workforce. Research shows employers need critical thinkers, troubleshooters, and creative problem-solvers
to stay relevant in our fast-paced, technology-driven world. MindTap helps you achieve this with assignments and
activities that provide hands-on practice and real-life relevance. Students are guided through assignments that help
them master basic knowledge and understanding before moving on to more challenging problems.

All MindTap activities and assignments are tied to defined unit learning objectives. MindTap provides the analytics and
reporting so you can easily see where the class stands in terms of progress, engagement, and completion rates. Use

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
xiv Preface

the content and learning path as is or pick and choose how our materials will wrap around yours. You control what
the students see and when they see it. Learn more at http://www.cengage.com/mindtap/.

In addition to the readings, the Java Programming, Tenth Edition MindTap includes the following:

❯❯Gradeable assessments and activities: All assessments and activities from the readings will be available as
gradeable assignments within MindTap, including Review Questions, Game Zone, Case Problems, and Two
Truths & a Lie.
❯❯Videos: Each unit is accompanied by videos that help to explain important unit concepts and provide demos on
how students can apply those concepts.
❯❯Coding Snippets: These short, ungraded coding activities are embedded in the MindTap Reader and provide
students an opportunity to practice new programming concepts “in the moment.” The coding Snippets help
transition the students from conceptual understanding to application of Java code.
❯❯Coding labs: These assignments provide real-world application and encourage students to practice new coding
skills in a complete online IDE. Guided feedback provides personalized and immediate feedback to students as
they proceed through their coding assignments so that they can understand and correct errors in their code.
❯❯Interactive study aids: Flashcards and PowerPoint lectures help users review main concepts from the units.

Instructor and Student Resources


Additional instructor and student resources for this product are available online. Instructor assets include an
Instructor’s Manual, Educator’s Guide, PowerPoint® slides, Solution and Answer Guide, solutions, and a test bank
powered by Cognero®. Student assets include data files. Sign up or sign in at www.cengage.com to search for and access
this product and its online resources.

❯❯Instructor’s Manual: The Instructor’s Manual includes additional instructional material to assist in class
preparation, including sections such as Chapter Objectives, Complete List of Chapter Activities and
Assessments, Key Terms, What’s New In This Chapter, Chapter Outline, Discussion Questions, Suggested Usage
for Lab Activities, Additional Activities and Assignments, and Additional Resources. A sample syllabus also is
available.
❯❯PowerPoint presentations: The PowerPoint slides can be used to guide classroom presentations, to make
available to students for chapter review, or to print as classroom handouts.
❯❯Solution and Answer Guide: Solutions to all end-of-chapter assignments are provided along with feedback.

❯❯Solutions: Solutions to all programming exercises are available. If an input file is needed to run a programming
exercise, it is included with the solution file.
❯❯Test bank: Cengage Testing Powered by Cognero is a flexible, online system that allows you to:
■■ Author, edit, and manage test bank content from multiple Cengage solutions.
■■ Create multiple test versions in an instant.
■■ Deliver tests from your LMS, your classroom, or wherever you want.
❯❯Educator’s Guide: The Educator’s Guide contains a detailed outline of the corresponding MindTap course.

❯❯Transition Guide: The Transition Guide outlines information on what has changed from the Ninth Edition.

❯❯Data files: Data files necessary to complete some of the steps and projects in the course are available. The Data
Files folder includes Java files that are provided for every program that appears in a figure in the text.

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Preface xv

About the Author


Joyce Farrell has taught computer programming at McHenry County College, Crystal Lake, Illinois; the University of
Wisconsin, Stevens Point, Wisconsin; and Harper College, Palatine, Illinois. Besides Java, she has written books on
programming logic and design, C#, and C++ for Cengage.

Acknowledgments
I would like to thank all of the people who helped to make this project a reality, including Tran Pham, Associate Product
Manager; Mary Convertino, Learning Designer; Maria Garguilo, Senior Content Manager; Dan Seiter, Developmental
Editor, and John Freitas, Quality Assurance Tester. I am lucky to work with these professionals who are dedicated to
producing high-quality instructional materials.

I am also grateful to the reviewers who provided comments and encouragement during this course’s development,
including Dr. Ross Foultz, Coastal Carolina University; and Dr. Carl M. Rebman, Jr., University of San Diego. Also, thank
you to Charles W. Lively III, Ph.D. – Academic Faculty, Georgia Institute of Technology, who provided the appendix on
JavaFX.

Thanks, too, to my husband, Geoff, for his constant support, advice, and encouragement. Finally, this project is
dedicated to Norman Williams Peterson, who has brought a smile to my face every time I have seen him.

Joyce Farrell

Read This Before You Begin


The following information will help you as you prepare to complete this course.

To the User of the Data Files


To complete the steps and projects in this course, you need data files that have been created specifically for some of
the exercises. Your instructor will provide the data files to you. You also can obtain the files electronically by signing
up or signing in at www.cengage.com and then searching for and accessing this product and its online resources. Note
that you can use a computer in your school lab or your own computer to complete the exercises.

Using Your Own Computer


To use your own computer to complete the steps and exercises, you need the following:

❯❯Software: Java SE 16 or later, available from www.oracle.com/technetwork/java/index.html. Although almost


all of the examples in this course will work with earlier versions of Java, a few require Java 16 or later. You also
need a text editor, such as Notepad. A few exercises ask you to use a browser for research.
❯❯Hardware: For operating system requirements (memory and disk space), see http://java.com/en/download/
help.

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
xvi Preface

Features
This text focuses on helping students become better programmers and understand Java program development through
a variety of key features. In addition to Chapter Objectives, Summaries, and Key Terms, these useful features will help
students regardless of their learning styles.

You Do It

These sections walk students through program development step by step.

These notes provide additional information—for example, a common error to watch out for or
Note background information on a topic.

Two Truths & a Lie

These quizzes appear after almost every chapter section, with answers provided. Each quiz contains three
statements based on the preceding section of text—two statements are true and one is false.

Answers give immediate feedback without “giving away” answers to the multiple-choice questions and
programming problems later in the chapter. Students also have the option to take these quizzes in MindTap.

Don’t Do It Icon
The Don’t Do It icon illustrates how NOT to do something—for example, having a dead code path in a program. These
icons provide a visual jolt to the student, emphasizing that particular practices are NOT to be emulated and making
students more likely to recognize problems in existing code.

import java.util.Scanner;
public class GetUserInfo2 Don’t Do It
{
public static void main(String[] args) If you accept numeric
{ input prior to string input,
String name; the string input is ignored
int age; unless you take special
Scanner inputDevice = new Scanner(System.in); action.
System.out.print("Please enter your age >> ");
age = inputDevice.nextInt();
System.out.print("Please enter your name >> ");
name = inputDevice.nextLine();
System.out.println("Your name is " + name +
" and you are " + age + " years old.");
}
}

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Preface xvii

Don’t Do It
These sections at the end of each chapter list advice for avoiding common programming errors.

Assessment

Review Questions
Review Questions test student comprehension of the major ideas and techniques presented. Twenty questions follow
each chapter.

Programming Exercises
Programming Exercises provide opportunities to practice concepts. These exercises allow students to explore each
major programming concept presented in the chapter. Additional coding labs and snippets are available in MindTap.

Debugging Exercises
Debugging Exercises are included with each chapter because examining programs critically and closely is a crucial
programming skill. Students and instructors can download these exercises at www.cengage.com.

Game Zone
Game Zone exercises are included at the end of each chapter. Students can create games as an additional entertaining
way to understand key programming concepts.

Case Problems
Case Problems provide opportunities to build more detailed programs that continue to incorporate increasing
functionality throughout the course.

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Chapter 1

Creating Java
Programs
Learning Objectives
When you complete this chapter, you will be able to:

1.1 Define basic programming terminology


1.2 Compare procedural and object-oriented programming
1.3 Describe the features of the Java programming language
1.4 Analyze a Java application that produces console output
1.5 Compile a Java class and correct syntax errors
1.6 Run a Java application and correct logic errors
1.7 Add comments to a Java class
1.8 Create a Java application that produces GUI output
1.9 Identify and consult resources to help develop Java programming skills

1.1 Learning Programming Terminology


You see many computers every day. There might be a laptop on your desk, and there also are computers in
your phone, in your car, and perhaps in your thermostat, washing machine, and vacuum cleaner. When you
learn computer terminology and how to program a computer, you learn a bit about how these devices work,
you develop your critical thinking skills, and you learn to communicate more clearly. You will reap all these
benefits as you work through this course.

Computer systems consist of both hardware and software.

❯❯Computer equipment, such as a monitor or keyboard, is hardware.

❯❯Programs are software. A computer program (or simply, program) is a set of instructions that you write
to tell a computer what to do.

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
2 Chapter 1 Creating Java Programs

Software can be divided into two broad categories:

❯❯A program that performs a task for a user (such as calculating and producing paychecks, word processing, or
playing a game) is application software. Programs that are application software are called applications, or apps
for short.
❯❯A program that manages the computer itself (such as Windows or Linux) is system software.

The logic behind any computer program, whether it is an application or system program, determines the exact order of
instructions needed to produce desired results. Much of this course describes how to develop the logic for application
software.

You can write computer programs in high- or low-level programming languages:

❯❯A high-level programming language such as Java, Visual Basic, C++, or C# allows you to use English-like, easy-
to-remember terms such as read, write, and add.
❯❯A low-level programming language corresponds closely to a computer’s circuitry and is not as easily read or
understood. Because they correspond to circuitry, low-level languages must be customized for every type of
machine on which a program runs.

All computer programs, even high-level language programs, ultimately are converted to the lowest-level language,
which is machine language. Machine language, or machine code, is the most basic set of instructions that a computer
can execute. Each type of processor (the internal hardware that handles computer instructions) has its own set of
machine language instructions. Programmers often describe machine language using 1s and 0s to represent the on-
and-off circuitry of computer systems.

The system that uses only 1s and 0s is the binary numbering system. Appendix B describes the binary
Note system in detail. Later in this chapter, you will learn that bytecode is the name for the binary code created
when Java programs are converted to machine language.

Every programming language has its own syntax, or rules about how language elements are combined correctly to
produce usable statements. For example, depending on the specific high-level language, you might use the verb print
or write to produce output. All languages have a specific, limited vocabulary (the language’s keywords) and a specific
set of rules for using that vocabulary. When you are learning a computer programming language, such as Java, C++, or
Visual Basic, you are learning the vocabulary and syntax for that language.

Using a programming language, programmers write a series of program statements, which are similar to English
sentences. The statements carry out the program’s tasks. Program statements are also known as commands because
they are orders to the computer, such as Output this word or Add these two numbers.

After the program statements are written in a high-level programming language, a computer program called a compiler
or interpreter translates the statements into machine language. A compiler translates an entire program before carrying
out any statements, or executing them, whereas an interpreter translates one program statement at a time, executing
a statement as soon as it is translated.

Whether you use a compiler or interpreter often depends on the programming language you use.
Note For example, C++ is a compiled language, and Visual Basic is an interpreted language. Each type of
translator has its supporters; programs written in compiled languages execute more quickly, whereas
programs written in interpreted languages can be easier to develop and debug. Java uses the best of
both technologies: a compiler to translate your programming statements and an interpreter to read the
compiled code line by line when the program executes (also called at run time).

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
1.1 Learning Programming Terminology 3

Compilers and interpreters issue one or more error messages each time they encounter an invalid program statement—
that is, a statement containing a syntax error, or misuse of the language. Examples of syntax errors include misspelling
a keyword or omitting a word that a statement requires. When a syntax error is detected, the programmer can correct
the error and attempt another translation. Repairing all syntax errors is the first part of the process of debugging a
program—freeing the program of all flaws or errors, also known as bugs. Figure 1-1 illustrates the steps a programmer
takes while developing an executable program. You will learn more about debugging Java programs later in this chapter.

Figure 1-1 The program development process

Plan program logic

Write program language statements


that correspond to the logic

Debugging process
Use translating software (a compiler or
interpreter) that translates programming
language statements to machine language

Debugging process
Can all statements No Examine list of
be successfully
syntax errors
translated?

Yes

Execute the program

Examine
program output

Are there runtime Yes


or output errors?

No

As Figure 1-1 shows, you might write a program that compiles successfully (that is, it contains no syntax errors), but
it still might not be a correct program because it might contain one or more logic errors. A logic error is a bug that
allows a program to run, but that causes it to operate incorrectly. Correct logic requires that all the right commands
be issued in the appropriate order. Examples of logic errors include multiplying two values when you meant to divide
them or producing output prior to obtaining the appropriate input. When you develop a program of any significant
size, you should plan its logic before you write any program statements.
Correcting logic errors is much more difficult than correcting syntax errors. Syntax errors are discovered by the
language translator when you compile a program, but a program can be free of syntax errors and execute while still

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
4 Chapter 1 Creating Java Programs

retaining logic errors. Sometimes you can find logic errors by carefully examining the structure of your program (when
a group of programmers do this together, it is called a structured walkthrough), but sometimes you can identify logic
errors only when you examine a program’s output. For example, if you know an employee’s paycheck should contain
the value $4,000, but when you examine a payroll program’s output you see that it holds $40, then a logic error has
occurred. Perhaps an incorrect calculation was performed, or maybe the hours-worked value was output by mistake
instead of the net pay value. When output is incorrect, the programmer must carefully examine all the statements
within the program, revise or move the offending statements, and translate and test the program again.

Just because a program produces correct output does not mean it is free from logic errors. For example,
Note suppose that a program should multiply two values entered by the user, that the user enters two 2s, and
that the output is 4. The program might actually be adding the values by mistake. The programmer would
discover the logic error only by entering different values, such as 5 and 7, and examining the result.

Programmers call some logic errors semantic errors. For example, if you misspell a programming
Note language word, you commit a syntax error, but if you use a correct word in the wrong context, you
commit a semantic error.

Two Truths & a Lie  Learning Programming Terminology

In each “Two Truths & a Lie” section, two of the numbered statements are true, and one is false. Identify the false
statement and explain why it is false.

1. Unlike a low-level programming language, a high-level programming language allows you to use
a vocabulary of reasonable terms instead of the sequences of on-and-off switches that perform the
corresponding tasks.

2. A syntax error occurs when you violate the rules of a language; locating and repairing all syntax errors is
part of the process of debugging a program.

3. Logic errors are fairly easy to find because the software that translates a program finds all the logic errors for you.

The false statement is #3. A language translator finds syntax errors, but logic errors can still exist in a program that
is free of syntax errors.

1.2 C
 omparing Procedural and Object-Oriented
Programming Concepts
All computer programmers must deal with syntax errors and logical errors in much the same way, but they might take
different approaches to the entire programming process. Procedural programming and object-oriented programming
describe two different approaches to writing computer programs.

Procedural Programming
Procedural programming is a style of programming in which operations are executed one after another in sequence.

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
1.2 Comparing Procedural and Object-Oriented Programming Concepts 5

The typical procedural program defines and uses named computer memory locations; each of these named locations
that can hold data is called a variable. For example, data might be read from an input device and stored in a location
the programmer has named rateOfPay. The variable value might be used in an arithmetic statement, used as the
basis for a decision, sent to an output device, or have other operations performed with it. The data stored in a variable
can change, or vary, during a program’s execution.

For convenience, the individual operations used in a computer program are often grouped into logical units called
procedures. For example, a series of four or five comparisons and calculations that together determine a person’s
federal withholding tax value might be grouped as a procedure named calculateFederalWithholding(). (As a
convention, this course will show parentheses following every procedure name.) As a procedural program executes
its statements, it can sometimes pause to call a procedure. When a program calls a procedure, the current logic is
temporarily suspended so that the procedure’s commands can execute. A single procedural program might contain any
number of procedure calls. Procedures are also called modules, methods, functions, and subroutines. Users of different
programming languages tend to use different terms. As you will learn later in this chapter, Java programmers most
frequently use the term method.

Object-Oriented Programming
Object-oriented programming is an extension of procedural programming in which you take a slightly different approach
to writing computer programs. Writing object-oriented programs involves the following:

❯❯Creating classes, which are blueprints for objects

❯❯Creating objects, which are specific instances of those classes

❯❯Creating applications that manipulate or use those objects

Programmers use OO as an abbreviation for object-oriented; it is pronounced oh oh. Object-oriented


Note programming is abbreviated OOP, and pronounced to rhyme with soup.

Originally, object-oriented programming was used most frequently for two major types of applications:

❯❯Computer simulations, which attempt to mimic real-world activities so that their processes can be improved or
so that users can better understand how the real-world processes operate
❯❯Graphical user interfaces (GUIs), pronounced gooeys, which allow users to interact with a program in a graphical
environment

Thinking about objects in these two types of applications makes sense. For example, a city might want to develop a
program that simulates traffic patterns and controls traffic signals to help prevent tie-ups. Programmers would create
classes for objects such as cars and pedestrians that contain their own data and rules for behavior. For example, each
car has a speed and a method for changing that speed. The specific instances of cars could be set in motion to create
a simulation of a real city at rush hour.

Creating a GUI environment for users is also a natural use for object orientation. It is easy to think of the components
a user manipulates on a computer screen, such as buttons and scroll bars, as similar to real-world objects. Each
GUI object contains data—for example, a button on a screen has a specific size and color. Each object also contains
­behaviors—for example, each button can be clicked and reacts in a specific way when clicked. Some people consider
the term object-oriented programming to be synonymous with GUI programming, but object-oriented programming
means more. Although many GUI programs are object oriented, not all object-oriented programs use GUI objects.
Modern businesses use object-oriented design techniques when developing all sorts of business applications, whether
they are GUI applications or not. Early in this course, you will learn object-oriented techniques that are appropriate
for any program type; in the last chapters, you will apply what you have learned about those techniques specifically
to GUI applications.

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
6 Chapter 1 Creating Java Programs

Understanding object-oriented programming requires grasping three basic concepts:

❯❯Encapsulation as it applies to classes as objects

❯❯Inheritance

❯❯Polymorphism

Understanding Classes, Objects, and Encapsulation


In object-oriented terminology, a class is a group or collection of objects with common properties. In the same way
that a blueprint exists before any houses are built from it, and a recipe exists before any cookies are baked from it, a
class definition exists before any objects are created from it. A class definition describes what attributes its objects
will have and what those objects will be able to do. Attributes are the characteristics that define an object; they are
properties of the object. When you learn a programming language such as Java, you learn to work with two types of
classes: those that have already been developed by the language’s creators and your own new, customized classes.

An object is a specific, concrete instance of a class. Creating an instance is called instantiation. You can create objects
from classes that you write and from classes written by other programmers, including Java’s creators. The values
contained in an object’s properties often differentiate instances of the same class from one another. For example, the
class Automobile describes what Automobile objects are like. Some properties of the Automobile class are
make, model, year, and color. Each Automobile object possesses the same attributes, but not necessarily the same
values for those attributes. One Automobile might be a 2014 white Honda Civic, and another might be a 2021 red
Chevrolet Camaro. Similarly, your dog has the properties of all Dogs, including a breed, name, age, and whether the
dog’s shots are current. The values of the properties of an object are referred to as the object’s state. In other words,
you can think of objects as roughly equivalent to nouns (words that describe a person, place, or thing), and of their
attributes as similar to adjectives that describe the nouns.

When you understand an object’s class, you understand the characteristics of the object. If your friend purchases an
Automobile, you know it has a model name, and if your friend gets a Dog, you know the dog has a breed. Knowing
what attributes exist for classes allows you to ask appropriate questions about the states or values of those attributes.
For example, you might ask how many miles the car gets per gallon, but you would not ask whether the car has had
shots. Similarly, in a GUI operating environment, you expect each component to have specific, consistent attributes and
methods, such as a window having a title bar and a close button, because each component gains these properties as a
member of the general class of GUI components. Figure 1-2 shows the relationship of some Dog objects to the Dog class.

By convention, programmers using Java begin their class names with an uppercase letter. Thus, the class
Note that defines the attributes and methods of an automobile probably would be named Automobile, and
the class for dogs probably would be named Dog. This convention, however, is not required to produce a
workable program.

Besides defining properties, classes define methods their objects can use. A method is a self-contained block of
program code that carries out some action, similar to a procedure in a procedural program. An Automobile, for
example, might have methods for moving forward, moving backward, and determining the status of its gas tank.
Similarly, a Dog might have methods for walking, eating, and determining its name, and a program’s GUI components
might have methods for maximizing and minimizing them as well as determining their size. In other words, if objects
are similar to nouns, then methods are similar to verbs.

In object-oriented classes, attributes and methods are encapsulated into objects. Encapsulation refers to two closely
related object-oriented notions:

❯❯Encapsulation is the enclosure of data and methods within an object. Encapsulation allows you to treat all of an
object’s methods and data as a single entity. Just as an actual dog contains all of its attributes and abilities, so
would a program’s Dog object.

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
1.2 Comparing Procedural and Object-Oriented Programming Concepts 7

Figure 1-2 Dog class definition and some objects created from it

Dog class definition Dog class instances (objects)

istock.com/GlobalP
istock.com/GlobalP

istock.com/olaser
Every Dog that is
created will have a:

Name

Age

Breed Ginger Bowser Roxy


6 2 1
Shot status Akita Retriever Beagle
Up to date Up to date Up to date

❯❯Encapsulation also refers to the concealment of an object’s data and methods from outside sources. Concealing
data is sometimes called information hiding, and concealing how methods work is implementation hiding; you
will learn more about both terms as you learn more about classes and objects. Encapsulation lets you hide
specific object attributes and methods from outside sources and provides the security that keeps data and
methods safe from inadvertent changes.

If an object’s methods are well written, the user can be unaware of the low-level details of how the methods are
executed, and the user must simply understand the interface or interaction between the method and the object. For
example, if you can fill your Automobile with gasoline, it is because you understand the interface between the gas
pump nozzle and the vehicle’s gas tank opening. You don’t need to understand how the pump works mechanically
or where the gas tank is located inside your vehicle. If you can read your speedometer, it does not matter how the
displayed value is calculated. As a matter of fact, if someone produces a superior, more accurate speed-determining
device and inserts it in your Automobile, you don’t have to know or care how it operates, as long as your interface
remains the same. The same principles apply to well-constructed classes used in object-oriented programs—programs
that use classes only need to work with interfaces.

Understanding Inheritance and Polymorphism


An important feature of object-oriented program design that differentiates it from procedural program design is
­inheritance—the ability to create classes that share the attributes and methods of existing classes, but with more
specific features. For example, Automobile is a class, and all Automobile objects share many traits and abilities.
Convertible is a class that inherits from the Automobile class; a Convertible is a type of Automobile that has
and can do everything a “plain” Automobile does—but with an added ability to lower its top. (In turn, A
­ utomobile
inherits from the Vehicle class.) Convertible is not an object—it is a class. A specific Convertible is an object—
for example, my1967BlueMustangConvertible.

Inheritance helps you understand real-world objects. For example, the first time you encounter a convertible, you
already understand how the ignition, brakes, door locks, and other systems work because you realize that a convert-
ible is a type of automobile. Therefore, you need to be concerned only with the attributes and methods that are “new”
with a convertible. The advantages in programming are the same—you can build new classes based on existing classes
and concentrate on the specialized features you are adding.

A final important concept in object-oriented terminology (that does not exist in procedural programming terminology)
is polymorphism. Literally, polymorphism means many forms—it describes the feature of languages that allows the

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
8 Chapter 1 Creating Java Programs

same word or symbol to be interpreted correctly in different situations based on the context. For example, although the
classes Automobile, Sailboat, and Airplane all inherit from Vehicle, methods such as turn() and stop()
work differently for instances of those classes. The advantages of polymorphism will become more apparent when you
begin to create GUI applications containing features such as windows, buttons, and menu bars. In a GUI application,
it is convenient to remember one method name, such as setColor() or setHeight(), and have it work correctly
no matter what type of object you are modifying.

When you see a plus sign (+) between two numbers, you understand they are being added. When you
Note see it carved in a tree between two names, you understand that the names are linked romantically.
Because the symbol has diverse meanings based on context, it is polymorphic. Later in this course, you
will learn more about inheritance and polymorphism and how they are implemented in Java. Using Java,
you can write either procedural or object-oriented programs. In this course, you will learn about how to
do both.

Two Truths & a Lie   Comparing Procedural and Object-Oriented Programming Concepts

1. An instance of a class is a created object that possesses the attributes and methods described in the class
definition.

2. Encapsulation protects data by hiding it within an object.

3. Polymorphism is the ability to create classes that share the attributes and methods of existing classes, but
with more specific features.

The false statement is #3. Inheritance is the ability to create classes that share the attributes and methods of
existing classes, but with more specific features; polymorphism describes the ability to use one term to cause
multiple actions.

1.3 Features of the Java Programming Language


Java was developed by Sun Microsystems as an object-oriented language for general-purpose business
applications and for interactive, World Wide Web-based Internet applications. (Sun was later acquired by Oracle
­Corporation.) Some of the advantages that make Java a popular language are its security features and the fact
that it is architecturally neutral. In other words, unlike many other languages, you can use Java to write a program
that runs on any operating system (such as Windows, macOS, or Linux) or any device (such as PCs, phones, and
tablet computers).

Java can be run on a wide variety of computers and devices because it does not execute instructions on a computer
directly. Instead, Java runs on a hypothetical computer known as the Java Virtual Machine (JVM). When programmers
call the JVM hypothetical, they mean it is not a physical entity created from hardware, but is composed only of
software.

Figure 1-3 shows the Java environment. Programming statements written in a high-level programming language
are source code. When you write a Java program, you first construct the source code using a plain text editor
such as Notepad, or you can use a development environment such as Eclipse, NetBeans, or JDeveloper.
A development environment is a set of tools that help you write programs by providing such features as
displaying a language’s keywords in color.

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
1.3 Features of the Java Programming Language 9

Figure 1-3 The Java environment

Java Source Code

Source code is
stored on a disk in
a file with a name
ending in .java

Java Compiler

Compiler creates
bytecode that
is stored on a
disk in a file with
a name ending in
Java Virtual Machine .class

Java Interpreter

JVM (named java.exe)


performs security checks
and translates bytecode to
machine language, which
Computer Operating
executes
System

When you write a Java program, the following steps take place:

❯❯The Java source code statements you write are saved in a file.

❯❯The Java compiler converts the source code into a binary program of bytecode.

❯❯A program called the Java interpreter then checks the bytecode and communicates with the operating system,
executing the bytecode instructions line by line within the JVM.

Because the Java program is isolated from the operating system, it is also insulated from the particular hardware on
which it is run. Because of this insulation, the JVM provides security against intruders accessing your computer’s
hardware through the operating system. Therefore, Java is more secure than other languages. Another advantage
provided by the JVM means less work for programmers—when using other programming languages, software vendors
usually have to produce multiple versions of the same product (a Windows version, Macintosh version, UNIX version,
Linux version, and so on) so all users can run the program. With Java, one program version runs on all these platforms.
“Write once, run anywhere” (WORA) is the slogan developed by Sun Microsystems to describe the ability of one Java
program version to work correctly on multiple platforms.

Java also is simpler to use than many other object-oriented languages. Java is modeled after C++. Although neither
language is easy to read or understand on first exposure, Java does eliminate some of the most difficult-to-understand
features in C++, such as pointers and multiple inheritance.

You can write two types of Java applications:

❯❯Console applications, which support character or text output to a computer screen

❯❯Windowed applications, which create a GUI with elements such as menus, toolbars, and dialog boxes

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
10 Chapter 1 Creating Java Programs

Console applications are the easier applications to create; you start using them in the next section. You will create
your first simple GUI application later in this chapter.

Two Truths & a Lie   Features of the Java Programming Language

1. Java was developed to be architecturally neutral, which means that anyone can build an application without
extensive study.

2. After you write a Java program, the compiler converts the source code into a binary program of bytecode.

3. You can create both console applications and windowed applications using Java.

The false statement is #1. Java was developed to be architecturally neutral, which means that you can use Java to
write a program that will run on any platform.

1.4 A
 nalyzing a Java Application That Produces
Console Output
At first glance, even the simplest Java application involves a fair amount of confusing syntax. Consider the application
in Figure 1-4. This program is written on seven lines, and its only task is to display First Java application on the screen.

Figure 1-4 The First class


public class First
{
public static void main(String[] args)
{
System.out.println("First Java application");
}
}

In program code in figures in this course, Java keywords as well as true, false, and null are blue, and
Note all other program elements are black. A complete list of Java keywords is shown later in this chapter.

The code for every complete program shown in this course is available in a set of student files you can
Note download so that you can execute the programs on your own computer.

Understanding the Statement That Produces the Output


Although the program in Figure 1-4 occupies several lines, it contains only one Java programming statement. This
statement does the actual work of the program:
System.out.println("First Java application");

Like all Java statements, this one ends with a semicolon. Most Java programming statements can be spread across as many
lines as you choose, as long as you place line breaks in appropriate places. For example, in the program in Figure 1-4, you
could place a line break immediately before or after the opening parenthesis, or immediately before or after the closing
parenthesis. However, you usually want to place a short statement on a single line.

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
1.4 Analyzing a Java Application That Produces Console Output 11

The text First Java application is a literal string of characters—a series of characters that will appear in output exactly as
entered. Any literal string in Java is written between double quotation marks. In Java, a literal string cannot be broken
and placed on multiple lines. Figure 1-5 labels this string and the other parts of the statement.

Figure 1-5 Anatomy of a Java statement

"First Java application"


out is a property of the is a literal string that is the argument
System is a class. System class. to the println() method.

System.out.println("First Java application");

Dots separate classes, println() is a method. Every Java statement ends


objects, and methods. Method names are always with a semicolon.
followed by parentheses.

The string within quotation marks, "First Java application", appears within parentheses because the string
is an argument to a method, and arguments to methods always appear within parentheses following the method name.
Arguments are pieces of information that are sent into a method. The act of sending arguments to a method is called
passing arguments to the method.

As an analogy, consider placing a catalog order with a company that sells sporting goods. Processing a catalog order
is a method that consists of a set of standard procedures—recording the order, checking the availability of the item,
pulling the item from the warehouse, and so on. Each catalog order also requires a set of data items, such as which
item number you are ordering and the quantity of the item desired; these data items can be considered the arguments
to the order-processing method. If you order two of item 5432 from a catalog, you expect different results than if you
order 1,000 of item 9008. Likewise, if you pass the argument "Happy Holidays" to a Java display method, you expect
different results than if you pass the argument "First Java application".

Within the statement System.out.println("First Java application");, the method to which you are
passing "First Java application" is named println(). The Java methods println() and print() both
produce output, with a small difference:

❯❯With println(), after the output is displayed, the insertion point moves to the following line so that
subsequent output appears on a new line.
❯❯With print(), the insertion point does not advance to a new line, so subsequent output appears at
the end of the current line.

When you call a method, you always use parentheses following the method name. In this course, you will learn about
many methods that require arguments between their parentheses, and many others for which you leave the paren-
theses empty. The println() method can be used with no arguments when you want to output a blank line. Later
in this chapter, you will learn about a method named showMessageDialog() that requires two arguments. Other
methods require more.

Within the statement System.out.println("First Java application");, out is an object that is a property
of the System class; out refers to the standard output device for a system, normally the monitor. The out object
itself is an instance of the PrintStream class, which contains several methods, including println(). Technically,
you could create the out object and write the instructions within the println() method yourself, but it would be
time consuming, and the creators of Java assumed you would want to frequently display output on a screen. Therefore,
the System and PrintStream classes, the out object, and the println() and print() methods were created as
conveniences for the programmer.

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
12 Chapter 1 Creating Java Programs

Within the statement System.out.println("First Java application");, System is a class. Therefore,


System defines attributes for System objects, just as the Dog class defines the attributes for Dog objects. One
of the System attributes is out. (You can probably guess that another attribute is in and that it represents an
input device.)

The dots (periods) in System.out.println() are used to separate the names of the components in the statement.
You will use this format repeatedly in your Java programs. Java is case sensitive; the class named System is a
completely different class from one named system, SYSTEM, or even sYsTeM, and out is a different object from one
named Out or OUT. You must pay close attention to using correct uppercase and lowercase values when you write
Java programs.

So, the statement that displays the string "First Java application" contains the following:

❯❯A class name

❯❯An object reference

❯❯A method call


❯❯A method argument

❯❯A statement-ending semicolon

The statement that displays the string cannot stand alone; it is embedded within a class, as shown in Figure 1-4.

Understanding the First Class


Everything that you use within a Java program must be part of a class. When you write public class First, you
are defining a class for which you have chosen the name First. You can define a Java class using any name or identifier
you need, as long as it meets the following requirements:

❯❯A Java identifier must begin with a letter of the English alphabet, a non-English letter (such as a or p), an
underscore, or a dollar sign. A class name cannot begin with a digit.
❯❯A Java identifier can contain only letters, digits, underscores, or dollar signs.

❯❯A Java identifier cannot be a reserved keyword, such as public or class. (See Figure 1-6 for a list of reserved
keywords.)

Figure 1-6 Java reserved keywords

The underscore _ double int strictfp


character is a abstract else interface super
reserved keyword
assert enum long switch
in Java.
boolean extends native synchronized
break final new this
byte finally non-sealed throw
catch float package throws
char for private transient
class goto protected try
const if public void
continue implements return volatile
default import short while
do instanceof static

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
1.4 Analyzing a Java Application That Produces Console Output 13

❯❯A Java identifier cannot be one of the following values: true, false, or null. These are not keywords (they
are primitive values), but they are reserved and cannot be used.
❯❯The following are not keywords, but their use is restricted in some contexts: permits, record, sealed, var,
and yield. It is better not to use these words as identifiers.

Java is based on Unicode, which is an international system of character representation. The term letter
Note indicates English-language letters as well as characters from Arabic, Greek, and other alphabets. You can
learn more about Unicode in Appendix B.

The first entry in Figure 1-6, the underscore, was added as a keyword in Java 9. The keyword non-sealed
Note was added in Java 15. The keyword non-sealed is unconventional, as no other keywords use a hyphen.

Although const and goto are reserved as keywords, they are not used in Java programs, and they have
Note no function. Both words are used in other languages and were reserved in case developers of future
versions of Java wanted to implement them.

It is a Java standard, although not a requirement, to begin class identifiers with an uppercase letter and employ other
uppercase letters as needed to improve readability. (By contrast, method identifiers, like println(), conventionally
begin with a lowercase letter.) The style that joins words in which each word begins with an uppercase letter is
called Pascal casing, or sometimes upper camel casing. You should follow established conventions for Java so your
programs will be easy for other programmers to interpret and follow. This course uses established Java programming
conventions.

Table 1-1 lists some valid and conventional class names that you could use when writing programs in Java. Table 1-2
provides some examples of class names that could be used in Java (if you use these class names, the class will compile)
but that are unconventional and not recommended. Table 1-3 provides some class name examples that are illegal.

Table 1-1 Some valid class names in Java


Class Name Description
Employee Begins with an uppercase letter
UnderGradStudent Begins with an uppercase letter, contains no spaces, and emphasizes each new word with an
initial uppercase letter
InventoryItem Begins with an uppercase letter, contains no spaces, and emphasizes the second word with an
initial uppercase letter
Budget2024 Begins with an uppercase letter and contains no spaces

Table 1-2 Legal but unconventional and nonrecommended class names in Java
Class Name Description
Undergradstudent New words are not indicated with initial uppercase letters, making this identifier difficult to read
Inventory_Item An underscore is not commonly used to indicate new words
BUDGET2024 Using all uppercase letters for class identifiers is not conventional
budget2024 Conventionally, class names do not begin with a lowercase letter

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
14 Chapter 1 Creating Java Programs

Table 1-3 Some illegal class names in Java


Class Name Description
Inventory Item The space character is illegal in an identifier
class class is a reserved keyword
2024Budget Class names cannot begin with a digit
phone# The number symbol (#) is illegal in an identifier

Figure 1-7 shows the parts of the First class shell in its first, second, and last lines—its header, and its opening and
closing curly braces. The class header contains the keyword class, which identifies First as a class. The keyword
public is an access specifier. An access specifier defines the circumstances under which a class can be accessed
and the other classes that have the right to use a class. Public access is the most liberal type of access; you will learn
about public access and other types of access when you learn more about methods.
After the class header, you enclose the contents of a class within curly braces ({ and }); any data items and methods
between the curly braces make up the class body. A class body can be composed of any number of data items and
methods. In Figure 1-7 (and again in Figure 1-8), the class First contains four lines between the curly braces; these
will be described in the next section.

Figure 1-7 The parts of a typical class

The keyword class


public is an access identifies First as First is the name of
specifier. a class. the class.

This line is
public class First
the class
header. {
public static void main(String[] args)
Everything {
between the System.out.println("First Java application");
curly braces is }
the class body. }

Understanding the main() Method


The main() method in Figure 1-8 is made up of the four lines between the curly braces of the First class.

Figure 1-8 The parts of a typical main() method

static means this method works without


instantiating an object of the class.

public is an access specifier. void is the method’s return type.

public class First


{
This line is the public static void main(String[] args)
method header.
{
System.out.println("First Java application");
Everything between
}
the curly braces is the
method body.
}

String is a class. Any The square brackets mean the args is the identifier of the array of
arguments to this method argument to this method is an Strings that is the argument to
must be String objects. array of Strings. You will this method.
learn about arrays later in this
course.

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
1.4 Analyzing a Java Application That Produces Console Output 15

A method header is the first line in a method; it contains information about how other methods can interact with it.
In Figure 1-8, the method header is public static void main(String[] args). The meaning and purpose
of each of the terms used in the method header will become clearer as you complete this course; a brief explanation
will suffice for now.

❯❯The keyword public is an access specifier, just as it is when you use it to define the First class.

❯❯The keyword static means that a method is accessible and usable even though no objects of the class
exist.
❯❯The keyword void indicates that the main() method does not return any value when it is called. This doesn’t
mean that main() doesn’t produce output—in fact, this method does. It only means that the main() method
does not send any value back to any other method that might use it. You will learn more about return values
when you study methods in more detail.
❯❯The name of the method is main(). As is the convention with Java methods, its identifier begins with
a lowercase letter. Not all classes have a main() method; in fact, many do not. All Java applications,
however, must include a class containing a public method named main(), and most Java applications
have additional classes and methods. When you execute a Java application, the JVM always executes the
main() method first.
❯❯In the method header, the contents between the parentheses, String[] args, represent the type of
argument that can be passed to the main() method, just as the string "First Java application"
is an argument passed to the println() method. The String class is a Java class that can be used to
hold character strings. According to Java convention, it begins with an uppercase letter, like other classes.
The brackets following String mean that the argument is a list of Strings. You will learn more about the
String class and lists later in this course. The identifier args is used to hold any String objects that
might be sent to the main() method. The main() method could do something with those arguments,
such as display them, but in Figures 1-4, 1-7, and 1-8, the main() method does not actually use the args
identifier. Nevertheless, you must place an identifier within the main() method’s parentheses. The
identifier does not need to be named args—it could be any legal Java identifier—but the name args is
traditional.

In this course, you won’t pass any arguments to a program’s main() method, but when you run a
Note program, you could. Even though you pass no arguments, the main() method must contain String[]
and a legal identifier (such as args) within its parentheses.

The simple application originally shown in Figure 1-4 has many Figure 1-9 Shell code
pieces to remember. However, for now, you can use the Java code
shown in Figure 1-9 as a shell, in which you replace AnyClassName public class AnyClassName
{
with a class name you choose and the line /******/ with any public static void main(String[] args)
statements that you want to execute. {
/******/
}
}
Indent Style
In general, whitespace is optional in Java. Whitespace is any com-
bination of nonprinting characters. You use whitespace to organize your program code and make it easier to read.
You can insert whitespace between words or lines in your program code by typing spaces, tabs, or blank lines
because the compiler ignores these extra spaces. However, you cannot use whitespace within an identifier or
keyword, or surrounding the dots in any class-object-method combination.

For every opening curly brace ({) in a Java program, there must be a corresponding closing curly brace (}), but the
placement of the opening and closing curly braces is not important to the compiler. For example, the following class

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
16 Chapter 1 Creating Java Programs

executes in exactly the same way as the one shown in Figure 1-4. The only difference is the layout of the braces—the
line breaks occur after the opening braces instead of before them.
public class First{
public static void main(String[] args){
System.out.println("First Java application");
}
}

The indent style shown in the preceding example, in which opening braces do not stand alone on separate
lines, is known as the K & R style and is named for Kernighan and Ritchie, who wrote the first book about the
C programming language. The indent style shown in Figures 1-4, 1-7, and 1-8, in which curly braces are aligned
and each occupies its own line, is called the Allman style and is named for Eric Allman, a programmer who
popularized the style. The Allman style is used throughout this course. However, Java programmers use a variety
of indent styles, and all can produce workable Java programs. When you write your own code, you should develop
a consistent style. In school, your instructor might have a preferred style, and when you get a job as a Java
programmer, your organization most likely will have a preferred style. With many development environments,
indentations are made for you automatically as you type.

Most programmers indent a method’s statements a few spaces more than its curly braces. Some programmers indent
two spaces, some three, and some four. Some programmers use the Tab key to create indentations, but others are
opposed to this practice because the Tab key can indicate different indentation sizes on different systems. Some pro-
grammers don’t care whether tabs or spaces are used, as long as they are not mixed in the same program. The Java
compiler does not care how you indent. Again, the most important rule is to develop a consistent style of which your
organization approves.

Saving a Java Class


When you write a Java class, you must save it using a writable storage medium such as a disk, DVD, or USB device. In
Java, if a class is public (that is, if you use the public access specifier before the class name), you must save the
class in a file with exactly the same name and a .java extension. For example, the First class must be stored in a file
named First.java. The class name and filename must match exactly, including the use of uppercase and lowercase char-
acters. If the extension is not .java, the Java compiler does not recognize the file as containing a Java class. Appendix
A contains additional information about saving a Java application.

Two Truths & a Lie   Analyzing a Java Application That Produces Console Output

1. In the method header public static void main(String[] args), the word public is an access specifier.

2. In the method header public static void main(String[] args), the word static means that a
method is accessible and usable, even though no objects of the class exist.

3. In the method header public static void main(String[] args), the word void means that the
main() method is an empty method.

The false statement is #3. In the method header public static void main(String[] args), the word void
means that the main() method does not return any value when it is called.

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
1.4 Analyzing a Java Application That Produces Console Output 17

You Do It   Your First Application

Now that you understand the basics of an application written in Java, you are ready to enter your own Java
application into a text editor. It is a tradition among programmers that the first program you write in any language
produces “Hello, world!” as its output. You will create such a program now. You can use any text editor, such as
Notepad or TextPad, or a development environment, such as Eclipse.

It is best to use the simplest available text editor when writing Java programs. Multifeatured word-
Note processing programs save documents as much larger files because of all the built-in features, such as font
styles and margin settings, which the Java compiler cannot interpret. Additionally, one school of thought
is that you should use a simple text editor such as Notepad because it does not provide features such as
automatically completing statements for you or color-coding language features, thus forcing you to better
learn all the nuances of the language.

1. Start the text editor, and then open a new document.

2. Type the class header as follows:

public class Hello


In this example, the class name is Hello. You can use any valid name you want for the class. If you choose
Hello, you always must refer to the class as Hello, and not as hello, because Java is case sensitive.

3. Press Enter once, type { (opening curly brace), press Enter again, and type } (closing curly brace). You will add
the main() method between these curly braces. Although it is not required, the convention used in this course
is to place each curly brace on its own line and to align opening and closing curly brace pairs with each other.
Using this format makes your code easier to read.

4. As shown in Figure 1-10, add the main() method header between the curly braces, and then type a set of
curly braces for main().

5. Next, add the statement within the main() method that will produce the output Hello, world!. Use Figure 1-11
as a guide for adding the println() statement to the main() method.

6. Save the application as Hello.java. The class name and filename must match exactly, and you must use the .java
extension.

Figure 1-10 The main() method shell Figure 1-11 Complete Hello class
for the Hello class
public class Hello
public class Hello {
{ public static void main(String[] args)
public static void main(String[] args) {
{ System.out.println("Hello, world!");
} }
} }

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
18 Chapter 1 Creating Java Programs

1.5 C
 ompiling a Java Class and Correcting
Syntax Errors
After you write and save an application, two steps must occur before you can view the application’s output.

1. You must compile the class you wrote (called the source code) into bytecode.
2. You must use the Java interpreter to translate the bytecode into executable statements.

Compiling a Java Class


If you are using a development environment, you can compile your program by clicking the Compile button or by
clicking the Build menu and selecting Compile. If you are using a text editor such as Notepad, you can compile your
source code file from the command line. Your prompt should show the folder or directory where your program file is
stored. Then you type javac followed by the name of the file that contains the source code. For example, to compile
a file named First.java, you type the following and then press Enter:
javac First.java

Compiling the program will produce one of three outcomes:

❯❯You receive a message such as 'javac' is not recognized as an internal or external


command, operable program or batch file.
❯❯You receive one or more programming language error messages.

❯❯You receive no messages, which means that the application compiled successfully.

When compiling, if the source code file is not in the current path, you can type a full path with the
Note filename. For example:

javac c:\java\MyClasses\Chapter.01\First.java

In a DOS environment, you can change directories using the cd command. For example, to change from
Note the current directory to a subdirectory named MyClasses, you type cd MyClasses and press Enter.
Within any directory, you can back up to the root directory by typing cd\ and pressing Enter.

If you receive an error message that the command is not recognized, it might mean one of the following:

❯❯You misspelled the command javac.

❯❯You misspelled the filename.

❯❯You are not within the correct subfolder or subdirectory on your command line.

❯❯Java was not installed properly, or the class or classpath variable was not set correctly.
(See Appendix A for information about installation, class, and classpath.)

If you receive a programming language error message, it means the source code has one or more syntax errors. Recall
that a syntax error is a programming error that occurs when you introduce typing errors into your program or use
the programming language incorrectly. For example, if your class name is first (with a lowercase f  ) in the source
code but you saved the file as First.java (with an uppercase F ), you will receive an error message when you compile
the application. The error message will be similar to class first is public, should be declared in a file named first.java

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
1.5 Compiling a Java Class and Correcting Syntax Errors 19

because first and First are not the same in a case-sensitive language. If this error occurs, you must reopen the text file
that contains the source code, make the necessary corrections, and then save the file and attempt to compile it again.

Appendix A contains information about troubleshooting, including how to change filenames in a


Note Windows environment.

If you receive no error messages after compiling the code in a file named First.java, the application compiled successfully.
In that case, a file named First.class is created and saved in the same folder as the text file that holds the source code.
After a successful compile, you can execute the program (run the class file) on any computer that has a Java language
interpreter. You will learn how to execute a program in the next section.

Correcting Syntax Errors


Frequently, you might make typing errors as you enter Java statements into your text editor. When you issue the com-
mand to compile a class containing errors, the Java compiler produces one or more error messages. The exact error
message that appears varies depending on the compiler you are using.

The FirstWithMissingSemicolon class shown in Figure 1-12 contains an error—the semicolon is missing at the
end of the println() statement. (Of course, this class has been helpfully named to alert you to the error.) When you
compile this class, an error message similar to the one shown in Figure 1-13 is displayed.

Figure 1-12 The FirstWithMissingSemicolon class

public class FirstWithMissingSemicolon


{
Don’t Do It
public static void main(String[] args) The statement-ending
semicolon has been
{ omitted.
System.out.println("First Java application")
}

Figure 1-13 Error message generated when the FirstWithMissingSemicolon


class is compiled

The first line of the error message in Figure 1-13 displays the name of the file in which the error was found
(FirstWithMissingSemicolon.java), the line number in which it was found (5), and the nature of the error (’;’ expected).
The next line of the error message displays the statement that contains the error, including a caret that points to the
exact location where the error was first discovered. As you will see when you write and compile Java programs, the

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
20 Chapter 1 Creating Java Programs

place where an error is discovered is not necessarily where the error was made. For example, sometimes an error is
not discovered until the line that follows the line that contains the error. Fairly frequently, it takes a little detective
work to interpret an error message and determine its cause.

Finally, the message generated in Figure 1-13 includes a count of the number of errors found—in this case, there is just
one error. This error is an example of a compile-time error, or one in which the compiler detects a violation of language
syntax rules and is unable to translate the source code to machine code.

When you compile a class, the compiler reports as many errors as it can find so that you can fix as many errors as
possible. Sometimes, one error in syntax causes multiple error messages that normally would not be errors if the
first syntax error did not exist, so fixing one error might eliminate multiple error messages. Sometimes, when you fix
a compile-time error and recompile a program, new error messages are generated. That’s because when you fix the
first error, the compiler can proceed beyond that point and possibly discover new errors. Of course, no programmer
intends to type a program containing syntax errors, but when you do, the compiler finds them all for you.

Two Truths & a Lie   Compiling a Java Class and Correcting Syntax Errors

1. After you write and save an application, you can compile the bytecode to create source code.

2. When you compile a class, you create a new file with the same name as the original file but with a .class
extension.

3. Syntax errors are compile-time errors.

The false statement is #1. After you write and save an application, you can compile the source code to create
bytecode.

You Do It   Compiling a Java Class

You are ready to compile the Hello class that you created in the previous “You Do It” section.

1. If it is not still open on your screen, open the Hello.java file that you saved in the previous “You Do It” section.

2. If you are using a development environment, you can compile a program by clicking the Compile button.
Otherwise, you can compile a program from the command prompt. Go to the command-line prompt for the
drive and folder or subdirectory in which you saved Hello.java. At the command line, type the following:

javac Hello.java

After a few moments, you should return to the command prompt. If you see error messages instead, reread the
previous section to discover whether you can determine the source of the error.

If the error message indicates that the command was not recognized, make sure that you spelled the javac
command correctly, including using the correct case. Also, make sure you are using the correct directory or folder
where the Hello.java file is stored.

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
1.5 Compiling a Java Class and Correcting Syntax Errors 21

If the error message indicates a language error, check your file against Figure 1-11, making sure it matches exactly.
Fix any errors, and compile the application again. If errors persist, read through the next section to see if you can
discover the solution.
Correcting Syntax Errors
In this section, you examine error messages and gain firsthand experience with syntax errors.

1. If your version of the Hello class did not compile successfully, examine the syntax error messages. Now that
you know the messages contain line numbers and carets to pinpoint mistakes, it might be easier for you to fix
problems. After you determine the nature of any errors, resave the file and recompile it.

2. Even if your Hello class compiled successfully, you Figure 1-14 The HelloErrors class
need to gain experience with error messages. Your
student files contain a file named HelloErrors.java. public class HelloErrors
{
Find this file and open it in your text editor. If you do public static void main(String[] args)
not have access to the student files that accompany {
System.out.println("Hello");
this course, you can type the file yourself, as shown System.out.println("This is a test");
in Figure 1-14. }
}
3. Save the file as HelloErrors.java in the folder in which
you want to work. Then compile the class using the
following command to confirm that it compiles without error:

javac HelloErrors.java
4. In the first line of the file, remove the c from class, making the first line read public lass HelloErrors. Save
the file and compile the program. Error messages are generated similar to those shown in Figure 1-15. Even
though you changed only one keystroke in the file, four error messages appear. The first indicates that class,
interface, or enum is expected in line 1. You haven’t learned about the Java keywords enum or interface
yet, but you know that you caused the error by altering the word class. The next three errors in lines 3, 6, and 7
show that the compile is continuing to look for one of the three keywords, but fails to find them.

Figure 1-15 Error messages generated when class is misspelled in the


HelloErrors program

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
22 Chapter 1 Creating Java Programs

5. Repair the program by reinserting the c in class. Save the file and compile it again. The program should
compile successfully. In this case, when you fix one error, four error messages are removed.

6. Next, remove the word void from the third line of the program. Save the file and compile it. Figure 1-16
shows the error message, which indicates that a return type is required. The message does not indicate
that void is missing because Java supports many return types for methods. In this case, however, void is
the correct return type, so reinsert it into the correct place in the program, and then save and recompile
the file.

Figure 1-16 Error message generated when void is omitted from the
main() method header in the HelloErrors program

7. Remove the final closing curly brace from the HelloErrors program. Save the file and recompile it.
Figure 1-17 shows the generated message “reached end of file while parsing.” Parsing is the process the
compiler uses to divide your source code into meaningful portions; the message means that the compiler
was in the process of analyzing the code when the end of the file was encountered prematurely. If you repair
the error by reinserting the closing curly brace, saving the file, and recompiling it, you remove the error
message.

Figure 1-17 Error message generated when the closing curly brace is
omitted from the HelloErrors program

8. Continue to introduce errors in the program by misspelling words, omitting punctuation, and adding
extraneous keystrokes. Remember to save each program version before you recompile it; otherwise, you will
recompile the previous version. When error messages are generated, read them carefully and try to understand
their meaning in the context of the error you purposely caused. After all compiler error messages have been
eliminated, you can run the program using the java command.

Occasionally, even though you inserted an error into the program, no error messages will be generated. That
does not mean your program is correct. It only means that the program contains no syntax errors. A program
can be free of syntax errors but still not be correct, as you will learn in the next section.

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
1.6 Running a Java Application and Correcting Logic Errors 23

1.6 R
 unning a Java Application and Correcting
Logic Errors
After a program compiles with no syntax errors, you can execute it. Just because a program compiles and executes,
however, does not mean the program is error free.

Running a Java Application


To run an application from a development environment, you can click the Run button or click the Build menu and then
click Run. To run the First application from the command line, you type the following:
java First

Figure 1-18 shows the application’s output in the command window. In Figure 1-18 Output of the First
this example, you can see that the First class is stored in a folder named application
Java on the C drive. After you type the java command to execute the
program, the literal string in the call to the println() method is output,
so First Java application appears on the screen. Control then returns to
the command prompt.

The procedure to confirm the storage location of your First.java class varies depending on your operating
Note system. In a Windows operating system, for example, you can open Windows Explorer, locate the icon
representing the storage device you are using, find the folder in which you have saved the file, and
expand the folder. You should see the First.java file.

When you run a Java application using the java command, do not add the .class extension to the filename. If you type
java First, the interpreter looks for a file named First.class. If you type java First.class, the interpreter looks
for a file named First.class.class.

Modifying a Compiled Java Class


After viewing the application output, you might decide to modify the class to get a different result. For example, you
might decide to change the First application’s output from First Java application to the following:
My new and improved
Java application

To produce the new output, first you must modify the text Figure 1-19 First class containing output
file that contains the existing class. You need to change the modified from the original version
existing literal string and then add an output statement for
public class First
another text string. Figure 1-19 shows the class that changes
{
the output. public static void main(String[] args)
{
The changes to the First class include the addition of System.out.println("My new and improved");
System.out.println("Java application");
the statement System.out.println("My new and }
improved"); and the removal of the word First from the }
string in the other println() statement.

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
24 Chapter 1 Creating Java Programs

If you make changes to the file, as shown in Figure 1-19, and save the file without recompiling it, then when you execute
the program by typing java First at the command line, you will not see the new output—you will see the old output
without the added line. Even though you save a text file that contains the modified source code for a class, the class
in the already-compiled class file executes. After you save the file named First.java, the previously compiled version
of the class with the same name is still stored on your computer. Before the new source code can execute, you must
do the following:

1. Save the file with the changes (using the same filename).
2. Recompile the class with the javac command.
3. Interpret the class bytecode and execute the class using the java command.

Figure 1-20 shows the new output. Figure 1-20 Execution of modified
First class
When you recompile a class, the original version of the compiled
file with the .class extension is replaced, and the original version no
longer exists. When you modify a class, you must decide whether
you want to retain the original version. If you do, you must give the
new version a new class name and a new filename, or you must save
it in a different folder.

Once in a while, when you make a change to a Java class and then recompile and execute it, the old
Note version still runs. The simplest solution is to delete the .class file and compile again. Programmers call this
creating a clean build.

Correcting Logic Errors


A second kind of error occurs when the syntax of the program is Figure 1-21 Output of FirstBadOutput
correct and the program compiles but produces incorrect results program
when you execute it. This type of error is a logic error, which is
often more difficult to find and resolve. For example, Figure 1-21
shows the output of the execution of a successfully compiled pro-
gram named FirstBadOutput. If you glance at the output too
quickly, you might not notice that Java is misspelled. The compiler
does not find spelling errors within a literal string; it is legitimate
to produce any combination of letters as output. Other examples
of logic errors include multiplying two values when you meant to add, printing one copy of a report when you meant
to print five, or forgetting to produce a total at the end of a business report when a user has requested one. Errors of
this type must be detected by carefully examining the program output. It is the responsibility of the program author
to test programs and find any logic errors.

You have already learned that syntax errors are compile-time errors. A logic error is a type of runtime error—an error
not detected until the program asks the computer to do something wrong, or even illegal, while executing. Not all
runtime errors are the fault of the programmer. For example, a computer’s hardware might fail while a program is
executing. Good programming practices, however, can help to minimize runtime errors.

The process of fixing computer errors has been known as debugging since a large moth was found
Note wedged into the circuitry of a mainframe computer at Harvard University in 1947. You can search the Web
for pictures of the moth.

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
1.7 Adding Comments to a Java Class 25

Two Truths & a Lie   Running a Java Application and Correcting Logic Errors

1. In Java, if a class is public, you must save the class in a file with exactly the same name and a .java
extension.

2. To compile a file named MyProgram.java, you type java MyProgram, but to execute the program, you
type java MyProgram.java.

3. When you compile a program, sometimes one error in syntax causes multiple error messages.

The false statement is #2. To compile a file named MyProgram.java, you type javac MyProgram.java, but to
execute the program, you type the following:

java MyProgram

1.7 Adding Comments to a Java Class


As you can see, even the simplest Java class requires several lines of code and contains somewhat perplexing
syntax. Large applications that perform many tasks include much more code, and as you write larger applications,
it becomes increasingly difficult to remember why you included steps or how you intended to use particular
variables. Documenting your program code helps you remember why you wrote lines of code the way you did.
Program comments are nonexecuting statements that you add to a program for the purpose of documentation.
In other words, comments are designed for people reading the source code and not for the computer executing
the program.

Programmers use comments to leave notes for themselves and for others who might read their programs in the future.
At the very least, your Java class files should include comments indicating the author, the date, and the class name
or function. The best practice dictates that you also include a brief comment to describe the purpose of each method
you create within a class.

As you work through this course, add comments as the first lines of every file. The comments should contain the class
name and purpose, your name, and the date. Your instructor might ask you to include additional comments.

Turning some program statements into comments can sometimes be useful when you are developing an application.
If a program is not performing as expected, you can “comment out” various statements and subsequently run the pro-
gram to observe the effect. When you comment out a statement, you turn it into a comment so the compiler does not
translate it, and the JVM does not execute its command. This can help you pinpoint the location of errant statements
in malfunctioning programs.

Java supports three types of comments:

❯❯Line comments start with two forward slashes ( // ) and continue to the end of the current line. A line comment
can appear on a line by itself or at the end (and to the right) of a line following executable code. Line comments
do not require an ending symbol.
❯❯Block comments start with a forward slash and an asterisk ( /* ) and end with an asterisk and a forward slash
( */ ). A block comment can appear on a line by itself, on a line before executable code, or on a line after
executable code. Block comments also can extend across as many lines as needed.
❯❯Javadoc comments are a special case of block comments called documentation comments because they are
used to automatically generate nicely formatted program documentation with a program named Javadoc.
Javadoc comments begin with a forward slash and two asterisks ( /** ) and end with an asterisk and a forward
slash ( */ ). Appendix E teaches you how to create Javadoc comments.

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Another Random Scribd Document
with Unrelated Content
CHAPTER IX.

HARAR—THE MOSLEM ABYSSINIA—THE TIMBUCTOO OF


EAST AFRICA, THE EXPLORATION OF WHICH HAD BEEN
ATTEMPTED IN VAIN BY SOME THIRTY TRAVELLLERS.

Richard returned up the Red Sea to Egypt, and much enjoyed the
rest and safety for a short time, and then returned to Bombay, his
leave being up; but the wandering fever was still upon him, and as
the most difficult place for a white man to enter was Harar, in
Somali-land, Abyssinia, he determined that that should be his object.
It is inhabited by a very dangerous race to deal with, and no white
man had ever penetrated to Harar. The first white man who went to
Abyssinia was kept prisoner till he died. The East India Company had
long wished to explore it, because Berberah, the chief port of
Somali-land, is the safest and best harbour on the western side of
the Indian Ocean—far better than Aden. They went to work with
that strange mixture of caution and generosity with which they
treated those of their servants who stepped out of what Richard calls
their "quarter-deck" routine, that is, to let him go as a private
traveller, and the Government to give him no protection, but would
allow him to retain the same pay that he would enjoy whilst on
leave. Dr. Carter and others refused to do more than to coast along
in a cruiser.
Richard applied for Lieutenant Herne, of the 1st Bombay Fusiliers,
Lieutenant Stroyan, Indian Navy, and Lieutenant Speke, 46th Bengal
Native Infantry. Herne was distinguished by his surveys,
photography, and mechanics on the west coast of India, in Scinde,
and on the Punjaub rivers; Stroyan as amateur surveyor; and Speke,
collector of the Fauna of Tibet and the Himalayas and sportsman.
Assistant-Surgeon Ellerton Stocks, botanist, traveller, and a first-rate
man in all ways, died before the expedition started.
Jealousy, as usual, immediately rose up in opposition. First, Sir
James Outram, Political Resident at Aden, called it a tempting of
Providence, and Dr. Buist, the editor of the Bombay Times, was told
to run down the Somali Expedition, in which task he was assisted by
the unpopular chaplain. This was not very gratifying to four high-
spirited men; so, instead of using Berberah as a base of operations,
then westward to Harar, and then south-east to Zanzibar, the
Resident changed the whole scheme and made it fail. Herne was to
go to Berberah, where he was joined later by Stroyan. Speke was to
land in a small harbour called Bunder Guray, and to trace the
watershed of the Wady Nogal, to buy horses and camels, and collect
red earth with gold in it; but his little expedition failed through his
guide's treachery. Herne and Stroyan succeeded. Richard reserved
for himself the post of danger. Harar was as difficult to enter as
Mecca. It is the southernmost masonry-built settlement in North
Equatorial Africa. He would go as an Arab merchant. Harar had
never been visited, has its own language, its own unique history and
traditions. The language was unwritten, but he wrote a grammar,
and a vocabulary in which the etymology is given, and there he had
enough savage anthropology to interest him. He writes—

"In the first place, Berberah is the true key of the Red Sea, the
centre of East African traffic, and the only safe place for
shipping upon the Western Erythræan shore, from Suez to
Guardafui, backed by lands capable of cultivation, and by hills
covered with pine and other valuable trees, enjoying a
comparatively temperate climate, with a regular, though thin
monsoon. This harbour has been coveted by many a foreign
conqueror. Circumstances have thrown it into our arms, and if
we refuse a chance, another and a rival nation will not be so
blind. [We have since given it away, and kept the far inferior
Aden.] We are bound to protect the lives of subjects on this
coast. In 1825 the crew of the Mary Ann brig was treacherously
murdered by the Somal. They continued in that state, and if to-
morrow a Peninsular and Oriental Company steamer by any
chance fell into their power, it would be the same history. Harar,
scarcely three hundred miles distance from Aden, is a
counterpart of the ill-famed Timbuctoo. A tradition exists that
with the entrance of the first Christian, Harar will fall. All
therefore who have attempted it were murdered. It was
therefore a point of honour with me to utilize my title of Haji, by
entering this City, visiting its Ruler, and returning in safety, after
breaking the Guardian's spell."

This exploration of Harar was one of Richard's most


He starts for
Harar in splendid and dangerous expeditions, and, for some
Somali-land.
reason or other, the least known; the reason being, as I
think, that his pilgrimage to Mecca was still making a great noise,
and that the Crimean War had cropped up, deadening the interest in
all personal adventure. He therefore thought himself fortunate in
being able to persuade Lord Elphinstone, Governor of Bombay, to
patronize an expedition into Somali-land.
He was away four months. The journey was useful; at least, it has
proved so to the Egyptians, to the English, and now to the Italians.
He sailed away, leaving Herne, Stroyan, and Speke, each engaged
on his respective work, and arrived at Zayla.

"My ship companions," he writes, "were the wildest of the wild,


and as we came into port Zayla a barque came up to give us the
bad news. Friendship between the Amir of Harar and the
Governor of Zayla had been broken; the road through the Eesa
Somal had been closed by the murder of Masúd, a favourite
slave and adopted son of Sharmarkay; all strangers had been
expelled the City for some misconduct by the Harar chief;
moreover, small-pox was raging there with such violence that
the Galla peasantry would allow neither ingress nor egress. The
tide was out, and we waded a quarter of a mile amongst giant
crabs, who showed gristly claws, sharp coralline, and seaweed
so thick as to become almost like a mat. In the shallower pacts
the sun was painfully hot even to my well-tried feet. I was taken
immediately to the Governor at Zayla, a fellow Haji, who gave
me hospitality.
"The well-known sounds of El Islam returned from memory.
Again the melodious chant of the muezzin—no evening bell can
compare with it for solemnity and beauty—and in the
neighbouring Mosque, the loudly intoned 'Amin' and 'Allaho
Akbar,' far superior to any organ, rang in my ear. The evening
gun of camp was represented by the nakkarah, or kettle-drum,
which sounded about seven p.m. at the southern Gate; and at
ten a second drumming warned the paterfamilias that it was
time for home, and thieves and lovers, that it was the hour for
bastinado. Nightfall was ushered in by the song, the dance, and
the marriage festival—here no permission is required for 'native
music in the lines'—and muffled figures flitted mysteriously
through the dark alleys.

"After a peep through the open window, I fell asleep, feeling


once more at home.
Preparations "I was too much of an Arab to weary of the endless
at Zayla. preparations for forming a caravan. I used to provide
myself with a Korán and sit receiving visitors, and
would occasionally go into the Mosque, my servant carrying the
prayer carpet, three hundred pair of eyes staring at me, and
after reciting the customary two-bow prayer, in honour of the
Mosque, I would place a sword and rosary before me, and,
taking the Korán, read the cow-chapter, No. 18, in a loud and
twanging voice. This is the character I adopted. You will bear in
mind, if you please, that I am a Moslem merchant, a character
not to be confounded with the notable individuals seen on
''Change.' Mercator, in the East, is a compound of tradesmen,
divine, and T.G. Usually of gentle birth, he is everywhere
welcomed and respected; and he bears in his mind and manner
that, if Allah please, he may become Prime Minister a month
after he has sold you a yard of cloth. Commerce appears to be
an accident, not an essential, with him, yet he is by no means
deficient in acumen. He is a grave and reverend seignior, with
rosary in hand and Korán on lip; is generally a pilgrim; talks at
dreary length about Holy Places; writes a pretty hand; has read
and can recite much poetry; is master of his religion; demeans
himself with respectability; is perfect in all points of ceremony
and politeness, and feels equally at home whether Sultan or
slave sit upon his counter. He has a wife and children in his own
country, where he intends to spend the remnant of his days; but
'the world is uncertain'—'Fate descends, and man's eyes seeth it
not'—'the earth is a charnel-house;' briefly, his many old saws
give him a kind of theoretical consciousness that his bones may
moulder in other places but his fatherland.
"For half a generation we have been masters of Aden, filling
Southern Arabia with our calicos and rupees—what is the
present state of affairs there? We are dared by the Bedouins to
come forth from behind our stone walls and fight like men in the
plain,—British protégés are slaughtered within the range of our
guns,—our allies' villages have been burned in sight of Aden,—
our deserters are welcomed and our fugitive felons protected,—
our supplies are cut off, and the garrison is reduced to extreme
distress, at the word of a half-naked bandit,—the miscreant
Bhagi, who murdered Captain Mylne in cold blood, still roams
the hills unpunished,—gross insults are the sole
acknowledgements of our peaceful overtures,—the British flag
has been fired upon without return, our cruisers being ordered
to act only on the defensive,—and our forbearance to attack is
universally asserted and believed to arise from mere cowardice.
Such is, and such will be, the opinion and the character of the
Arab!
"I stayed here for twenty-six days, rising at dawn; then went to
the Terrace to perform my devotions, and make observation of
my neighbours; breakfast at six, then coffee, pipe, and a nap;
then receive visitors, who come by dozens with nothing to do or
say. When they were only Somal, I wrote Arabic, or extracted
from some useful book. When Arabs were there, I would recite
tales from the 'Arabian Nights,' to their great delight. At eleven,
dinner, more coffee and pipes; then the natives would go to
sleep, and I wrote my journals and studies. At about two p.m.
more visitors would come, and at sunset again to the Terrace,
or walk to a mosque, where games are going on, or stroll to a
camp of Bedawi. The Gates are locked at sunset, and the keys
are carried to the Haji. It is not safe to be without the City later.
Then comes supper.
"After it we repair to the roof to enjoy the prospect of the far
Tajarrah Hills and the white moonbeams sleeping upon the
nearer sea. The evening star hangs like a diamond upon the still
horizon; around the moon a pink zone of light mist, shading off
into turquoise blue and a delicate green-like chrysopraz, invests
the heavens with a peculiar charm. The scene is truly
suggestive; behind us, purpling in the night air and silvered by
the radiance from above, lie the wolds and mountains tenanted
by the fiercest of savages, their shadowy mysterious forms
exciting vague alarms in the traveller's breast. Sweet as the
harp of David, the night-breeze and the music of the water
comes up from the sea; but the ripple and the rustling sound
alternate with the hyæna's laugh, and the jackal's cry, and the
wild dog's lengthened howl.
Desert "This journey, which occupied nearly four months,
Journey. was to be through a savage, treacherous, ferocious,
and bloodthirsty people, whose tribes were in a
constant state of blood-feud. The party consisted of nine, an
abban or guide, three Arab matchlock men, two women cooks,
who were called Shehrazade and Deenarzade after the 'Arabian
Nights,' a fourth servant, and a Bedawin woman to drive a
donkey, which camels will follow and which is the custom. We
had four or five mules, saddled and bridled, and camels for the
baggage. Every one wept over us, and considered us dead men.
The abban objected to some routes on account of avoiding
tribes with which he had a blood-feud."
This was, as I have said, far the most dangerous of Richard's
explorations, quite as difficult as Mecca, and far more difficult than
anything Stanley has ever done, with his advantages of men, money,
and luxuries. The women seemed to be much hardier than the men;
they carried the pipe and tobacco, led the camels, adjusted the
burdens, at the halt unloaded the cattle, disposed the baggage,
covered them with a mat tent, cooked the food, made tea and
coffee, and bivouacked outside the tent.
He writes—

"The air was fresh and clear; and the night breeze was delicious
after the stormy breath of day. The weary confinement of walls
made the weary expanse a luxury to the sight, whilst the
tumbling of the surf upon the near shore, and the music of the
jackal, predisposed to sweet sleep. We now felt that at length
the die was cast. Placing my pistols by my side, with my rifle
butt for a pillow, and its barrel as a bed-fellow, I sought repose
with none of the apprehension which even the most stout-
hearted traveller knows before the start. It is the difference
between fancy and reality, between anxiety and certainty; to
men gifted with any imaginative powers the anticipation must
ever be worse than the event. Thus it happens, that he who
feels a thrill of fear before engaging in a peril, exchanges it for a
throb of exultation when he finds himself hand to hand with the
danger."

The description of the journey is filled in his notes by being hindered


and almost captured by Bedawi, lamed with thorns, the camels
casting themselves down from fatigue, famishing from hunger, and,
worse, from thirst—the only water being sulphurous, which affected
both man and beast—and attacks from lions, sleep being disturbed
by large ants, three-quarters of an inch long, with venomous stings.
Everywhere they went, everybody wept over them, as dead men. He
finds time, nevertheless, to remark, that at the height of 3350 feet
he found a buttercup and heard a woodpecker tapping, that
reminded him of home. He describes a sham attack of twelve
Bedawi, who, when they saw what his revolver could do, said they
were only in fun.
At one of the kraals he gives an account of how, being surrounded
by Somals, they were boasting of their shooting, and of the skill with
which they used the shield, but they seemed not to understand the
proper use of the sword.

"Thinking it was well to impress them with the superiority of


arms, I requested them to put up one of their shields as a mark.
They laughed very much, but would not comply. The Somal hate
a vulture, because it eats the dead and dying; so, seeing a large
brown bare-necked vulture at twenty paces distance, I shot it
with my revolver; then I loaded a gun with swan-shot, which
they had never seen, and, aiming at a bird that they considered
far out of gunshot distance, I knocked it over flying. Fresh
screams followed this marvellous feat, and they said, 'Lo! he
bringeth down the birds from heaven.' Their Chief, putting his
forefinger in his mouth, praised Allah, and prayed to be
defended from such a calamity; and always after, when they
saw me approach, they said, 'Here comes the Shaykh who
knows knowledge.' I then gave a stick to the best man; I
provided myself in the same way, and allowed him to cut at me
as much as ever he liked, easily warding off the blows with a
parry. After repeated failures, and tiring himself enormously, he
received a sounding blow from me upon the least bony part of
his person. The crowd laughed long and loud, and the knight-at-
arms retired in confusion.
"Every now and then we got into difficulties with the Bedawi,
who would not allow us to proceed, declaring the land was
theirs. We did not deny the claim, but I threatened sorcery,
death, and wild beasts, and foraging parties to their camels,
children, and women. It generally brought them to their senses.
They would spit on us for good luck, and let us depart. Once a
Chief was smitten by Shehrazade's bulky charms, and wanted to
carry her off. Once in the evening we came upon the fresh trail
of a large Habr Awal cavalcade, which frightened my
companions dreadfully. We were only nine men and two
women, to contend against two hundred horsemen, and all,
except the Hammal and Long Guled, would have run away at
the first charge. The worst of the ride was over rough and stony
road, the thorns tearing their feet and naked legs, and the
camels slipping over the rounded pebbles.
"The joy of coming to a kraal was great, where the Chiefs of the
village appeared, bringing soft speech, sweet water, new milk,
fat sheep and goats, for a tobe of Cutch canvas. We passed a
quiet, luxurious day of coffee and pipes, fresh cream and
roasted mutton. After the great heats and dangers from
horsemen on the plain, we enjoyed the cool breeze of the hills,
cloudy skies, and the verdure of the glades which refreshed our
beasts. Here I shot a few hawks, and was rewarded with loud
exclamations of 'Allah preserve thy hand! may thy skill never fail
thee before the foe.' A woman ran away from my steam kettle,
thinking it was a weapon. They looked upon my sunburnt skin
with a favour they denied to the lime-white face. The Somali
Bedawi gradually affiliated me to their tribes.
"At one village the people rushed out, exclaiming, 'Lo! let us
look at the Kings;' at others, 'Come and see the white man; he
is the Governor of Zayla.' My fairness (for, brown as I am, I am
fair to them) and the Arab dress made me sometimes the ruler
of Aden, the Chief of Zayla, the Haji's son, a boy, an old woman,
a man painted white, a warrior in silver armour, a merchant, a
pilgrim, a head priest, Ahmed the Indian, a Turk, an Egyptian, a
Frenchman, a Banyan, a Sheríf, and, lastly, a calamity sent down
from heaven to weary out the lives of the Somal. Every kraal
had its own conjecture.
"On December 9th, I rode a little off my way to visit some ruins,
Darbíyah Kola, or Kola's Fort, so called on account of its Galla
queen. There were once two cities, Aububah, and they fought
like the Kilkenny cats till both were eaten up. This was about
three hundred years ago, and the substantial ruins have fought
a stern fight with Time.
"Remnants of houses cumber the soil, and the carefully built
wells are filled with rubbish. The palace was pointed out to me,
with its walls of stone and clay, intersected by layers of
woodwork. The Mosque is a large, roofless building, containing
twelve square pillars of rude masonry, and the mihrab, or prayer
niche, is denoted by a circular arch of tolerable construction. But
the voice of the muezzin is hushed for ever, and creepers now
twine around the ruined fane. The scene was still and dreary as
the grave; for a mile and a half in length all was ruins—ruins—
ruins.
"Leaving this Dead City, we rode towards the south-west
between two rugged hills. Topping the ridge, we stood for a few
minutes to observe the view before us. Beneath our feet lay a
long grassy plain—the sight must have gladdened the hearts of
our starving mules—and for the first time in Africa horses
appeared grazing free amongst the bushes. A little further off
lay the Aylonda Valley, studded with graves and dark with
verdure. Beyond it stretched the Wady Haráwwah, a long
gloomy hollow in the general level. The background was a bold
sweep of blue hill, the second gradient of the Harar line, and on
its summit, closing the western horizon, lay a golden streak, the
Marar Prairie. Already I felt at the end of my journey.
"It was not an unusual thing in the dusk to see a large animal
following us with quick stealthy strides, and that I, sending a
rifle ball as correctly as I could in the direction, put to flight a
large lion.
"The nearer I got to Harar, the more I was stopped by parties of
Gallas, and some went on to report evil of me, and many
threats were uttered. The 'End of Time' in the last march turned
tail. 'Dost thou believe me to be a coward, O Pilgrim?' 'Of a
truth I do,' I answered. Nothing abashed, and with joy at his
heart, he hammered his mule with his heel, and rode off,
saying, 'What hath man but a single life, and he who throweth it
away, what is he but a fool?'"

He gives a good account of elephant-hunting, but they did not get


near any. The water was in some places so hard it raised lumps like
nettle-stings, and they had to butter themselves. At one place the
inhabitants flocked out to stare at them. He fired his rifle by way of
salute over the head of the prettiest girl. The people, delighted,
exclaimed, "Mod! Mod! honour to thee!" and he replied with shouts
of "Kulliban! may Heaven aid thee!"

"When there is any danger a Somali watchman sings and


addresses himself in dialogue, with different voices, to persuade
thieves that several men are watching. Ours was a spectacle of
wildness as he sat before the blazing fire. The 'End of Time'
conceived the jocose idea of crowning me King of the country,
with loud cries of 'Buh! Buh! Buh!' while showering leaves from
a gum tree and water from a prayer-bottle over my head, and
then with all solemnity bound on my turban. I was hindered and
threatened in no end of places, and my companions threatened
to desert me, saying, 'They will spoil that white skin of thine at
Harar.' Still I pushed on. The Guda Birsi Bedawi number ten
thousand spears.
"One night we came upon a sheet of bright blaze, a fire
threatening the whole prairie.
"At last came the sign of leaving the Desert. The scene lifted,
and we came to the second step of the Ethiopian highlands. In
the midst of the valley beneath ran a serpentine of shining
waters, the gladdest spectacle we had yet witnessed. Further in
front, masses of hill rose abruptly from shady valleys, encircled
on the far horizon by a straight blue line of ground resembling a
distant sea. Behind us glared the desert. We had now reached
the outskirts of civilization, where man, abandoning his flocks
and herds, settles, cultivates, and attends to the comforts of
life.
"We saw fields, with lanes between, the daisy, the thistle, and
the sweet-briar, settled villages, surrounded by strong abatis of
thorns, which stud the hills everywhere, clumps of trees, to
which the beehives are hung, and yellow crops of holcus, or
grain. The Harvest-Home-song sounded pleasant to my ears,
and, contrasting with the silent desert, the hum of man's
habitation was music. They flocked out to gaze upon us,
unarmed, and welcomed us. We bathed in the waters, on whose
banks were a multitude of huge Mantidæ, pink and tender
green. I now had ample time to see the manners and customs
of the settled Somali, as I was conducted to the cottage of the
Gerad's pretty wife, and learned the home, and the day, and the
food. They spoke Harari, Somali, Galla, Arabic, and dialects. My
kettle seems to have created surprise everywhere.
"Here the last preparations were made for entering this dreadful
City. All my people, and my camels, and most of my goods, had
to be left here for the return journey, and it was the duty of this
Chief (Gerad) to accompany me. I happened to hear one of
them say, 'Of what use is his gun? Before he could fetch fire I
should put this arrow through him.' I wheeled round, and
discharged a barrel over their heads, which threw them into
convulsions of terror. The man I had now to depend upon was
Adan bin Kaushan, a strong wiry Bedawin. He was tricky,
ambitious, greedy of gain, fickle, restless, and treacherous, a
cunning idiot, always so difficult to deal with. His sister was
married to the father of the Amir of Harar, but he said, 'He
would as soon walk into a crocodile's mouth as go into the walls
of Harar.' He received a sword, a Korán, a turban, an Arab
waistcoat of gaudy satin, about seventy tobes, and a similar
proportion of indigo-dyed stuff—he privily complained to me
that the Hammal had given him but twelve cloths. A list of his
wants will best explain the man. He begged me to bring him
from Berberah a silver-hilted sword and some soap, one
thousand dollars, two sets of silver bracelets, twenty guns with
powder and shot, snuff, a scarlet cloth coat embroidered with
gold, some poison that would not fail, and any other little article
of luxury which might be supposed to suit him. In return he was
to present me with horses, mules, slaves, ivory, and other
valuables: he forgot, however, to do so before he departed.
"Whilst we were discussing the project, and getting on
satisfactorily, five strangers well mounted rode in. Two were
citizens, and three were Habr Awal Bedawi, high in the Amir's
confidence; they had been sent to settle blood-money with
Adan. They then told him that I, the Arab, was not one who
bought and sold, but a spy; that I and my party should be sent
prisoners to Harar. Adan would not give us up, falsely promising
to present our salaams to the Amir. When they were gone he
told me how afraid he was, and that it was impossible for him to
conduct me to the City. I then relied upon what has made many
a small man Great, my good star and audacity.
"Driven to bay, I wrote an English letter from the Political Agent
at Aden, to the Amir of Harar, intending to deliver it in person; it
was 'neck or nothing.' I only took what was necessary, Sherwa
the son of Adan, the Bedawi Actidon and Mad Said, and left
everything behind me, excepting some presents for the Amir, a
change of clothes, an Arab book or two, a few biscuits,
ammunition, and a little tobacco. I passed through a lovely
country, was stopped by the Gallas, and by the Habr Awal
Bedawi, who offered, if we could wait till sunrise, to take us into
the City; so I returned a polite answer, leading them to expect
that I should wait till eight a.m. for them. I left my journals,
sketches, and books in charge of Adan.
He enters "The journey was hard, and I encountered a Harar
the City in Grandee, mounted upon a handsomely caparisoned
Triumph.
mule, and attended by servants. He was very
courteous, and, seeing me thirsty, ordered me a cup of water.
Finally arriving, at the crest of a hill, stood the City—the end of
my present travel—a long, sombre line, strikingly contrasting
with the white-washed towns of the East. The spectacle,
materially speaking, was a disappointment; nothing conspicuous
appeared but two grey minarets of rude shape; many would
have grudged exposing three lives to win so paltry a prize. But
of all that have attempted it, none ever succeeded in entering
that pile of stones; the thoroughbred traveller will understand
my exultation, although my two companions exchanged glances
of wonder. Stopping while my companions bathed, I retired to
the wayside and sketched the town. We arrived at three p.m.,
and advancing to the gate, Mad Said accosted a warder whom
he knew, sent our salaams to the Amir, saying we came from
Aden, and requested the honour of audience. The Habr Awal
collected round me inside the town, and scowling, inquired why
we had not apprised them of our intention of entering the City;
but it was 'war to the knife,' and I did not deign to answer.

Ten Days at Harar—the Most Exciting Trial of all.

"We were kept waiting half an hour, and were told by the
warder to pass the threshold. Long Guled gave his animal to the
two Bedawi, every one advising my attendants to escape with
the beasts, as we were going to be killed, on the road to this
African St. James. We were ordered to run, but we leisurely led
our mules in spite of the guide's wrath, entered the gate, and
strolled down the yard, which was full of Gallas with spears, and
the waiting gave me an opportunity to inspect the place. I
walked into a vast hall, a hundred feet long, between two long
rows of Galla spearmen, between whose lines I had to pass.
They were large half-naked savages, standing like statues, with
fierce movable eyes, each one holding, with its butt end on the
ground, a huge spear, with a head the size of a shovel. I
purposely sauntered down them coolly with a swagger, with my
eyes fixed upon their dangerous-looking faces. I had a six-
shooter concealed in my waist-belt, and determined, at the first
show of excitement, to run up to the Amir, and put it to his
head, if it were necessary, to save my own life.
Interview "The Amir was like a little Indian Rajah, an etiolated
with the youth about twenty-four or twenty-five years old,
Amir.
plain, thin bearded, with a yellow complexion,
wrinkled brows, and protruding eyes. His dress was a flowing
robe of crimson cloth, edged with snowy fur, and a narrow white
turban tightly twisted round a tall conical cap of red velvet, like
the old Turkish headgear of our painters. His throne was a
common Indian kursi, or raised cot, about five feet long, with
back and sides supported by a dwarf railing; being an invalid, he
rested his elbow upon a pillow, under which appeared the hilt of
a Cutch sabre. Ranged in double line, perpendicular to the Amir,
stood the 'Court,' his cousins and nearest relations, with right
arms bared after the fashion of Abyssinia.
"I entered this second avenue of Galla spearsmen with a loud
'Peace be upon ye!' to which H.H. replying graciously, and
extending a hand, bony and yellow as a kite's claw, snapped his
thumb and middle finger. Two chamberlains stepping forward,
held my forearms, and assisted me to bend low over the
fingers, which, however, I did not kiss, being naturally averse to
performing that operation upon any but a woman's hand. My
two servants then took their turn: in this case, after the back
was saluted, the palm was presented for a repetition.[1] These
preliminaries concluded, we were led to, and seated upon a mat
in front of the Amir, who directed towards us a frowning brow
and an inquisitive eye.
"I made some inquiries about the Amir's health: he shook his
head captiously, and inquired our errand. I drew from my
pocket my own letter: it was carried by a chamberlain, with
hands veiled in his tobe, to the Amir, who, after a brief glance,
laid it upon the couch, and demanded further explanation. I
then represented in Arabic that we had come from Aden,
bearing the compliments of our Daulah, or Governor, and that
we had entered Harar to see the light of H.H.'s countenance:
this information concluded with a little speech describing the
changes of Political Agents in Arabia, and alluding to the
friendship formerly existing between the English and the
deceased Chief Abubakr.
"The Amir smiled graciously.
"This smile, I must own, was a relief. We had been prepared for
the worst, and the aspect of affairs in the Palace was by no
means reassuring.
"Whispering to his Treasurer, a little ugly man with a baldly
shaven head, coarse features, pug nose, angry eyes, and
stubbly beard, the Amir made a sign for us to retire. The baisé
main was repeated, and we backed out of the audience-shed in
high favour. According to grandiloquent Bruce, 'the Court of
London and that of Abyssinia are, in their principles, one;' the
loiterers in the Harar palace-yard, who had before regarded us
with cut-throat looks, now smiled as though they loved us.
Marshalled by the guard, we issued from the precincts, and,
after walking a hundred yards, entered the Amir's second
palace, which we were told to consider our home. There we
found the Bedawi, who, scarcely believing that we had escaped
alive, grinned in the joy of their hearts, and we were at once
provided from the Chief's kitchen with a dish of shabta, holcus
cakes soaked in sour milk, and thickly powdered with red
pepper, the salt of this inland region.
"When we had eaten, the Treasurer reappeared, bearing the
Amir's command that we should call upon his Wazir, the Gerad
Mohammad. We found a venerable old man, whose benevolent
countenance belied the reports current about him in Somali-
land. Half rising, although his wrinkled brow showed suffering,
he seated me by his side upon the carpeted masonry-bench,
where lay the implements of his craft—reeds, inkstands, and
whitewashed boards for paper—politely welcomed me, and,
gravely stroking his cotton-coloured beard, desired to know my
object in good Arabic.
"I replied almost in the words used to the Amir, adding,
however, some details, how in the old day one Madar Faríh had
been charged by the late Sultan Abubakr with a present to the
Governor of Aden, and that it was the wish of our people to re-
establish friendly relations and commercial intercourse with
Harar.
"'Khayr Inshallah! it is well, if Allah please!' ejaculated the
Gerad. I then bent over his hand, and took leave.
"Returning, we inquired anxiously of the Treasurer about my
servants' arms, which had not been returned, and were assured
that they had been placed in the safest of storehouses, the
Palace. I then sent a common six-barrelled revolver as a present
to the Amir, explaining its use to the bearer, and we prepared to
make ourselves as comfortable as possible. The interior of our
new house was a clean room, with plain walls, and a floor of
tamped earth; opposite the entrance were two broad steps of
masonry, raised about two feet, and a yard above the ground,
and covered with hard matting. I contrived to make upon the
higher ledge a bed with the cushions which my companions
used as shabracques, and after seeing the mules fed and
tethered, lay down to rest, worn out by fatigue and profoundly
impressed with the poésie of our position. I was under the roof
of a bigoted prince whose least word was death; amongst a
people who detest foreigners; the only European that had ever
passed over their inhospitable threshold; and, more than that, I
was the fated instrument of their future downfall."

He gives a very detailed account of the City of Harar, its inhabitants,


and all he saw during his ten days there, for which I refer people to
"First Footsteps in East Africa," one large volume, 1856. He says—

"The explorer must frequently rest satisfied with descrying from


his Pisgah, the knowledge which another more fortunate is
destined to acquire. Inside Harar, I was so closely watched, that
it was impossible to put pen to paper. It was only when I got
back to Wilensi that I hastily collected the grammatical forms,
and a vocabulary which proves that the language is not Arabic;
that it has an affinity with the Amharic. Harar has its own
tongue, unintelligible to any save the citizens. Its little
population of eight thousand souls is a distinct race. A common
proverb is, 'Hard as the heart of Harar.' They are extremely
bigoted, especially against Christians, and are fond of a religious
war, or jehád, with the Gallas. They hold foreigners in hate and
contempt, and divide them into two classes, Arabs and Somal.
"The Somals say that the State dungeon is beneath the palace,
and that he who once enters it lives with unkempt beard and
untrimmed nails till the day when death sets him free. There is
nothing more terrible; the captive is heavily ironed, lies in a
filthy dungeon, and receives no food, except what he can obtain
from his own family, or buy or beg from his guards. The Amir
has bad health; I considered him consumptive. It is something
in my favour that, as soon as I departed, he wrote to the acting
Political Resident at Aden, earnestly begging to be supplied with
a Frank physician, and offering protection to any European who
might be persuaded to visit his dominions. His rule was severe,
if not just, and it has all the prestige of secrecy. Even the Gerad
Mohammad, even the Queen Dowager, are threatened with
fetters if they offer uncalled-for advice. His principal occupation
is spying his many stalwart cousins, indulging in vain fears of
the English and the Turks, amassing treasure by commerce and
cheating.
"The Amir Ahmed is alive to the fact that some State should
hedge in a Prince. Neither weapons nor rosaries are allowed in
his presence; a chamberlain's robe acts as spittoon; whenever
anything is given to or taken from him his hand must be kissed;
even on horseback two attendants fan him with the hems of
their garments. Except when engaged on the Haronic visits,
which he, like his father, pays to the streets and byways at
night, he is always surrounded by a strong body-guard. He rides
to Mosque escorted by a dozen horsemen, and a score of
footmen with guns and whips precede him; by his side walks an
officer, shading him with a huge and heavily fringed red-satin
umbrella—from India to Abyssinia the sign of princely dignity.
Even at his prayers, two or three chosen matchlockmen stand
over him with lighted fusees. When he rides forth in public, he is
escorted by a party of fifty men; the running footmen crack
their whips and shout, 'Let! Let!' (Go! go!), and the citizens
avoid stripes by retreating into the nearest house, or running
into another street.
Has Great "Immediately on our arrival we were called upon by
Success. all sorts of Arabs; they were very civil to me at first,
but when the Amir ceased to send for me, just as at
civilized Courts, they prudently cut me. The moment the Amir
sent for me, my Habr Awal enemies, seeing the tide of fortune
setting in my favour, changed their tactics, and proposed
themselves as my escort to return to Berberah, which I politely
refused. They did me all the harm they could, but my good star
triumphed. After one day's rest, I was summoned to wait upon
the Gerad Mohammad, who was Prime Minister. Sword in hand,
and, followed by my two attendants, I walked to the Palace, and
found him surrounded by six counsellors; they were eating jat,
which has somewhat the effect of hashish.
"He sat me by his right hand on the dais, where I ate jat, being,
fortunately, used to these things, and fingered the rosary. Then
followed prayer, and then a theological discussion, in which,
fortunately, I was able to distinguish myself. My theology won
general approbation and kind glances from the elders. In a very
short time I was sent for by the Amir, and this time was allowed
to approach the outer door with covered feet. I entered as
ceremoniously as before, and the prince motioned me to sit
near the Gerad, on a Persian rug to the right of the throne; my
attendants on humble mats at a greater distance. After sundry
inquiries of what was going on at Aden, the Resident's letter
was suddenly produced by the Amir, who bade me explain its
contents, and wished to know if it was my intention to buy and
sell at Harar. I replied, 'We are neither buyers nor sellers; we
have become your guests to pay our respects to the Amir, who
may Allah preserve, and that the friendship between the two
Powers may endure.' The Amir was pleased, and I therefore
ventured to hope that the Prince would soon permit me to
return, as the air of Harar was too dry for me, and that we were
in danger of small-pox, then raging in the town, and through
the Gerad, the Amir said, 'The reply will be vouchsafed,' and the
interview was over.
"I sent my salaam to one of the Ulema, Shaykh Jámi; he
accepted the excuse of health and came to see me. He was
remarkably well read in the religious sciences, and a great man
at Mecca, with much influence with the Sultan, and employed
on political Missions amongst the Chiefs. He started with the
intention of winning the Crown of Glory by murdering the British
Resident at Aden, but he was so struck with the order of justice
of our rule, he offered El Islam to that officer, who received it so
urbanely, that the simple Eastern, instead of cutting the Kaffir's
throat, began to pray fervently for his conversion. We were
kindly looked upon by a sick and decrepid eunuch, named
Sultán. I used to spend my evenings preaching to the Gallas.
Damaging "The Gerad Mohammad was now worked upon by
Reports. the Habr Awal, my enemies, to make inquiries about
me, and one of the Ayyal Gedíd clan came up and
reported that three brothers[2] had landed in the Somal country,
that two of them were anxiously waiting at Berberah the return
of the fourth from Harar, and that, though dressed like Moslems,
they were really English spies in Government employ, and
orders were issued for cutting off Caravans. We, however, were
summoned to the Gerad's, where, fortunately for me, I found
him suffering badly from bronchitis. I saw my chance. I related
to him all its symptoms, and told him that if I could only get
down to Aden, I could send him all the right remedies, with
directions. He clung to the hope of escaping his sufferings, and
begged me to lose no time. Presently the Amir sent for him, and
in a few minutes I was sent for alone. A long conversation
ensued about the state of Aden, of Zayla, of Berberah, and of
Stamboul. The Chief put a variety of questions about Arabia,
and every object there; the answer was that the necessity of
commerce, confined us to the gloomy rock Aden. He used some
obliging expressions about desiring our friendship, and having
considerable respect for a people who built, he understood,
large ships. I took the opportunity of praising Harar in cautious
phrase, and especially of regretting that its coffee was not
better known amongst the Franks. The small wizen-faced man
smiled, as Moslems say, the smile of Umar;[3] seeing his brow
relax for the first time, I told him that, being now restored to
health, we requested his commands for Aden. He signified
consent with a nod, and the Gerad, with many compliments,
gave me a letter addressed to the Political Resident, and
requested me to take charge of a mule as a present. I then
arose, recited a short prayer, the gist of which was that the
Amir's days and reign might be long in the land, and that the
faces of his foes might be blackened here and hereafter, bent
over his hand, and retired. Returning to the Gerad's levée-hut, I
saw by the countenances of my two attendants that they were
not a little anxious about the interview, and comforted them
with the whispered word, 'Achha!' (all right!)
"Presently appeared the Gerad, accompanied by two men, who
brought my servants' arms, and the revolver which I had sent to
the prince. This was a contretemps. It was clearly impossible to
take back the present; besides which, I suspected some finesse
to discover my feelings towards him. The other course would
ensure delay. I told the Gerad that the weapon was intended
especially to preserve the Amir's life, and, for further effect,
snapped caps in rapid succession, to the infinite terror of the
august company. The Minister returned to his Master, and soon
brought back the information that, after a day or two, another
mule should be given to me. With suitable acknowledgments we
arose, blessed the Gerad, bade adieu to the assembly, and
departed joyful; the Hammal, in his glee, speaking broken
English, even in the Amir's courtyard.
"Shaykh Jámi was rendered joyful by the news he told me when
I arrived; he had been informed that in the Town was a man
who had brought down the birds from heaven, and the citizens
had been thrown into a great excitement by my probable
intentions. One of the principal Ulema, and a distinguished Haji,
had been dreaming dreams in my favour, and sent their
salaams. My long residence in the East had made me grateful to
the learned, whose influence over the people, when unbiased by
bigotry, is for the good. On January 11th, I was sent for by the
Gerad, and given the second mule; he begged me not to forget
his remedies as soon as I reached Aden, and I told him that I
would start on the morrow. I scarcely had got in, when there
were heavy showers and thunder. When I got up to mount early
on Friday morning, of course a mule had strayed; then Shaykh
Jámi would not go till Monday. Now, as I had been absent from
my goods and chattels a whole fortnight, as the people at Harar
are immensely fickle, as you never know the moment that the
Amir may change his mind, for all African Cities are prisons on a
large scale—you enter by your own will, but you leave by
another's—I longed to start; however, the storms warned me to
be patient, and I deterred my departure till next morning.
He leaves "Long before dawn on Saturday, January 13th, the
Harar safely.mules were saddled, bridled, and charged with our
scanty luggage. After a hasty breakfast we shook
hands with old Sultán, the eunuch, mounted and pricked
through the desert streets. Suddenly my weakness and sickness
left me—so potent a drug is joy—and, as we passed the Gates,
loudly salaaming to the warders, who were crouching over the
fire inside, a weight of care and anxiety fell from me like a cloak
of lead.
"Yet I had time, on the top of my mule, for musing upon how
melancholy a thing is Success. Whilst failure inspirits a man,
attainment reads the sad prosy lesson that all our glories
'Are shadows, not substantial things.'
Truly said the sayer, 'Disappointment is the salt of life'—a
salutary bitter which strengthens the mind for fresh exertion,
and gives a double value to the prize.
"This shade of melancholy soon passed away. We made in a
direct line for Kondura. At one p.m. we safely threaded the
Gallas' pass, and about an hour afterwards we exclaimed,
'Alhamdulillah,' at the sight of Sagharrah and the distant Marar
Prairie. Entering the village, we discharged our firearms. The
men gave cordial poignées de mains—some danced with joy to
see us return alive; they had heard of our being imprisoned,
bastinadoed, slaughtered; they swore that the Gerad was
raising an army to rescue or revenge us—in fact, had we been
their kinsmen, more excitement could not have been displayed.
Lastly, in true humility, crept forward the "End of Time," who, as
he kissed my hand, was upon the point of tears.
"A pleasant evening was spent in recounting our perils, as
travellers will do, and complimenting one another upon the
power of our star.
"At eight next morning we rode to Wilensi, and as we
approached, all the villagers and wayfarers inquired if we were
the party that had been put to death by the Amir of Harar.
"Loud congratulations and shouts of joy awaited our arrival. The
Kalendar was in a paroxysm of delight; both Shehrazade and
Deenarzade were affected with giggling and what might be
blushing. We reviewed our property and found that the One-
eyed had been a faithful steward, so faithful indeed that he had
wellnigh starved the two women. Presently appeared the Gerad
and his sons, bringing with them my books; the former was at
once invested with a gaudy Abyssinian tobe of many colours, in
which he sallied forth from the cottage the admired of all
admirers. The pretty wife, Sudíyah, and the good Khayrah were
made happy by sundry gifts of huge Birmingham ear-rings,
brooches and bracelets, scissors, needles, and thread. The
evening as usual ended in a feast.
"We were obliged to halt a week at Wilensi to feed, for both
man and beast to lay in a stock of strength for the long desert
march before us, to buy onions, tobacco, spices, wooden
platters, and a sort of bread called karanji. Here I made my
grammar and vocabulary of the Harari tongue, under the
supervision of Mad Said and Ali the poet, a Somali educated at
Harar, who knew Arabic, Somali, Galla, and Harar languages.
"On January 21st I wanted to start, but Shaykh Jámi appeared
with all the incurables of the country. Nobody can form an idea
of the difficulties that an Eastern will put in your way when you
want to start, and unfortunately in nine cases out of ten the
ruses they have resort to, do prevent your starting. Now, in this
case, I decided that talismans were the best and safest
medicines in these mountains. The Shaykh doubted them, but
when I exhibited my diploma as a Master-Sufi, a new light broke
in upon him and his attendants. 'Verily he hath declared himself
this day!' whispered each to his neighbour, sorely mystified.
Shaykh Jámi carefully inspected the document, raised it
reverently to his forehead, muttered prayers, and owned himself
my pupil.
A Fearful "Now, however, all my followers had got some
Desert reason why they could not go, so I sauntered out
Journey.
alone, attended only by the Hammal, and, in spite of
the Chief summoning me to halt, I took an abrupt leave and
went off, and entered the Marar Prairie with pleasure. The
truants joined us later on, and we met a party whose Chief, a
Somali, expressed astonishment at our escaping from Harar, told
us that the Berberi were incensed with us for leaving the direct
road, advised us to push on that night, to 'ware the bush,
whence the Midjans would use their poisoned arrows. The
Berberi had offered a hundred cows for our person dead or
alive. Then my party sat down to debate; they palavered for
three hours. They said that the camels could not walk, that the
cold of the prairies was death to man, till darkness came on.
Experience had taught me that it was waste of time to debate
overnight about dangers to be faced next day, so I ate my
dates, drank my milk, and lay down to enjoy sweet sleep in the
tranquil silence of the desert. Although I did not know it till after
my return from Berberah, Gerad Adan was my greatest danger.
If his plotting had succeeded it would have cost him dear, but
would also have proved fatal to me. The 23rd of January passed
in the same manner, and the explanation I had with my men
was, that on the morrow at dawn I would cross the Marar
Prairie by myself; and we started at dawn on the 24th, giving a
wide berth to the Berberis, whose camp-fires were quite visible
at a distance. As we were about to enter the lands of the Habr
Awal, our enemies, a week would elapse before we could get
protection. We had resolved to reach the coast within the
fortnight, instead of which a month's march was in prospect.
Suddenly Beuh appeared, and I proposed to him that he should
escort the Caravans to Zayla, and that I and the two others who
had accompanied me to Harar would mount our mules, only
carrying arms and provisions for four days. I pushed through
the land of our enemies the Habr Awal. In the land we were to
traverse every man's spear would be against us, so I chose the
desert roads, and carefully avoided all the kraals. It was with
serious apprehension that I pocketed all my remaining
provisions—five biscuits, a few limes, a few lumps of sugar. Any
accident to our mules, any delay would starve us; we were
traversing a desert where no one would sell us meat or milk,
and only one water-bottle in the whole party.
Want of "We rode thirty-five miles over awful tracks. Our toil
Water. was rendered doubly dreadful by the Eastern
traveller's dread—the demon of Thirst rode like Care
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about testbank and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebooksecure.com

You might also like