100% found this document useful (56 votes)
193 views

EBOOK Java Programming A Comprehensive Introduction First Edition Download Full Chapter PDF Kindle

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

EBOOK Java Programming A Comprehensive Introduction First Edition Download Full Chapter PDF Kindle

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

Java Programming: A Comprehensive

Introduction, First edition


Visit to download the full and correct content document:
https://ebookmass.com/product/java-programming-a-comprehensive-introduction-first
-edition/
Herbert Schildt | Dale Skrien

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

Java Programming
programming course using Java. This text takes a logical approach to the presentation
of core topics, moving step by step from the basics to more advanced material, with
objects being introduced at the appropriate time. The book is divided into three parts:
Part One covers the elements of the Java language and the fundamentals of programming.

Programming
An introduction to object-oriented design is also included.
Part Two introduces GUI (Graphical User Interface) programming using Swing.
Part Three explores key aspects of Java’s API (Application Programming Interface) library,
including the Collections Framework and the concurrency API.

Hallmark Features
Presents topics in a clear and logical order. This “straight ahead” approach introduces
A Comprehensive Introduction
each new feature in a cohesive, logical sequence.
Introduces objects after the basics. Objects are introduced in Chapter 4, after key elements
of the language are covered.
Separates the teaching of the GUI from the teaching of the language elements. The
instructor has flexibility in choosing when to introduce GUI programming.

Introduction
A Comprehensive
Includes coverage of Java 7 (JDK 7). Students can learn a modern version of the language.
Provides numerous examples and exercises. Examples given throughout make the

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


purpose and use of program elements clear, while the exercises test the student’s grasp of
material. Answers to selected exercises are given in the back of the book.

Pedagogical Highlights
Progress Checks reinforce core concepts and provide immediate feedback to the student
that key concepts have been learned.
Ask the Expert sections supply additional information or interesting commentary related
to the topic at hand.
Try This elements provide step-by-step examples that show core programming topics in action.

Learn more about Java Programming at the book’s web site: www.mhhe.com/schildt1e

Schildt
Skrien

TM

College Programming Series


CONTENTS

PREFACE xxv

PART I The Java Language 1

CHAPTER 1 Java Programming Fundamentals 3


Computing Basics 4
The Hardware Components of a Computer 4
Bits, Bytes, and Binary 5
The Operating System 6
The Program 7
Programming Languages 8
The Java Language 9
The Origins of Java 9
Java’s Contribution to the Internet 11
Java Applets 11
Security 11
Portability 12
Java’s Solution: The Bytecode 12
The Evolution of Java 13
The Key Attributes of Object-Oriented
Programming 14
Encapsulation 15
Polymorphism 16
Inheritance 16
The Java Development Kit 17
A First Simple Program 18
Entering the Program 18
Compiling the Program 19
Running the Program 19
The First Sample Program Line by Line 19
Handling Syntax Errors 22
A Second Simple Program 23
Another Data Type 25

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


viii content s

Two Control Statements 28


The if Statement 28
The for Loop 30
Create Blocks of Code 32
Semicolons and Positioning 33
Indentation Practices 34
Indentation Practices 34
The Java Keywords 36
Identifiers in Java 37
The Java Class Libraries 38
Exercis es 39

CHAPTER 2 Introducing Data Types and Operators 43


Why Data Types are Important 43
Java’s Primitive Types 44
Integers 44
Floating-Point Types 46
Characters 47
The Boolean Type 48
Literal s 50
Hexadecimal, Octal, and Binary Literals 51
Character Escape Sequences 52
String Literals 52
A Closer Look at Variables 53
Initializing a Variable 54
Dynamic Initialization 54
The Scope and Lifetime of Variables 55
Operators 58
Arithmetic Operators 58
Increment and Decrement 59
Relational and Logical Operators 60
Short-Circuit Logical Operators 62
The Ass ignment Operator 64
Shorthand Assignments 64
Type Conversion in Assignments 65
Using a Cast 66
Operator Precedence 68
Expressions 70
Type Conversion in Expressions 70
Spacing and Parentheses 72
Exercis es 73

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


Contents ix

CHAPTER 3 Program Control Statements 77


Input Characters from the Keyboard 78
The if Statement 79
Nested ifs 81
The if-else-if Ladder 82
The switch Statement 83
Nested switch Statements 86
The for Loop 90
Some Variations on the for Loop 91
Missing Pieces 92
The Infinite Loop 93
Loops with No Body 93
Declaring Loop Control Variables
 Inside the for Statement 94
The Enhanced for Loop 95
The while Loop 95
The do-while Loop 97
Use break to Exit a Loop 102
Use break as a Form of goto 104
Use continue 108
Nested Loops 113
Exercises 114

CHAPTER 4 Introducing Classes, Objects, and Methods 119


Class Fundamentals 119
The General Form of a Class 120
Defining a Class 121
How Objects are Created 124
Reference Variables and Assignment 124
Methods 126
Adding a Method to the Vehicle Class 126
Returning from a Method 128
Returning a Value 129
Using Parameters 131
Adding a Parameterized Method to Vehicle 133
Constructors 141
Parameterized Constructors 142
Adding a Constructor to the Vehicle Class 143
The new Operator Revisited 145

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


x content s

Garbage Collection and Finalizers 145


The finalize( ) Method 146
The this Keyword 149
Exercis es 151

CHAPTER 5 More Data Types and Operators 155


Arrays 155
One-Dimensional Arrays 156
Multidimensional Arrays 161
Two-Dimensional Arrays 161
Irregular Arrays 163
Arrays of Three or More Dimensions 164
Initializing Multidimensional Arrays 164
Alternative Array Declaration Syntax 166
Assigning Array References 166
Using the length Member 168
The For-Each Style for Loop 176
Iterating Over Multidimensional Arrays 179
Applying the Enhanced for 180
Strings 181
Constructing Strings 182
Operating on Strings 182
Arrays of Strings 184
Strings are Immutable 185
Using a String to Control a switch Statement 186
Using Command-Line Arguments 187
The Bitwise Operators 189
The Bitwise AND, OR, XOR, and NOT Operators 189
The Shift Operators 194
Bitwise Shorthand Assignments 196
The ? Operator 200
Exercis es 201

CHAPTER 6 A Closer Look at Methods and Classes 205


Controlling Access to Class Members 205
Java’s Access Modifiers 206
Pass Objects to Methods 211
How Arguments are Passed 212
Returning Objects 215
Method Overloading 217

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


Contents xi

Overloading Constructors 222


Recursion 228
Understanding static 232
Static Variables 233
Static Methods 235
Static Blocks 236
Introducing Nested and Inner Classes 240
Varargs: Variable-Length Arguments 244
Varargs Basics 245
Overloading Varargs Methods 247
Varargs and Ambiguity 249
Exercises 250

CHAPTER 7 Inheritance 257


Inheritance Basics 257
Member Access and Inheritance 260
Constructors and Inheritance 263
Using super to Call Superclass
 Constructors 265
Using super to Access Superclass Members 269
Creating a Multilevel Hierarchy 273
When are Constructors Executed? 276
Superclass References
 and Subclass Objects 277
Method Overriding 282
Overridden Methods Support
 Polymorphism 285
Why Overridden Methods? 287
Applying Method Overriding to TwoDShape 287
Using Abstract Classes 291
Using final 296
final Prevents Overriding 296
final Prevents Inheritance 296
Using final with Data Members 297
The Object Class 298
Exercises 299

CHAPTER 8 Interfaces 303


Interface Fundamentals 303
Creating an Interface 304

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


xii content s

Implementing an Interface 305


Using Interface References 309
Implementing Multiple Interfaces 311
Constants in Interfaces 319
Interfaces can be Extended 321
Nested Interfaces 322
Final Thoughts on Interfaces 323
Exercis es 323

CHAPTER 9 Packages 327


Package Fundamentals 327
Defining a Package 328
Finding Packages and CLASSPATH 329
A Short Package Example 329
Packages and Member Access 331
A Package Access Example 332
Understanding Protected Members 334
Importing Packages 336
Importing Java’s Standard Packages 337
Static Import 341
Exercis es 344

CHAPTER 10 Exception Handling 347


The Exception Hierarchy 348
Exception Handling Fundamentals 348
Using try and catch 349
A Simple Exception Example 349
The Consequences of an Uncaught
 Exception 352
Exceptions Enable You to Handle
 Errors Gracefully 353
Using Multiple catch Clauses 355
Catching Subclass Exceptions 356
try Blocks can be Nested 357
Throwing an Exception 359
Rethrowing an Exception 360

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


Contents xiii

A Closer Look at throwable 361


Using finally 363
Using throws 365
Java’s Built-in Exceptions 366
New Exception Features Added by JDK 7 369
Creating Exception Subclasses 370
Exercises 377

CHAPTER 11 Using I/O 383


Java’s I/O Is Built on Streams 384
Byte Streams and Character Streams 384
The Byte Stream Classes 384
The Character Stream Classes 385
The Predefined Streams 386
Using the Byte Streams 387
Reading Console Input 388
Writing Console Output 389
Reading and Writing Files Using
 Byte Streams 390
Inputting from a File 391
Writing to a File 394
Automatically Closing a File 396
Reading and Writing Binary Data 399
Random-Access Files 404
Using Java’s Character-Based Streams 407
Console Input Using Character Streams 407
Console Output Using Character Streams 411
File I/O Using Character Streams 412
Using a FileWriter 412
Using a FileReader 413
File 415
Obtaining a File’s Properties 415
Obtaining a Directory Listing 417
Using FilenameFilter 418
The listFiles( ) Alternative 419
Various File Utility Methods 419
Using Java’s Type Wrappers to
 Convert Numeric Strings 421
Exercises 430

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


xiv content s

CHAPTER 12 Multithreaded Programming 435


Multithreading Fundamentals 435
The Thread Class and Runnable Interface 436
Creating a Thread 437
Some Simple Improvements 440
Creating Multiple Threads 445
Determining When a Thread Ends 447
Thread Priorities 450
Synchronization 451
Using Synchronized Methods 452
The Synchronized Statement 455
Thread Communication Using notify( ),
 wait( ), and notifyAll( ) 458
An Example That Uses wait( ) and notify( ) 458
Suspending, Resuming, and
 Stopping Threads 464
Exercis es 469

CHAPTER 13 Enumerations, Autoboxing, and Annotations 475


Enumerations 475
Enumeration Fundamentals 476
Java Enumerations are Class Types 479
The values( ) and valueOf( ) Methods 479
Constructors, Methods, Instance Variables,
  and Enumerations 480
Two Important Restrictions 482
Enumerations Inherit Enum 482
Autoboxing 490
Type Wrappers and Boxing 490
Autoboxing Fundamentals 492
Autoboxing and Methods 493
Autoboxing/Unboxing Occurs in Expressions 494
A Word of Warning 496
Annotations (Metadata) 497
Creating and Using an Annotation 497
Built-in Annotations 498
Exercis es 500

CHAPTER 14 Generics 505


Generics Fundamentals 506
A Simple Generics Example 506

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


Contents xv

Generics Work Only with Objects 510


Generic Types Differ Based on Their Type Arguments 510
A Generic Class with Two Type Parameters 510
The General Form of a Generic Class 512
Bounded Types 513
Using Wildcard Arguments 516
Bounded Wildcards 519
Generic Methods 522
Generic Constructors 524
Generic Class Hierarchies 525
Generic Interfaces 528
Raw Types and Legacy Code 535
Type Inference with the Diamond Operator 538
Erasure 540
Ambiguity Errors 540
Some Generic Restrictions 541
Type Parameters Can’t be Instantiated 541
Restrictions on Static Members 542
Generic Array Restrictions 542
Generic Exception Restriction 543
Exercises 543

CHAPTER 15 Applets and the Remaining Java Keywords 549


Applet Basics 549
A Complete Applet Skeleton 553
Applet Initialization and Termination 554
A Key Aspect of an Applet’s Architecture 554
Requesting Repainting 555
Using the Status Window 560
Passing Parameters to Applets 561
The Remaining Java Keywords 563
The volatile Modifier 564
The transient Modifier 564
instanceof 564
strictfp 564
assert 565
Native Methods 565
Exercises 567

CHAPTER 16 Introduction to Object-Oriented Design 569


Elegant Software and Why It Matters 570
Properties of Elegant Software 571

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


xvi content s

Elegant Methods 573


Naming Conventions 573
Method Cohesion 574
Well-formed Objects 576
Internal Documentation 577
External Documentation 578
Elegant Classes 581
Class Cohesion and the Expert Pattern 581
Avoiding Duplication 583
Complete Interface 585
Design with Change in Mind 586
Demeter’s Law 589
Inheritance versus Delegation 591
UML Class Diagrams 591
Code Reuse Perspective 594
The Is-a Relationship 594
Similar Behavior 597
Polymorphism 600
Costs of Inheritance 600
Design Patterns 603
Adapter Pattern 604
Observer Pattern 607
Exercis es 612

PART II Introducing Gui Programming


With Swing 617
CHAPTER 17 Swing Fundamentals 619
The Origins and Design Philosophy
 of Swing 620
Components and Containers 622
Components 622
Containers 623
The Top-Level Container Panes 623
Layout Managers 624
A First Simple Swing Program 625
The First Swing Example Line by Line 626
Event Handling 631
Events 631
Event Sources 631
Event Listeners 632
Event Classes and Listener Interfaces 632
Adapter Classes 632

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


Contents xvii

Using a Push Button 635


Introducing JTextField 643
Use Anonymous Inner Classes
 to Handle Events 655
Exercises 656

CHAPTER 18 Exploring Swing Controls 659


Jlabel and ImageIcon 660
The Swing Buttons 663
Handling Action Events 664
Handling Item Events 664
JButton 665
JToggleButton 668
Check Boxes 670
Radio Buttons 672
JTextField 675
JScrollPane 685
JList 692
JComboBox 696
Trees 699
JTable 703
A Brief Word about Models 706
Exercises 707

CHAPTER 19 Working with Menus 711


Menu Basics 711
An Overview of JMenuBar, JMenu,
 and JMenuItem 713
JmenuBar 713
JMenu 714
JMenuItem 715
Create a Main Menu 715
Add Mnemonics and Accelerators
 to Menu Items 720
Add Images and Tooltips to Menu Items 723
 Use JRadioButto nMenuItem
 and JCheckBoxMenuItem 730
Exercises 733

CHAPTER 20 Dialogs 737


JOptionPane 738
showMessageDialog( ) 740

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


xviii content s

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

CHAPTER 21 Threading, Applets, and Painting 779


Multithreading in Swing 779
Use Timer 786
Create Swing Applets 792
A Simple Swing Applet 793
Painting 800
Painting Fundamentals 800
The Graphics Context 801
Compute the Paintable Area 802
Request Painting 802
A Paint Example 802
Exercis es 808

PART III Exploring The Java Api Library 811


CHAPTER 22 String Handling 813
String Fundamentals 813
The String Constructors 814
Three String-Related Language Features 816
String Literals 817
String Concatenation 817
String Concatenation with Other Data Types 817
Overriding toString( ) 818
The length() Method 823
Obtaining the Characters within a String 824
charAt( ) 824
getChars( ) 824
toCharArray( ) 825
String Comparison 826
equals( ) and equalsIgnoreCase( ) 826
equals( ) Versus == 827
regionMatches( ) 828
startsWith( ) and endsWith( ) 828
compareTo( ) and compareToIgnoreCase( ) 829

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


Contents xix

Using indexOf( ) and lastIndexOf( ) 831


Obtaining a Modified String 833
substring( ) 833
replace( ) 834
trim( ) 835
Changing the Case of Characters
  Within a String 836
StringBuffer and StringBuilder 839
Exercises 839

CHAPTER 23 Exploring java.lang 843


Primitive Type Wrappers 844
Number 844
Double and Float 845
Byte, Short, Integer, and Long 846
Character 849
Boolean 852
Autoboxing and the Type Wrappers 852
The Math Class 853
The Process Class 857
The ProcessBuilder Class 857
The Runtime Class 859
The System Class 861
Using currentTimeMillis( ) to Time Program Execution 862
Using arraycopy( ) 863
Obtaining Property Values 864
Redirecting Standard I/O Streams 864
The Object Class 866
The Class Class 866
The Enum Class 868
Thread-Related Classes and
 The Runnable Interface 868
Other Classes 869
The java.lang Interfaces 869
The Comparable Interface 870
The Appendable Interface 872
The Iterable Interface 873
The Readable Interface 873
The CharSequence Interface 873
The AutoCloseable Interface 874
Exercises 875

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


xx content s

CHAPTER 24 Exploring java.util 879


The Locale Class 881
Working with Date and Time 884
Date 884
Calendar and GregorianCalendar 885
Formatting Output with Formatter 890
The Formatter Constructors 890
Formatting Basics 891
Formatting Strings and Characters 894
Formatting Numbers 894
Formatting Date and Time 895
The %n and %% Specifiers 897
Specifying a Minimum Field Width 897
Specifying Precision 898
Using the Format Flags 899
The Uppercase Option 902
Using an Argument Index 902
Formatting for a Different Locale 903
Closing a Formatter 904
Formatting and the printf( ) Method 907
The Scanner Class 909
The Scanner Constructors 909
Scanning Basics 909
Some Scanner Examples 911
Some Other Scanner Features 916
The Random Class 917
Use Observable and Observer 918
The Timer and TimerTask Classes 922
Miscellaneous Utility Classes
 and Interfaces 924
Exercis es 925

CHAPTER 25 Using the Data Structures in the Collections


Framework 929
An Overview of Data Structures 930
Stacks and Queues 930
Linked Lists 931
Trees 932
Hash Tables 933
Choosing a Data Structure 933

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


Contents xxi

Collections Overview 934


The Collection Interfaces 935
The Collection Interface 936
The List Interface 938
The Set Interface 938
The SortedSet Interface 938
The NavigableSet Interface 940
The Queue Interface 940
The Deque Interface 942
The Collection Classes 944
The ArrayList Class 945
The LinkedList Class 948
The HashSet Class 952
The TreeSet Class 954
The LinkedHashSet Class 956
The ArrayDeque Class 957
The PriorityQueue Class 959
Accessing a Collection via an Iterator 960
Using an Iterator 960
The For-Each Alternative to Iterators 964
Working with Maps 964
The Map Interfaces 964
The Map Classes 969
Comparators 974
The Collection Algorithms 976
The Arrays Class 980
The Legacy Classes and Interfaces 981
The Enumeration Interface 981
Vector 981
Stack 981
Dictionary 981
Hashtable 981
Properties 982
Exercises 982

CHAPTER 26 Networking with java.net 985


Networking Fundamentals 985
The Networking Classes and Interfaces 986
The InetAddress Class 987
The Socket Class 989
The URL Class 993
The URLConnec tion Class 995

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


xxii content s

The H ttpURLConnection Class 1000


Datagrams 1002
DatagramSocket 1003
DatagramPacket 1003
A Datagram Example 1004
Exercis es 1007

CHAPTER 27 The Concurrency Utilities 1009


The Concurrent API Packages 1010
java.util.concurrent 1010
java.util.concurrent.atomic 1011
java.util.concurrent.locks 1011
Using Synchronization Objects 1012
Semaphore 1012
CountDownLatch 1015
CyclicBarrier 1018
Exchanger 1020
Phaser 1023
Using an Executor 1030
A Simple Executor Example 1031
Using Callable and Future 1033
The TimeUnit Enumeration 1036
The Concurrent Collections 1038
Locks 1038
Atomic Operations 1041
Parallel Programming via the Fork/
 Join Framework 1042
The Main Fork/Join Classes 1043
ForkJoinTask<V> 1043
RecursiveAction 1044
RecursiveTask<V> 1044
ForkJoinPool 1045
The Divide-and-Conquer Strategy 1046
A Simple First Fork/Join Example 1047
Understanding the Impact of the Level of Parallelism 1049
An Example That Uses RecursiveTask<V> 1052
Executing a Task Asynchronously 1054

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


Contents xxiii

The Concurrency Utilities versus


 Java’s Traditional Approach 1055
Exercises 1056

Appendix A Using Java’s Documentation Comments 1059


The javadoc Tags 1059
The General Form of a Documentation
         
C omment 1063
What javadoc Outputs 1064
An Example That Uses Documentation
         
C omments 1064
Appendix B An Introduction to Regular Expressions 1067
The Pattern Class 1067
The Matcher Class 1068
Regular Expression Syntax Basics 1068
Demonstrating Pattern Matching 1069
Using the Wildcard Character
         
a nd Quantifiers 1071
Working with Classes of Characters 1073
Using replaceAll( ) 1073
The String Class Connection 1074
Things to Explore 1074
Appendix C Answers to Selected Exercises 1075

Index 1129

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


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

T
his book teaches the fundamentals of programming by way of the Java language.
It assumes no prior programming experience and begins with the basics, such as
how to compile and run a Java program. Next, it discusses the keywords, opera-
tors, and constructs that form the Java language. The book also covers several parts
of the Java Application Programming Interface (API) library, including Swing, which
is the framework used to create programs that have a graphical user interface (GUI),
and the Collections Framework, which is used to store collections of objects. In short,
this book is intended as a comprehensive introduction to Java. Like most computer
languages, Java has evolved over time. At the time of this writing, the latest version is
Java 7 (JDK 7), and this is the version of Java covered by this book. However, most of
the material is also applicable to other recent versions of Java, such as version 6.

A STRAIGHT AHEAD APPROACH


This book uses what we characterize as a “straight ahead” approach. By this, we mean
that topics are introduced in a cohesive sequence that is intended to keep the focus
of each discussion on the topic at hand. This approach simplifies and streamlines the
presentation. On occasions when a departure from the main presentation flow is nec-
essary, we attempt to do so in a way that minimizes the disruption. The goal of our
approach is to present the Java language in a way that clearly shows the interrelation-
ship of its parts, rather than as a jumble of disconnected features.
To help manage the material, this book is organized into three parts. Part One
describes the elements that define the Java language and the core elements of pro-
gramming. It begins with an overview of Java followed by the basic concepts of data
types, operators, and control statements. It then progressively introduces the more
sophisticated features of the language, such as classes, methods, inheritance, inter-
faces, packages, exceptions, multithreading, and generics. Part One also describes
I/O, because it is integral to many Java programs, and applet fundamentals, because
the applet is a quintessential Java application. Part One ends with a chapter on object-
oriented design.
As it relates directly to Part One, our “straight ahead” approach keeps the focus
on the elements of the Java language and the fundamentals of programming, with
each new section building on the foundation of what comes before. Where possible,
we avoid digressions that distract from the main topic. For example, discussions of
GUI programming via Swing are handled in Part Two, rather than being intermixed
with discussions of basic concepts. This way, the presentation in Part One remains
firmly rooted in the core issues of Java and of programming.

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


xxvi preface

Part Two introduces Swing. It begins with an overview of GUI programming with
Swing, including the basic concepts of components, events, and layout manag-
ers. Subsequent chapters advance in an orderly fashion, presenting an overview of
several Swing components, followed by menus, dialogs, painting, and so on. This
“straight ahead” approach is intended to help students more easily integrate each
new feature into the overall picture they are forming of the Swing framework.
Part Three explores portions of the Java API library. Because the API library
is very large, it is not possible to discuss it in its entirety in this book. Instead, we
focus on what we consider to be those parts of the library with which every Java pro-
grammer should be familiar. In addition to covering large portions of java.lang and
java.util (with special emphasis on the Collections Framework), we also present an
overview of networking, and introduce the concurrency API, including the Fork/Join
Framework. The material is presented in a straightforward manner that is designed to
give the student a solid overview of several core library elements.

OBJECTS SOON…BUT NOT TOO SOON


One of the first commonly-asked questions about a programming book is whether
it uses an “objects early” or an “objects late” approach to teaching the key tenets of
object-oriented programming. Of course, what constitutes “early” or “late” can be
somewhat subjective, and neither term precisely describes the organization of this
book. The phrase we use to characterize our approach is “objects soon, but not too
soon.” Our goal is to introduce objects at the appropriate time for the student. We
believe that this is not until key features of the language have been learned.
Towards this end, the focus of the first three chapters is on the fundamentals of the
Java language, such as its syntax, data types, operators, and control statements. We
believe that mastery of these elements is a necessary first step because they form the
foundation of the language, and the foundation of programming in general. (In other
words, it is difficult to write meaningful programs without understanding these ele-
ments.) In our view, only after the basic elements of a program have been learned, is
the student ready to move forward to objects.
After the book has covered the fundamentals, objects are introduced in Chapter 4,
and from that point on, object-oriented features, techniques, and concepts are inte-
grated into the remaining chapters. Additionally, objects are introduced in a carefully
paced, step-by-step fashion. This is intended to help the student grasp each new fea-
ture in context, and without being overwhelmed.

PEDAGOGICAL FEATURES
This book includes several pedagogical elements to facilitate and reinforce learning.
Each feature helps ensure that students are fully aware of key skills, can gauge their
advancement, and can verify that all concepts are learned.
j Key Skills & Concepts: Each chapter begins with a list that identifies the key
skills and concepts presented in the chapter.
j Ask the Expert: At various points throughout the book are Ask the Expert
boxes. These contain additional information or interesting commentary about

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


Preface xxvii

a topic, and use a Question/Answer format. They provide supplemental infor-


mation without disrupting the main presentation flow.
j Try This Elements: Each chapter contains one or more Try This elements.
These are step-by-step examples that walk through the development of a
program that demonstrates an aspect of Java related to the chapter’s topic.
Typically, these are longer examples that show a feature in a more practical
setting.
j Progress Checks: Throughout each chapter, Progress Checks are presented
to test the student’s understanding of the preceding section. The answers to
these questions are at the bottom of the same page.
j Exercises: Each chapter concludes with exercises that include short answer,
fill-in-the-blank, and true/false questions, and coding exercises. The answers
to selected exercises are in Appendix C.

ACM RECOMMENDATIONS
The 2008 update to the ACM Curricula Recommendations (http://www.acm.org/
education/curricula/ComputerScience2008.pdf) recommends that all computer science
students be fluent in at least one programming language and have some understanding
of object-oriented and event-driven programming. We believe that students who learn
the material covered by this book will have the desired knowledge and skills. We have
included in the book not just an introduction to programming using the Java language,
but broader coverage that includes advanced Java features, the Swing framework, and
large parts of several important API packages.
The first part of the book covers a significant portion of the topics in the
Programming Fundamentals (PF) knowledge area of the ACM Recommendations
(the main exceptions being the knowledge units FoundationsInformationSecurity and
SecureProgramming). The first part also includes a chapter on object-oriented design,
which covers a number of the topics in the PL/ObjectOrientedProgramming and SE/
SoftwareDesign knowledge units. The second part of the book, which introduces
GUI programming with Swing, addresses some of the topics in the knowledge unit
HC/GUIProgramming. The third part includes, among others, topics that relate to
concurrency. In fact, we devote Chapters 12 and 27 to multithreading and concurrency
because we feel, as the ACM Curricular Recommendations discuss, that concurrency
is becoming increasingly relevant to the discipline of computer science.

ONLINE RESOURCES
Students can access all of the source code for the programs in the text at the website
that accompanies Java Programming: A Comprehensive Approach: www.mhhe.com/
schildt1e. This site also offers a number of useful resources for the Java instructor.
j A Solutions manual for end-of-chapter exercises.

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


xxviii preface

j Instructor Notes, including suggested curricula and suggestions for teaching


particular topics.
j Supplemental Exercises that can be used to create quizzes and tests.
j PowerPoint Slides that serve as an outline for in-class instruction.
Please contact your McGraw-Hill representative for access information.

Additional instructor resources include:

This text is available as an eBook at www.CourseSmart.com. At CourseSmart your


students can take advantage of significant savings off the cost of a print textbook,
reduce their impact on the environment, and gain access to powerful web tools for
learning. CourseSmart eBooks can be viewed online or downloaded to a computer.
The eBooks allow students to do full text searches, add highlighting and notes, and
share notes with classmates. CourseSmart has the largest selection of eBooks available
anywhere. Visit www.CourseSmart.com to learn more and to try a sample chapter.

Craft your teaching resources to match the way you teach! With McGraw-Hill
Create™, www.mcgrawhillcreate.com, you can easily rearrange chapters, combine
material from other content sources, and quickly upload content you have written,
such as your course syllabus or teaching notes. Find the content you need in Create
by searching through thousands of leading McGraw-Hill textbooks. Arrange your
book to fit your teaching style. Create even allows you to personalize your book’s
appearance by selecting the cover and adding your name, school, and course infor-
mation. Order a Create book and you’ll receive a complimentary print review copy
in 3–5 business days or a complimentary electronic review copy (eComp) via email
in minutes. Go to www.mcgrawhillcreate.com today and register to experience how
McGraw-Hill Create™ empowers you to teach your students your way.

ACKNOWLEDGMENTS
We wish to acknowledge the many contributions made by the following people at
McGraw-Hill, without whom this book would not exist. They have made working on
the book a delight.
Editorial Director, Michael Lange
Global Publisher, Raghu Srinivasan
Senior Marketing Manager, Curt Reynolds
Developmental Editor, Robin Reed
Developmental Editor, Kathryn Neubauer

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


Preface xxix

Senior Project Manager, Lisa Bruflodt


Design Coordinator, Brenda Rolwes
Production Editor, Rose Kernan
We would also like to thank the following reviewers for their many helpful
comments, which were much appreciated.
Bill Barge, Trine University
Chris Bennett, University of Maine–Farmington
Augusto Casas, St Thomas Aquinas College
I-ping Chu, DePaul University
Vasil Hnatyshin, Rowan University
Rodney Hoffman, Occidental College
David Kamper Sr., Northeastern Illinois University
BJ Tjaden, Anne Arundel Community College
Richard Weiss, Evergreen State College
James Braman, Towson University
Steve Cooper, Stanford University
Michael Main, University of Colorado—Boulder
Jay McCarthy, Brigham Young University
Robert Moll, University of Massachusetts—Amherst
Jagadeesh Nandigam, Grand Valley State University
Gurpur Prabhu, Iowa State University
Daisy Sang, California State Polytechnic University
Mark Sherriff, University of Virginia
Joslyn Smith, Florida International University
James Young, University of Manitoba
Finally, and most importantly, we would like to thank our families for their support
during the preparation of this book.

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


sch2207X_fm_p0i-xxxvi.indd 30 23/12/11 4:29 PM
About the authors

Herbert Schildt has been writing about programming since 1984 and is the author
of several books on Java, C++, C, and C#. His programming books have sold
millions of copies worldwide and have been widely translated. Although he is
interested in all facets of computing, his primary focus is computer languages,
including the standardization of languages. Schildt holds BA and MCS degrees
from the University of Illinois, Urbana/Champaign. He provided the initial drafts
for most of the chapters in this book.

Dale Skrien has been teaching mathematics and computer science at Colby College
since 1980 and has been teaching Java since 1996. His interest in teaching stu-
dents not just how to program, but how to program well, led to the publication of
his textbook Object-Oriented Design using Java by McGraw-Hill. He holds a BA
degree from St. Olaf College, MS degrees from the University of Illinois and the
University of Washington, and a PhD degree from the University of Washington.
In addition to contributions throughout the book, he provided Chapter 16, which
introduces object-oriented design. He also provided the online supplements for
this book.

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


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

Since all Java programCode


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

3. Compile the program using the following command line:


javac GalToLitTable.java

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

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


c contains -1
c is negative

c contains 1
c is non-negative

Notice one other thing in this program. The line


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

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

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

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

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

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


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

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

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


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

to answer this question. Thus, the situation


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

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


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

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

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


Another random document with
no related content on Scribd:
DANCE ON STILTS AT THE GIRLS’ UNYAGO, NIUCHI

Newala, too, suffers from the distance of its water-supply—at least


the Newala of to-day does; there was once another Newala in a lovely
valley at the foot of the plateau. I visited it and found scarcely a trace
of houses, only a Christian cemetery, with the graves of several
missionaries and their converts, remaining as a monument of its
former glories. But the surroundings are wonderfully beautiful. A
thick grove of splendid mango-trees closes in the weather-worn
crosses and headstones; behind them, combining the useful and the
agreeable, is a whole plantation of lemon-trees covered with ripe
fruit; not the small African kind, but a much larger and also juicier
imported variety, which drops into the hands of the passing traveller,
without calling for any exertion on his part. Old Newala is now under
the jurisdiction of the native pastor, Daudi, at Chingulungulu, who,
as I am on very friendly terms with him, allows me, as a matter of
course, the use of this lemon-grove during my stay at Newala.
FEET MUTILATED BY THE RAVAGES OF THE “JIGGER”
(Sarcopsylla penetrans)

The water-supply of New Newala is in the bottom of the valley,


some 1,600 feet lower down. The way is not only long and fatiguing,
but the water, when we get it, is thoroughly bad. We are suffering not
only from this, but from the fact that the arrangements at Newala are
nothing short of luxurious. We have a separate kitchen—a hut built
against the boma palisade on the right of the baraza, the interior of
which is not visible from our usual position. Our two cooks were not
long in finding this out, and they consequently do—or rather neglect
to do—what they please. In any case they do not seem to be very
particular about the boiling of our drinking-water—at least I can
attribute to no other cause certain attacks of a dysenteric nature,
from which both Knudsen and I have suffered for some time. If a
man like Omari has to be left unwatched for a moment, he is capable
of anything. Besides this complaint, we are inconvenienced by the
state of our nails, which have become as hard as glass, and crack on
the slightest provocation, and I have the additional infliction of
pimples all over me. As if all this were not enough, we have also, for
the last week been waging war against the jigger, who has found his
Eldorado in the hot sand of the Makonde plateau. Our men are seen
all day long—whenever their chronic colds and the dysentery likewise
raging among them permit—occupied in removing this scourge of
Africa from their feet and trying to prevent the disastrous
consequences of its presence. It is quite common to see natives of
this place with one or two toes missing; many have lost all their toes,
or even the whole front part of the foot, so that a well-formed leg
ends in a shapeless stump. These ravages are caused by the female of
Sarcopsylla penetrans, which bores its way under the skin and there
develops an egg-sac the size of a pea. In all books on the subject, it is
stated that one’s attention is called to the presence of this parasite by
an intolerable itching. This agrees very well with my experience, so
far as the softer parts of the sole, the spaces between and under the
toes, and the side of the foot are concerned, but if the creature
penetrates through the harder parts of the heel or ball of the foot, it
may escape even the most careful search till it has reached maturity.
Then there is no time to be lost, if the horrible ulceration, of which
we see cases by the dozen every day, is to be prevented. It is much
easier, by the way, to discover the insect on the white skin of a
European than on that of a native, on which the dark speck scarcely
shows. The four or five jiggers which, in spite of the fact that I
constantly wore high laced boots, chose my feet to settle in, were
taken out for me by the all-accomplished Knudsen, after which I
thought it advisable to wash out the cavities with corrosive
sublimate. The natives have a different sort of disinfectant—they fill
the hole with scraped roots. In a tiny Makua village on the slope of
the plateau south of Newala, we saw an old woman who had filled all
the spaces under her toe-nails with powdered roots by way of
prophylactic treatment. What will be the result, if any, who can say?
The rest of the many trifling ills which trouble our existence are
really more comic than serious. In the absence of anything else to
smoke, Knudsen and I at last opened a box of cigars procured from
the Indian store-keeper at Lindi, and tried them, with the most
distressing results. Whether they contain opium or some other
narcotic, neither of us can say, but after the tenth puff we were both
“off,” three-quarters stupefied and unspeakably wretched. Slowly we
recovered—and what happened next? Half-an-hour later we were
once more smoking these poisonous concoctions—so insatiable is the
craving for tobacco in the tropics.
Even my present attacks of fever scarcely deserve to be taken
seriously. I have had no less than three here at Newala, all of which
have run their course in an incredibly short time. In the early
afternoon, I am busy with my old natives, asking questions and
making notes. The strong midday coffee has stimulated my spirits to
an extraordinary degree, the brain is active and vigorous, and work
progresses rapidly, while a pleasant warmth pervades the whole
body. Suddenly this gives place to a violent chill, forcing me to put on
my overcoat, though it is only half-past three and the afternoon sun
is at its hottest. Now the brain no longer works with such acuteness
and logical precision; more especially does it fail me in trying to
establish the syntax of the difficult Makua language on which I have
ventured, as if I had not enough to do without it. Under the
circumstances it seems advisable to take my temperature, and I do
so, to save trouble, without leaving my seat, and while going on with
my work. On examination, I find it to be 101·48°. My tutors are
abruptly dismissed and my bed set up in the baraza; a few minutes
later I am in it and treating myself internally with hot water and
lemon-juice.
Three hours later, the thermometer marks nearly 104°, and I make
them carry me back into the tent, bed and all, as I am now perspiring
heavily, and exposure to the cold wind just beginning to blow might
mean a fatal chill. I lie still for a little while, and then find, to my
great relief, that the temperature is not rising, but rather falling. This
is about 7.30 p.m. At 8 p.m. I find, to my unbounded astonishment,
that it has fallen below 98·6°, and I feel perfectly well. I read for an
hour or two, and could very well enjoy a smoke, if I had the
wherewithal—Indian cigars being out of the question.
Having no medical training, I am at a loss to account for this state
of things. It is impossible that these transitory attacks of high fever
should be malarial; it seems more probable that they are due to a
kind of sunstroke. On consulting my note-book, I become more and
more inclined to think this is the case, for these attacks regularly
follow extreme fatigue and long exposure to strong sunshine. They at
least have the advantage of being only short interruptions to my
work, as on the following morning I am always quite fresh and fit.
My treasure of a cook is suffering from an enormous hydrocele which
makes it difficult for him to get up, and Moritz is obliged to keep in
the dark on account of his inflamed eyes. Knudsen’s cook, a raw boy
from somewhere in the bush, knows still less of cooking than Omari;
consequently Nils Knudsen himself has been promoted to the vacant
post. Finding that we had come to the end of our supplies, he began
by sending to Chingulungulu for the four sucking-pigs which we had
bought from Matola and temporarily left in his charge; and when
they came up, neatly packed in a large crate, he callously slaughtered
the biggest of them. The first joint we were thoughtless enough to
entrust for roasting to Knudsen’s mshenzi cook, and it was
consequently uneatable; but we made the rest of the animal into a
jelly which we ate with great relish after weeks of underfeeding,
consuming incredible helpings of it at both midday and evening
meals. The only drawback is a certain want of variety in the tinned
vegetables. Dr. Jäger, to whom the Geographical Commission
entrusted the provisioning of the expeditions—mine as well as his
own—because he had more time on his hands than the rest of us,
seems to have laid in a huge stock of Teltow turnips,[46] an article of
food which is all very well for occasional use, but which quickly palls
when set before one every day; and we seem to have no other tins
left. There is no help for it—we must put up with the turnips; but I
am certain that, once I am home again, I shall not touch them for ten
years to come.
Amid all these minor evils, which, after all, go to make up the
genuine flavour of Africa, there is at least one cheering touch:
Knudsen has, with the dexterity of a skilled mechanic, repaired my 9
× 12 cm. camera, at least so far that I can use it with a little care.
How, in the absence of finger-nails, he was able to accomplish such a
ticklish piece of work, having no tool but a clumsy screw-driver for
taking to pieces and putting together again the complicated
mechanism of the instantaneous shutter, is still a mystery to me; but
he did it successfully. The loss of his finger-nails shows him in a light
contrasting curiously enough with the intelligence evinced by the
above operation; though, after all, it is scarcely surprising after his
ten years’ residence in the bush. One day, at Lindi, he had occasion
to wash a dog, which must have been in need of very thorough
cleansing, for the bottle handed to our friend for the purpose had an
extremely strong smell. Having performed his task in the most
conscientious manner, he perceived with some surprise that the dog
did not appear much the better for it, and was further surprised by
finding his own nails ulcerating away in the course of the next few
days. “How was I to know that carbolic acid has to be diluted?” he
mutters indignantly, from time to time, with a troubled gaze at his
mutilated finger-tips.
Since we came to Newala we have been making excursions in all
directions through the surrounding country, in accordance with old
habit, and also because the akida Sefu did not get together the tribal
elders from whom I wanted information so speedily as he had
promised. There is, however, no harm done, as, even if seen only
from the outside, the country and people are interesting enough.
The Makonde plateau is like a large rectangular table rounded off
at the corners. Measured from the Indian Ocean to Newala, it is
about seventy-five miles long, and between the Rovuma and the
Lukuledi it averages fifty miles in breadth, so that its superficial area
is about two-thirds of that of the kingdom of Saxony. The surface,
however, is not level, but uniformly inclined from its south-western
edge to the ocean. From the upper edge, on which Newala lies, the
eye ranges for many miles east and north-east, without encountering
any obstacle, over the Makonde bush. It is a green sea, from which
here and there thick clouds of smoke rise, to show that it, too, is
inhabited by men who carry on their tillage like so many other
primitive peoples, by cutting down and burning the bush, and
manuring with the ashes. Even in the radiant light of a tropical day
such a fire is a grand sight.
Much less effective is the impression produced just now by the
great western plain as seen from the edge of the plateau. As often as
time permits, I stroll along this edge, sometimes in one direction,
sometimes in another, in the hope of finding the air clear enough to
let me enjoy the view; but I have always been disappointed.
Wherever one looks, clouds of smoke rise from the burning bush,
and the air is full of smoke and vapour. It is a pity, for under more
favourable circumstances the panorama of the whole country up to
the distant Majeje hills must be truly magnificent. It is of little use
taking photographs now, and an outline sketch gives a very poor idea
of the scenery. In one of these excursions I went out of my way to
make a personal attempt on the Makonde bush. The present edge of
the plateau is the result of a far-reaching process of destruction
through erosion and denudation. The Makonde strata are
everywhere cut into by ravines, which, though short, are hundreds of
yards in depth. In consequence of the loose stratification of these
beds, not only are the walls of these ravines nearly vertical, but their
upper end is closed by an equally steep escarpment, so that the
western edge of the Makonde plateau is hemmed in by a series of
deep, basin-like valleys. In order to get from one side of such a ravine
to the other, I cut my way through the bush with a dozen of my men.
It was a very open part, with more grass than scrub, but even so the
short stretch of less than two hundred yards was very hard work; at
the end of it the men’s calicoes were in rags and they themselves
bleeding from hundreds of scratches, while even our strong khaki
suits had not escaped scatheless.

NATIVE PATH THROUGH THE MAKONDE BUSH, NEAR


MAHUTA

I see increasing reason to believe that the view formed some time
back as to the origin of the Makonde bush is the correct one. I have
no doubt that it is not a natural product, but the result of human
occupation. Those parts of the high country where man—as a very
slight amount of practice enables the eye to perceive at once—has not
yet penetrated with axe and hoe, are still occupied by a splendid
timber forest quite able to sustain a comparison with our mixed
forests in Germany. But wherever man has once built his hut or tilled
his field, this horrible bush springs up. Every phase of this process
may be seen in the course of a couple of hours’ walk along the main
road. From the bush to right or left, one hears the sound of the axe—
not from one spot only, but from several directions at once. A few
steps further on, we can see what is taking place. The brush has been
cut down and piled up in heaps to the height of a yard or more,
between which the trunks of the large trees stand up like the last
pillars of a magnificent ruined building. These, too, present a
melancholy spectacle: the destructive Makonde have ringed them—
cut a broad strip of bark all round to ensure their dying off—and also
piled up pyramids of brush round them. Father and son, mother and
son-in-law, are chopping away perseveringly in the background—too
busy, almost, to look round at the white stranger, who usually excites
so much interest. If you pass by the same place a week later, the piles
of brushwood have disappeared and a thick layer of ashes has taken
the place of the green forest. The large trees stretch their
smouldering trunks and branches in dumb accusation to heaven—if
they have not already fallen and been more or less reduced to ashes,
perhaps only showing as a white stripe on the dark ground.
This work of destruction is carried out by the Makonde alike on the
virgin forest and on the bush which has sprung up on sites already
cultivated and deserted. In the second case they are saved the trouble
of burning the large trees, these being entirely absent in the
secondary bush.
After burning this piece of forest ground and loosening it with the
hoe, the native sows his corn and plants his vegetables. All over the
country, he goes in for bed-culture, which requires, and, in fact,
receives, the most careful attention. Weeds are nowhere tolerated in
the south of German East Africa. The crops may fail on the plains,
where droughts are frequent, but never on the plateau with its
abundant rains and heavy dews. Its fortunate inhabitants even have
the satisfaction of seeing the proud Wayao and Wamakua working
for them as labourers, driven by hunger to serve where they were
accustomed to rule.
But the light, sandy soil is soon exhausted, and would yield no
harvest the second year if cultivated twice running. This fact has
been familiar to the native for ages; consequently he provides in
time, and, while his crop is growing, prepares the next plot with axe
and firebrand. Next year he plants this with his various crops and
lets the first piece lie fallow. For a short time it remains waste and
desolate; then nature steps in to repair the destruction wrought by
man; a thousand new growths spring out of the exhausted soil, and
even the old stumps put forth fresh shoots. Next year the new growth
is up to one’s knees, and in a few years more it is that terrible,
impenetrable bush, which maintains its position till the black
occupier of the land has made the round of all the available sites and
come back to his starting point.
The Makonde are, body and soul, so to speak, one with this bush.
According to my Yao informants, indeed, their name means nothing
else but “bush people.” Their own tradition says that they have been
settled up here for a very long time, but to my surprise they laid great
stress on an original immigration. Their old homes were in the
south-east, near Mikindani and the mouth of the Rovuma, whence
their peaceful forefathers were driven by the continual raids of the
Sakalavas from Madagascar and the warlike Shirazis[47] of the coast,
to take refuge on the almost inaccessible plateau. I have studied
African ethnology for twenty years, but the fact that changes of
population in this apparently quiet and peaceable corner of the earth
could have been occasioned by outside enterprises taking place on
the high seas, was completely new to me. It is, no doubt, however,
correct.
The charming tribal legend of the Makonde—besides informing us
of other interesting matters—explains why they have to live in the
thickest of the bush and a long way from the edge of the plateau,
instead of making their permanent homes beside the purling brooks
and springs of the low country.
“The place where the tribe originated is Mahuta, on the southern
side of the plateau towards the Rovuma, where of old time there was
nothing but thick bush. Out of this bush came a man who never
washed himself or shaved his head, and who ate and drank but little.
He went out and made a human figure from the wood of a tree
growing in the open country, which he took home to his abode in the
bush and there set it upright. In the night this image came to life and
was a woman. The man and woman went down together to the
Rovuma to wash themselves. Here the woman gave birth to a still-
born child. They left that place and passed over the high land into the
valley of the Mbemkuru, where the woman had another child, which
was also born dead. Then they returned to the high bush country of
Mahuta, where the third child was born, which lived and grew up. In
course of time, the couple had many more children, and called
themselves Wamatanda. These were the ancestral stock of the
Makonde, also called Wamakonde,[48] i.e., aborigines. Their
forefather, the man from the bush, gave his children the command to
bury their dead upright, in memory of the mother of their race who
was cut out of wood and awoke to life when standing upright. He also
warned them against settling in the valleys and near large streams,
for sickness and death dwelt there. They were to make it a rule to
have their huts at least an hour’s walk from the nearest watering-
place; then their children would thrive and escape illness.”
The explanation of the name Makonde given by my informants is
somewhat different from that contained in the above legend, which I
extract from a little book (small, but packed with information), by
Pater Adams, entitled Lindi und sein Hinterland. Otherwise, my
results agree exactly with the statements of the legend. Washing?
Hapana—there is no such thing. Why should they do so? As it is, the
supply of water scarcely suffices for cooking and drinking; other
people do not wash, so why should the Makonde distinguish himself
by such needless eccentricity? As for shaving the head, the short,
woolly crop scarcely needs it,[49] so the second ancestral precept is
likewise easy enough to follow. Beyond this, however, there is
nothing ridiculous in the ancestor’s advice. I have obtained from
various local artists a fairly large number of figures carved in wood,
ranging from fifteen to twenty-three inches in height, and
representing women belonging to the great group of the Mavia,
Makonde, and Matambwe tribes. The carving is remarkably well
done and renders the female type with great accuracy, especially the
keloid ornamentation, to be described later on. As to the object and
meaning of their works the sculptors either could or (more probably)
would tell me nothing, and I was forced to content myself with the
scanty information vouchsafed by one man, who said that the figures
were merely intended to represent the nembo—the artificial
deformations of pelele, ear-discs, and keloids. The legend recorded
by Pater Adams places these figures in a new light. They must surely
be more than mere dolls; and we may even venture to assume that
they are—though the majority of present-day Makonde are probably
unaware of the fact—representations of the tribal ancestress.
The references in the legend to the descent from Mahuta to the
Rovuma, and to a journey across the highlands into the Mbekuru
valley, undoubtedly indicate the previous history of the tribe, the
travels of the ancestral pair typifying the migrations of their
descendants. The descent to the neighbouring Rovuma valley, with
its extraordinary fertility and great abundance of game, is intelligible
at a glance—but the crossing of the Lukuledi depression, the ascent
to the Rondo Plateau and the descent to the Mbemkuru, also lie
within the bounds of probability, for all these districts have exactly
the same character as the extreme south. Now, however, comes a
point of especial interest for our bacteriological age. The primitive
Makonde did not enjoy their lives in the marshy river-valleys.
Disease raged among them, and many died. It was only after they
had returned to their original home near Mahuta, that the health
conditions of these people improved. We are very apt to think of the
African as a stupid person whose ignorance of nature is only equalled
by his fear of it, and who looks on all mishaps as caused by evil
spirits and malignant natural powers. It is much more correct to
assume in this case that the people very early learnt to distinguish
districts infested with malaria from those where it is absent.
This knowledge is crystallized in the
ancestral warning against settling in the
valleys and near the great waters, the
dwelling-places of disease and death. At the
same time, for security against the hostile
Mavia south of the Rovuma, it was enacted
that every settlement must be not less than a
certain distance from the southern edge of the
plateau. Such in fact is their mode of life at the
present day. It is not such a bad one, and
certainly they are both safer and more
comfortable than the Makua, the recent
intruders from the south, who have made USUAL METHOD OF
good their footing on the western edge of the CLOSING HUT-DOOR
plateau, extending over a fairly wide belt of
country. Neither Makua nor Makonde show in their dwellings
anything of the size and comeliness of the Yao houses in the plain,
especially at Masasi, Chingulungulu and Zuza’s. Jumbe Chauro, a
Makonde hamlet not far from Newala, on the road to Mahuta, is the
most important settlement of the tribe I have yet seen, and has fairly
spacious huts. But how slovenly is their construction compared with
the palatial residences of the elephant-hunters living in the plain.
The roofs are still more untidy than in the general run of huts during
the dry season, the walls show here and there the scanty beginnings
or the lamentable remains of the mud plastering, and the interior is a
veritable dog-kennel; dirt, dust and disorder everywhere. A few huts
only show any attempt at division into rooms, and this consists
merely of very roughly-made bamboo partitions. In one point alone
have I noticed any indication of progress—in the method of fastening
the door. Houses all over the south are secured in a simple but
ingenious manner. The door consists of a set of stout pieces of wood
or bamboo, tied with bark-string to two cross-pieces, and moving in
two grooves round one of the door-posts, so as to open inwards. If
the owner wishes to leave home, he takes two logs as thick as a man’s
upper arm and about a yard long. One of these is placed obliquely
against the middle of the door from the inside, so as to form an angle
of from 60° to 75° with the ground. He then places the second piece
horizontally across the first, pressing it downward with all his might.
It is kept in place by two strong posts planted in the ground a few
inches inside the door. This fastening is absolutely safe, but of course
cannot be applied to both doors at once, otherwise how could the
owner leave or enter his house? I have not yet succeeded in finding
out how the back door is fastened.

MAKONDE LOCK AND KEY AT JUMBE CHAURO


This is the general way of closing a house. The Makonde at Jumbe
Chauro, however, have a much more complicated, solid and original
one. Here, too, the door is as already described, except that there is
only one post on the inside, standing by itself about six inches from
one side of the doorway. Opposite this post is a hole in the wall just
large enough to admit a man’s arm. The door is closed inside by a
large wooden bolt passing through a hole in this post and pressing
with its free end against the door. The other end has three holes into
which fit three pegs running in vertical grooves inside the post. The
door is opened with a wooden key about a foot long, somewhat
curved and sloped off at the butt; the other end has three pegs
corresponding to the holes, in the bolt, so that, when it is thrust
through the hole in the wall and inserted into the rectangular
opening in the post, the pegs can be lifted and the bolt drawn out.[50]

MODE OF INSERTING THE KEY

With no small pride first one householder and then a second


showed me on the spot the action of this greatest invention of the
Makonde Highlands. To both with an admiring exclamation of
“Vizuri sana!” (“Very fine!”). I expressed the wish to take back these
marvels with me to Ulaya, to show the Wazungu what clever fellows
the Makonde are. Scarcely five minutes after my return to camp at
Newala, the two men came up sweating under the weight of two
heavy logs which they laid down at my feet, handing over at the same
time the keys of the fallen fortress. Arguing, logically enough, that if
the key was wanted, the lock would be wanted with it, they had taken
their axes and chopped down the posts—as it never occurred to them
to dig them out of the ground and so bring them intact. Thus I have
two badly damaged specimens, and the owners, instead of praise,
come in for a blowing-up.
The Makua huts in the environs of Newala are especially
miserable; their more than slovenly construction reminds one of the
temporary erections of the Makua at Hatia’s, though the people here
have not been concerned in a war. It must therefore be due to
congenital idleness, or else to the absence of a powerful chief. Even
the baraza at Mlipa’s, a short hour’s walk south-east of Newala,
shares in this general neglect. While public buildings in this country
are usually looked after more or less carefully, this is in evident
danger of being blown over by the first strong easterly gale. The only
attractive object in this whole district is the grave of the late chief
Mlipa. I visited it in the morning, while the sun was still trying with
partial success to break through the rolling mists, and the circular
grove of tall euphorbias, which, with a broken pot, is all that marks
the old king’s resting-place, impressed one with a touch of pathos.
Even my very materially-minded carriers seemed to feel something
of the sort, for instead of their usual ribald songs, they chanted
solemnly, as we marched on through the dense green of the Makonde
bush:—
“We shall arrive with the great master; we stand in a row and have
no fear about getting our food and our money from the Serkali (the
Government). We are not afraid; we are going along with the great
master, the lion; we are going down to the coast and back.”
With regard to the characteristic features of the various tribes here
on the western edge of the plateau, I can arrive at no other
conclusion than the one already come to in the plain, viz., that it is
impossible for anyone but a trained anthropologist to assign any
given individual at once to his proper tribe. In fact, I think that even
an anthropological specialist, after the most careful examination,
might find it a difficult task to decide. The whole congeries of peoples
collected in the region bounded on the west by the great Central
African rift, Tanganyika and Nyasa, and on the east by the Indian
Ocean, are closely related to each other—some of their languages are
only distinguished from one another as dialects of the same speech,
and no doubt all the tribes present the same shape of skull and
structure of skeleton. Thus, surely, there can be no very striking
differences in outward appearance.
Even did such exist, I should have no time
to concern myself with them, for day after day,
I have to see or hear, as the case may be—in
any case to grasp and record—an
extraordinary number of ethnographic
phenomena. I am almost disposed to think it
fortunate that some departments of inquiry, at
least, are barred by external circumstances.
Chief among these is the subject of iron-
working. We are apt to think of Africa as a
country where iron ore is everywhere, so to
speak, to be picked up by the roadside, and
where it would be quite surprising if the
inhabitants had not learnt to smelt the
material ready to their hand. In fact, the
knowledge of this art ranges all over the
continent, from the Kabyles in the north to the
Kafirs in the south. Here between the Rovuma
and the Lukuledi the conditions are not so
favourable. According to the statements of the
Makonde, neither ironstone nor any other
form of iron ore is known to them. They have
not therefore advanced to the art of smelting
the metal, but have hitherto bought all their
THE ANCESTRESS OF
THE MAKONDE
iron implements from neighbouring tribes.
Even in the plain the inhabitants are not much
better off. Only one man now living is said to
understand the art of smelting iron. This old fundi lives close to
Huwe, that isolated, steep-sided block of granite which rises out of
the green solitude between Masasi and Chingulungulu, and whose
jagged and splintered top meets the traveller’s eye everywhere. While
still at Masasi I wished to see this man at work, but was told that,
frightened by the rising, he had retired across the Rovuma, though
he would soon return. All subsequent inquiries as to whether the
fundi had come back met with the genuine African answer, “Bado”
(“Not yet”).
BRAZIER

Some consolation was afforded me by a brassfounder, whom I


came across in the bush near Akundonde’s. This man is the favourite
of women, and therefore no doubt of the gods; he welds the glittering
brass rods purchased at the coast into those massive, heavy rings
which, on the wrists and ankles of the local fair ones, continually give
me fresh food for admiration. Like every decent master-craftsman he
had all his tools with him, consisting of a pair of bellows, three
crucibles and a hammer—nothing more, apparently. He was quite
willing to show his skill, and in a twinkling had fixed his bellows on
the ground. They are simply two goat-skins, taken off whole, the four
legs being closed by knots, while the upper opening, intended to
admit the air, is kept stretched by two pieces of wood. At the lower
end of the skin a smaller opening is left into which a wooden tube is
stuck. The fundi has quickly borrowed a heap of wood-embers from
the nearest hut; he then fixes the free ends of the two tubes into an
earthen pipe, and clamps them to the ground by means of a bent
piece of wood. Now he fills one of his small clay crucibles, the dross
on which shows that they have been long in use, with the yellow
material, places it in the midst of the embers, which, at present are
only faintly glimmering, and begins his work. In quick alternation
the smith’s two hands move up and down with the open ends of the
bellows; as he raises his hand he holds the slit wide open, so as to let
the air enter the skin bag unhindered. In pressing it down he closes
the bag, and the air puffs through the bamboo tube and clay pipe into
the fire, which quickly burns up. The smith, however, does not keep
on with this work, but beckons to another man, who relieves him at
the bellows, while he takes some more tools out of a large skin pouch
carried on his back. I look on in wonder as, with a smooth round
stick about the thickness of a finger, he bores a few vertical holes into
the clean sand of the soil. This should not be difficult, yet the man
seems to be taking great pains over it. Then he fastens down to the
ground, with a couple of wooden clamps, a neat little trough made by
splitting a joint of bamboo in half, so that the ends are closed by the
two knots. At last the yellow metal has attained the right consistency,
and the fundi lifts the crucible from the fire by means of two sticks
split at the end to serve as tongs. A short swift turn to the left—a
tilting of the crucible—and the molten brass, hissing and giving forth
clouds of smoke, flows first into the bamboo mould and then into the
holes in the ground.
The technique of this backwoods craftsman may not be very far
advanced, but it cannot be denied that he knows how to obtain an
adequate result by the simplest means. The ladies of highest rank in
this country—that is to say, those who can afford it, wear two kinds
of these massive brass rings, one cylindrical, the other semicircular
in section. The latter are cast in the most ingenious way in the
bamboo mould, the former in the circular hole in the sand. It is quite
a simple matter for the fundi to fit these bars to the limbs of his fair
customers; with a few light strokes of his hammer he bends the
pliable brass round arm or ankle without further inconvenience to
the wearer.
SHAPING THE POT

SMOOTHING WITH MAIZE-COB

CUTTING THE EDGE


FINISHING THE BOTTOM

LAST SMOOTHING BEFORE


BURNING

FIRING THE BRUSH-PILE


LIGHTING THE FARTHER SIDE OF
THE PILE

TURNING THE RED-HOT VESSEL

NYASA WOMAN MAKING POTS AT MASASI


Pottery is an art which must always and everywhere excite the
interest of the student, just because it is so intimately connected with
the development of human culture, and because its relics are one of
the principal factors in the reconstruction of our own condition in
prehistoric times. I shall always remember with pleasure the two or
three afternoons at Masasi when Salim Matola’s mother, a slightly-
built, graceful, pleasant-looking woman, explained to me with
touching patience, by means of concrete illustrations, the ceramic art
of her people. The only implements for this primitive process were a
lump of clay in her left hand, and in the right a calabash containing
the following valuables: the fragment of a maize-cob stripped of all
its grains, a smooth, oval pebble, about the size of a pigeon’s egg, a
few chips of gourd-shell, a bamboo splinter about the length of one’s
hand, a small shell, and a bunch of some herb resembling spinach.
Nothing more. The woman scraped with the
shell a round, shallow hole in the soft, fine
sand of the soil, and, when an active young
girl had filled the calabash with water for her,
she began to knead the clay. As if by magic it
gradually assumed the shape of a rough but
already well-shaped vessel, which only wanted
a little touching up with the instruments
before mentioned. I looked out with the
MAKUA WOMAN closest attention for any indication of the use
MAKING A POT. of the potter’s wheel, in however rudimentary
SHOWS THE a form, but no—hapana (there is none). The
BEGINNINGS OF THE embryo pot stood firmly in its little
POTTER’S WHEEL
depression, and the woman walked round it in
a stooping posture, whether she was removing
small stones or similar foreign bodies with the maize-cob, smoothing
the inner or outer surface with the splinter of bamboo, or later, after
letting it dry for a day, pricking in the ornamentation with a pointed
bit of gourd-shell, or working out the bottom, or cutting the edge
with a sharp bamboo knife, or giving the last touches to the finished
vessel. This occupation of the women is infinitely toilsome, but it is
without doubt an accurate reproduction of the process in use among
our ancestors of the Neolithic and Bronze ages.
There is no doubt that the invention of pottery, an item in human
progress whose importance cannot be over-estimated, is due to
women. Rough, coarse and unfeeling, the men of the horde range
over the countryside. When the united cunning of the hunters has
succeeded in killing the game; not one of them thinks of carrying
home the spoil. A bright fire, kindled by a vigorous wielding of the
drill, is crackling beside them; the animal has been cleaned and cut
up secundum artem, and, after a slight singeing, will soon disappear
under their sharp teeth; no one all this time giving a single thought
to wife or child.
To what shifts, on the other hand, the primitive wife, and still more
the primitive mother, was put! Not even prehistoric stomachs could
endure an unvarying diet of raw food. Something or other suggested
the beneficial effect of hot water on the majority of approved but
indigestible dishes. Perhaps a neighbour had tried holding the hard
roots or tubers over the fire in a calabash filled with water—or maybe
an ostrich-egg-shell, or a hastily improvised vessel of bark. They
became much softer and more palatable than they had previously
been; but, unfortunately, the vessel could not stand the fire and got
charred on the outside. That can be remedied, thought our
ancestress, and plastered a layer of wet clay round a similar vessel.
This is an improvement; the cooking utensil remains uninjured, but
the heat of the fire has shrunk it, so that it is loose in its shell. The
next step is to detach it, so, with a firm grip and a jerk, shell and
kernel are separated, and pottery is invented. Perhaps, however, the
discovery which led to an intelligent use of the burnt-clay shell, was
made in a slightly different way. Ostrich-eggs and calabashes are not
to be found in every part of the world, but everywhere mankind has
arrived at the art of making baskets out of pliant materials, such as
bark, bast, strips of palm-leaf, supple twigs, etc. Our inventor has no
water-tight vessel provided by nature. “Never mind, let us line the
basket with clay.” This answers the purpose, but alas! the basket gets
burnt over the blazing fire, the woman watches the process of
cooking with increasing uneasiness, fearing a leak, but no leak
appears. The food, done to a turn, is eaten with peculiar relish; and
the cooking-vessel is examined, half in curiosity, half in satisfaction
at the result. The plastic clay is now hard as stone, and at the same
time looks exceedingly well, for the neat plaiting of the burnt basket
is traced all over it in a pretty pattern. Thus, simultaneously with
pottery, its ornamentation was invented.
Primitive woman has another claim to respect. It was the man,
roving abroad, who invented the art of producing fire at will, but the
woman, unable to imitate him in this, has been a Vestal from the
earliest times. Nothing gives so much trouble as the keeping alight of
the smouldering brand, and, above all, when all the men are absent
from the camp. Heavy rain-clouds gather, already the first large
drops are falling, the first gusts of the storm rage over the plain. The
little flame, a greater anxiety to the woman than her own children,
flickers unsteadily in the blast. What is to be done? A sudden thought
occurs to her, and in an instant she has constructed a primitive hut
out of strips of bark, to protect the flame against rain and wind.
This, or something very like it, was the way in which the principle
of the house was discovered; and even the most hardened misogynist
cannot fairly refuse a woman the credit of it. The protection of the
hearth-fire from the weather is the germ from which the human
dwelling was evolved. Men had little, if any share, in this forward
step, and that only at a late stage. Even at the present day, the
plastering of the housewall with clay and the manufacture of pottery
are exclusively the women’s business. These are two very significant
survivals. Our European kitchen-garden, too, is originally a woman’s
invention, and the hoe, the primitive instrument of agriculture, is,
characteristically enough, still used in this department. But the
noblest achievement which we owe to the other sex is unquestionably
the art of cookery. Roasting alone—the oldest process—is one for
which men took the hint (a very obvious one) from nature. It must
have been suggested by the scorched carcase of some animal
overtaken by the destructive forest-fires. But boiling—the process of
improving organic substances by the help of water heated to boiling-
point—is a much later discovery. It is so recent that it has not even
yet penetrated to all parts of the world. The Polynesians understand
how to steam food, that is, to cook it, neatly wrapped in leaves, in a
hole in the earth between hot stones, the air being excluded, and
(sometimes) a few drops of water sprinkled on the stones; but they
do not understand boiling.
To come back from this digression, we find that the slender Nyasa
woman has, after once more carefully examining the finished pot,
put it aside in the shade to dry. On the following day she sends me
word by her son, Salim Matola, who is always on hand, that she is
going to do the burning, and, on coming out of my house, I find her
already hard at work. She has spread on the ground a layer of very
dry sticks, about as thick as one’s thumb, has laid the pot (now of a
yellowish-grey colour) on them, and is piling brushwood round it.
My faithful Pesa mbili, the mnyampara, who has been standing by,
most obligingly, with a lighted stick, now hands it to her. Both of
them, blowing steadily, light the pile on the lee side, and, when the
flame begins to catch, on the weather side also. Soon the whole is in a
blaze, but the dry fuel is quickly consumed and the fire dies down, so
that we see the red-hot vessel rising from the ashes. The woman
turns it continually with a long stick, sometimes one way and
sometimes another, so that it may be evenly heated all over. In
twenty minutes she rolls it out of the ash-heap, takes up the bundle
of spinach, which has been lying for two days in a jar of water, and
sprinkles the red-hot clay with it. The places where the drops fall are
marked by black spots on the uniform reddish-brown surface. With a
sigh of relief, and with visible satisfaction, the woman rises to an
erect position; she is standing just in a line between me and the fire,
from which a cloud of smoke is just rising: I press the ball of my
camera, the shutter clicks—the apotheosis is achieved! Like a
priestess, representative of her inventive sex, the graceful woman
stands: at her feet the hearth-fire she has given us beside her the
invention she has devised for us, in the background the home she has
built for us.
At Newala, also, I have had the manufacture of pottery carried on
in my presence. Technically the process is better than that already
described, for here we find the beginnings of the potter’s wheel,
which does not seem to exist in the plains; at least I have seen
nothing of the sort. The artist, a frightfully stupid Makua woman, did
not make a depression in the ground to receive the pot she was about
to shape, but used instead a large potsherd. Otherwise, she went to
work in much the same way as Salim’s mother, except that she saved
herself the trouble of walking round and round her work by squatting
at her ease and letting the pot and potsherd rotate round her; this is
surely the first step towards a machine. But it does not follow that
the pot was improved by the process. It is true that it was beautifully
rounded and presented a very creditable appearance when finished,
but the numerous large and small vessels which I have seen, and, in
part, collected, in the “less advanced” districts, are no less so. We
moderns imagine that instruments of precision are necessary to
produce excellent results. Go to the prehistoric collections of our
museums and look at the pots, urns and bowls of our ancestors in the
dim ages of the past, and you will at once perceive your error.
MAKING LONGITUDINAL CUT IN
BARK

DRAWING THE BARK OFF THE LOG

REMOVING THE OUTER BARK


BEATING THE BARK

WORKING THE BARK-CLOTH AFTER BEATING, TO MAKE IT


SOFT

MANUFACTURE OF BARK-CLOTH AT NEWALA


To-day, nearly the whole population of German East Africa is
clothed in imported calico. This was not always the case; even now in
some parts of the north dressed skins are still the prevailing wear,
and in the north-western districts—east and north of Lake
Tanganyika—lies a zone where bark-cloth has not yet been
superseded. Probably not many generations have passed since such
bark fabrics and kilts of skins were the only clothing even in the
south. Even to-day, large quantities of this bright-red or drab
material are still to be found; but if we wish to see it, we must look in
the granaries and on the drying stages inside the native huts, where
it serves less ambitious uses as wrappings for those seeds and fruits
which require to be packed with special care. The salt produced at
Masasi, too, is packed for transport to a distance in large sheets of
bark-cloth. Wherever I found it in any degree possible, I studied the
process of making this cloth. The native requisitioned for the
purpose arrived, carrying a log between two and three yards long and
as thick as his thigh, and nothing else except a curiously-shaped
mallet and the usual long, sharp and pointed knife which all men and
boys wear in a belt at their backs without a sheath—horribile dictu!
[51]
Silently he squats down before me, and with two rapid cuts has
drawn a couple of circles round the log some two yards apart, and
slits the bark lengthwise between them with the point of his knife.
With evident care, he then scrapes off the outer rind all round the
log, so that in a quarter of an hour the inner red layer of the bark
shows up brightly-coloured between the two untouched ends. With
some trouble and much caution, he now loosens the bark at one end,
and opens the cylinder. He then stands up, takes hold of the free
edge with both hands, and turning it inside out, slowly but steadily
pulls it off in one piece. Now comes the troublesome work of
scraping all superfluous particles of outer bark from the outside of
the long, narrow piece of material, while the inner side is carefully
scrutinised for defective spots. At last it is ready for beating. Having
signalled to a friend, who immediately places a bowl of water beside
him, the artificer damps his sheet of bark all over, seizes his mallet,
lays one end of the stuff on the smoothest spot of the log, and
hammers away slowly but continuously. “Very simple!” I think to
myself. “Why, I could do that, too!”—but I am forced to change my
opinions a little later on; for the beating is quite an art, if the fabric is
not to be beaten to pieces. To prevent the breaking of the fibres, the
stuff is several times folded across, so as to interpose several
thicknesses between the mallet and the block. At last the required
state is reached, and the fundi seizes the sheet, still folded, by both
ends, and wrings it out, or calls an assistant to take one end while he
holds the other. The cloth produced in this way is not nearly so fine
and uniform in texture as the famous Uganda bark-cloth, but it is
quite soft, and, above all, cheap.
Now, too, I examine the mallet. My craftsman has been using the
simpler but better form of this implement, a conical block of some
hard wood, its base—the striking surface—being scored across and
across with more or less deeply-cut grooves, and the handle stuck
into a hole in the middle. The other and earlier form of mallet is
shaped in the same way, but the head is fastened by an ingenious
network of bark strips into the split bamboo serving as a handle. The
observation so often made, that ancient customs persist longest in
connection with religious ceremonies and in the life of children, here
finds confirmation. As we shall soon see, bark-cloth is still worn
during the unyago,[52] having been prepared with special solemn
ceremonies; and many a mother, if she has no other garment handy,
will still put her little one into a kilt of bark-cloth, which, after all,
looks better, besides being more in keeping with its African
surroundings, than the ridiculous bit of print from Ulaya.
MAKUA WOMEN

You might also like