0% found this document useful (0 votes)
11 views71 pages

Java Methods A Ab Object Oriented Programming and Data Structures Maria Litvin Download

The document provides information about various educational resources related to Java programming and object-oriented programming, including multiple eBooks available for download. It includes a detailed table of contents for a book titled 'Java Methods A & AB: Object-Oriented Programming and Data Structures' by Maria and Gary Litvin, outlining chapters on topics such as algorithms, data structures, and GUI components. Additionally, it contains copyright information and publisher details.

Uploaded by

tekjliig162
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views71 pages

Java Methods A Ab Object Oriented Programming and Data Structures Maria Litvin Download

The document provides information about various educational resources related to Java programming and object-oriented programming, including multiple eBooks available for download. It includes a detailed table of contents for a book titled 'Java Methods A & AB: Object-Oriented Programming and Data Structures' by Maria and Gary Litvin, outlining chapters on topics such as algorithms, data structures, and GUI components. Additionally, it contains copyright information and publisher details.

Uploaded by

tekjliig162
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/ 71

Java Methods A Ab Object oriented Programming

and Data Structures Maria Litvin download

https://ebookname.com/product/java-methods-a-ab-object-oriented-
programming-and-data-structures-maria-litvin/

Get the full ebook with Bonus Features for a Better Reading Experience on ebookname.com
Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Object Oriented Data Structures Using Java Chip Weems

https://ebookname.com/product/object-oriented-data-structures-
using-java-chip-weems/

A comprehensive introduction to object oriented


programming with Java 1st Edition C. Thomas Wu

https://ebookname.com/product/a-comprehensive-introduction-to-
object-oriented-programming-with-java-1st-edition-c-thomas-wu/

Object Oriented Programming Using C Fourth Edition


Joyce Farrell

https://ebookname.com/product/object-oriented-programming-using-
c-fourth-edition-joyce-farrell/

The Diaries of John Gregory Bourke Volumes 1 4 Charles


M. Robinson Iii

https://ebookname.com/product/the-diaries-of-john-gregory-bourke-
volumes-1-4-charles-m-robinson-iii/
Java How to Program 6th Edition Harvey Deitel & Paul
Deitel

https://ebookname.com/product/java-how-to-program-6th-edition-
harvey-deitel-paul-deitel/

Half the Human Experience 8th Edition Janet Shibley


Hyde

https://ebookname.com/product/half-the-human-experience-8th-
edition-janet-shibley-hyde/

Getting Things Done The Art of Stress Free Productivity


1st Edition David Allen

https://ebookname.com/product/getting-things-done-the-art-of-
stress-free-productivity-1st-edition-david-allen/

The DaVinci method Loporto

https://ebookname.com/product/the-davinci-method-loporto/

Hebrew Poems from Spain 1st Edition David Goldstein

https://ebookname.com/product/hebrew-poems-from-spain-1st-
edition-david-goldstein/
Comprehensive handbook of clinical health psychology
1st Edition Bret A. Boyer

https://ebookname.com/product/comprehensive-handbook-of-clinical-
health-psychology-1st-edition-bret-a-boyer/
Java
Methods
A & AB
Object-Oriented Programming
and
Data Structures

Maria Litvin
Phillips Academy, Andover, Massachusetts

Gary Litvin
Skylight Software, Inc.

Skylight Publishing
Andover, Massachusetts
Skylight Publishing
9 Bartlet Street, Suite 70
Andover, MA 01810

web: http://www.skylit.com
e-mail: [email protected]
[email protected]

Copyright © 2006 by Maria Litvin, Gary Litvin, and


Skylight Publishing

All rights reserved. No part of this publication may be reproduced,


stored in a retrieval system, or transmitted, in any form or by any means,
electronic, mechanical, photocopying, recording, or otherwise, without
the prior written permission of the authors and Skylight Publishing.

Library of Congress Control Number: 2005910949

ISBN 978-0-9727055-7-8

The names of commercially available software and products mentioned in this book are
used for identification purposes only and may be trademarks or registered trademarks
owned by corporations and other commercial entities. Skylight Publishing and the authors
have no affiliation with and disclaim any sponsorship or endorsement by any of these
products’ manufacturers or trademarks’ owners.

Sun, Sun Microsystems, Java, and Java logos are trademarks or registered trademarks of
Sun Microsystems, Inc. in the United States and other countries.

SCRABBLE® is the registered trademark of HASBRO in the United States and Canada and
of J.W. Spear and Sons, PLC, a subsidiary of Mattel, Inc., outside the United States and
Canada.

1 2 3 4 5 6 7 8 9 10 11 10 09 08 07 06

Printed in the United States of America


To Marg and Aaron
Brief Contents

Preface
How to Use This Book
Chapter 1 An Introduction to Hardware, Software, and the Internet
Chapter 2 An Introduction to Software Development
Chapter 3 Objects and Classes
Chapter 4 Algorithms
Chapter 5 Java Syntax and Style
Chapter 6 Data Types, Variables, and Arithmetic
Chapter 7 Boolean Expressions and if-else Statements
Chapter 8 Iterative Statements: while, for, do–while
Chapter 9 Implementing Classes and Using Objects
Chapter 10 Strings
Chapter 11 Class Hierarchies and Interfaces
Chapter 12 Arrays and ArrayLists
Chapter 13 Searching and Sorting
Chapter 14 Streams and Files
Chapter 15 Graphics
Chapter 16 GUI Components and Events
Chapter 17 Mouse, Keyboard, Sounds, and Images
Chapter 18 Big-O Analysis of Algorithms
Chapter 19 The Java Collections Framework
Chapter 20 Linked Lists
Chapter 21 Stacks and Queues
Continued

Draft. Copyright © 2006 by Skylight Publishing.


Chapter 22 Recursion Revisited
Chapter 23 Binary Trees
Chapter 24 Lookup Tables and Hashing
Chapter 25 Priority Queues
Chapter 26 Design Patterns
Appendix A The 17 Bits of Style
Appendix B Common Syntax Error Messages
Appendix C HTML Tutorial
Appendix D GUI Examples Index
Appendix E The EasyReader, EasyWriter, EasySound, EasyDate,
and EasyFormat Classes
Appendix F Computing in Context: Responsible, Ethical, and Effective
Computer Use
Index

Draft. Copyright © 2006 by Skylight Publishing.


Contents

Preface xvii

How to Use This Book xxi

Chapter 1. An Introduction to Hardware, Software, and the Internet 1


1.1 Prologue
1.2 Hardware Overview
1.2.1 The CPU
1.2.2 Memory
1.2.3 Secondary Storage Devices
1.2.4 Input and Output Devices
1.3 Software Overview
1.4 Representation of Information in Computer Memory
1.4.1 Numbers
1.4.2 Characters
1.5 The Internet
1.6 Summary
Exercises

Chapter 2. An Introduction to Software Development


2.1 Prologue
2.2 Compilers and Interpreters
2.3 Software Components and Packages
2.4 Lab: Three Ways to Say Hello
2.5 Object-Oriented Programming
2.6 Lab: More Ways to Say Hello
2.7 Summary
Exercises

Draft. Copyright © 2006 by Skylight Publishing.


viii CONTENTS

Chapter 3. Objects and Classes


3.1 Prologue
3.2 Case Study: First Steps
3.3 Classes
3.4 Fields, Constructors, and Methods
3.5 Case Study: First Steps Continued
3.6 Inheritance
3.7 Summary
Exercises

Chapter 4. Algorithms
4.1 Prologue
4.2 Properties of Algorithms
4.3 Iterations
4.4 Recursion
4.5 Case Study: Euclid’s GCF Algorithm
4.6 Working with Lists
4.7 Case Study: File Manager
4.8 Summary
Exercises

Chapter 5. Java Syntax and Style


5.1 Prologue
5.2 Using Comments
5.3 Reserved Words and Programmer-Defined Names
5.4 Syntax vs. Style
5.5 Statements, Blocks, Indentation
5.6 Lab: Correcting Syntax Errors
5.7 Summary
Exercises

Draft. Copyright © 2006 by Skylight Publishing.


CONTENTS ix

Chapter 6. Data Types, Variables, and Arithmetic


6.1 Prologue
6.2 Declaring Fields and Local Variables
6.3 Primitive Data Types
6.4 Strings
6.5 Constants
6.6 Scope of Variables
6.7 Arithmetic Expressions
6.8 Compound Assignment and Increment Operators
6.9 Converting Numbers and Objects into Strings
6.10 Lab: Pie Chart
6.11 Summary
Exercises

Chapter 7. Boolean Expressions and if-else Statements


7.1 Prologue
7.2 if–else Statements
7.3 boolean Data Type
7.4 Relational Operators
7.5 Logical Operators
7.6 Order of Operators
7.7 Short-Circuit Evaluation
7.8 if–else–if and Nested if–else
7.9 Case Study and Lab: Rolling Dice
7.10 The switch statement
7.11 Enumerated Data Types
7.12 Case Study and Lab: Rolling Dice Continued
7.13 Summary
Exercises

Chapter 8. Iterative Statements: while, for, do-while


8.1 Prologue
8.2 The while and for Loops
8.3 The do–while Loop
8.4 return and break in Loops
8.5 Nested Loops
8.6 Lab: Perfect Numbers
8.7 Summary
Exercises

Draft. Copyright © 2006 by Skylight Publishing.


x CONTENTS

Chapter 9. Implementing Classes and Using Objects


9.1 Prologue
9.2 Public and Private Features of a Class
9.3 Constructors
9.4 References to Objects
9.5 Defining Methods
9.6 Calling Methods and Accessing Fields
9.7 Passing Parameters to Constructors and Methods
9.8 return Statement
9.9 Case Study and Lab: Snack Bar
9.10 Overloaded Methods
9.11 Static Fields and Methods
9.12 Case Study and Lab: Snack Bar Continued
9.13 Summary
Exercises

Chapter 10. Strings


10.1 Prologue
10.2 Literal Strings
10.3 String Constructors and Immutability
10.4 String Methods
10.5 Converting Numbers into Strings and Strings into Numbers
10.6 Character Methods
10.7 Lab: Lipogrammer
10.8 The StringBuffer Class
10.9 Summary
Exercises

Chapter 11. Class Hierarchies and Interfaces


11.1 Prologue
11.2 Class Hierarchies and Polymorphism
11.3 Abstract Classes
11.4 Invoking Superclass’s Constructors
11.5 Calling Superclass’s Methods
11.6 Case Study: Dance Studio
11.7 Interfaces
11.8 Case Study: Dance Studio Continued
11.9 Summary
Exercises

Draft. Copyright © 2006 by Skylight Publishing.


CONTENTS xi

Chapter 12. Arrays and ArrayLists


12.1 Prologue
12.2 One-Dimensional Arrays
12.3 Lab: Fortune Teller
12.4 The ArrayList Class
12.5 ArrayList’s Constructors and Methods
12.6 ArrayList’s Pitfalls
12.7 Iterations and the “For Each” Loop
12.8 Inserting and Removing Elements
12.9 Lab: Creating an Index for a Document
12.10 Two-Dimensional Arrays
12.11 Case Study and Lab: Chomp
12.12 Summary
Exercises

Chapter 13. Searching and Sorting


13.1 Prologue
13.2 equals, compareTo, and compare
13.3 Sequential and Binary Search
13.4 Lab: Keeping Things in Order
13.5 Selection Sort
13.6 Insertion Sort
13.7 Mergesort
13.8 Quicksort
13.9 Lab: Benchmarks
13.10 The Arrays and Collections Classes
13.11 Summary
Exercises

Chapter 14. Streams and Files


14.1 Prologue
14.2 Pathnames and the java.io.File Class
14.3 Reading from a Text File
14.4 Writing to a Text File
14.5 Lab: Dictionary Maker
14.6 Summary
Exercises

Draft. Copyright © 2006 by Skylight Publishing.


xii CONTENTS

Chapter 15. Graphics


15.1 Prologue
15.2 paint, paintComponent, and repaint
15.3 Coordinates
15.4 Colors
15.5 Drawing Shapes
15.6 Fonts and Text
15.7 Case Study and Lab: Pieces of the Puzzle
15.8 Summary
Exercises

Chapter 16. GUI Components and Events


16.1 Prologue
16.2 Pluggable Look and Feel
16.3 Basic Swing Components and Their Events
16.4 Case Study and Lab: Speed Control
16.5 Pull-Down Menus
16.6 Layouts
16.7 Summary
Exercises

Chapter 17. Mouse, Keyboard, Sounds, and Images


17.1 Prologue
17.2 Mouse Events Handling
17.3 Keyboard Events Handling
17.4 Case Study and Lab: Drawing Editor
17.5 Lab: Cursor Keys
17.6 Sounds and Images
17.7 Summary
Exercises

Chapter 18. Big-O Analysis of Algorithms


18.1 Prologue
18.2 Big-O Notation
18.3 Sorting: a Big-O Review
18.4 Summary
Exercises

Draft. Copyright © 2006 by Skylight Publishing.


CONTENTS xiii

Chapter 19. The Java Collections Framework


19.1 Prologue
19.2 Collection<E> and Iterator<E>
19.3 Lists and ListIterator<E>
19.4 Stacks
19.5 Queues
19.6 Priority Queues
19.7 Sets
19.8 Maps
19.9 Case Study and Lab: Stock Exchange
19.10 Summary
Exercises

Chapter 20. Lists and Iterators


20.1 Prologue
20.2 Singly-Linked List
20.3 Traversals
20.4 Lab: Implementing a Singly-Linked List
20.5 Linked List with a Tail
20.6 Doubly-Linked List and Circular List
20.7 Lab: Teletext
20.8 Summary
Exercises

Chapter 21. Stacks and Queues


21.1 Prologue
21.2 Implementations of Stacks
21.3 Lab: Browsing
21.4 The Hardware Stack
21.5 Implementations of Queues
21.6 Case Study and Lab: Actors World
21.7 Summary
Exercises

Draft. Copyright © 2006 by Skylight Publishing.


xiv CONTENTS

Chapter 22. Recursion Revisited


22.1 Prologue
22.2 Three Examples
22.3 When Not to Use Recursion
22.4 Understanding and Debugging Recursive Methods
22.5 Lab: The Tower of Hanoi
22.6 Case Study and Lab: The Game of Hex
22.7 Summary
Exercises

Chapter 23. Binary Trees


23.1 Prologue
23.2 Implementation of Binary Trees
23.3 Traversals
23.4 Binary Search Trees
23.5 Lab: Morse Code
23.6 Case Study and Lab: Java Messenger
23.7 Summary
Exercises

Chapter 24. Lookup Tables and Hashing


24.1 Prologue
24.2 Lookup Tables
24.3 Lab: Cryptogram Solver
24.4 Hash Tables
24.5 java.util’s HashSet and HashMap
24.6 Lab: Search Engine
24.7 Summary
Exercises

Chapter 25. Heaps and Priority Queues


25.1 Prologue
25.2 Implementations of Priority Queues
25.3 Binary Trees: Non-Linked Representation
25.4 Heaps and Priority Queues
25.5 Lab: Heapsort
25.6 Summary
Exercises

Draft. Copyright © 2006 by Skylight Publishing.


CONTENTS xv

Chapter 26. Design Patterns


26.1 Prologue
26.2 Façade
26.3 Strategy
26.4 Singleton
26.5 Decorator
26.6 Composite
26.7 MVC (Model-View-Controller)
26.8 Summary
Exercises

Appendix A: The 17 Bits of Style


Appendix B: Common Syntax Error Messages
Appendix C: HTML Tutorial
Appendix D: GUI Examples Index
Appendix E: The EasyReader, EasyWriter, EasySound,
EasyDate, and EasyFormat Classes
Appendix F: Computing in Context: Responsible and Ethical
Computer Use

Index

Draft. Copyright © 2006 by Skylight Publishing.


xvi CONTENTS

Draft. Copyright © 2006 by Skylight Publishing.


Preface

This book offers a comprehensive introduction to the concepts and practices of


object-oriented programming in Java. It also introduces the most common data
structures and related algorithms and their implementations in the Java collections
framework. As the title implies, the book covers the material in the A- and AB-level
AP Computer Science course syllabus. This is equivalent to a two- or three-semester
college course sequence in introductory programming and data structures for
computer science majors. In addition to covering the AP curriculum in depth, we
introduce several topics that are not required for the AP exams, including file input
and output, graphics, graphical user interfaces, events handling in Java, and design
patterns. This additional material gives students a better sense of real-world Java
programming and enables them to undertake more realistic and engaging exercises
and labs.

This edition builds on our earlier books, Java Methods: An Introduction to Object-
Oriented Programming (Skylight Publishing, 2001) and Java Methods AB: Data
Structures (Skylight Publishing, 2003). In this edition we have organized all of the
material into one volume. Besides an upgrade to Java 5.0, we have made many
substantial changes that reflect the current thinking about object-oriented
programming (OOP) among computer science educators and professionals. We have
revised the sequence of topics for an earlier introduction of inheritance, class
hierarchies, interfaces, and polymorphism; enhanced the discussion of object-
oriented design; introduced new case studies and labs and updated and streamlined
those we decided to keep from the previous edition; recast almost all examples from
applets into applications; added a separate chapter on the Java collections framework;
and so on.

The book follows four main threads: OOP concepts and techniques, algorithms, Java
syntax and style, and Java libraries. As in the software engineering profession itself,
these threads are interwoven into an inseparable braid.

Our book strives to present the technical details while grounding them in clear
explanations of the underlying concepts. OOP has an extensive conceptual layer and
complex terminology. Fortunately, many OOP concepts are more straightforward
than the terminology makes them appear. The notions of objects (entities that
combine data elements and functions), classes (definitions of types of objects),
methods (functions that handle certain tasks), instantiation (creating an object of a
particular class), inheritance (one class extending the features of another class),

Draft. Copyright © 2006 by Skylight Publishing.


xviii PREFACE

encapsulation (hiding the implementation details of a class), polymorphism (calling


the correct methods automatically for specific objects disguised as more generic
types), and event-driven applications (where the operating system, the user, or events
in the program trigger certain actions) are actually quite intuitive.

We also emphasize good programming style, an element not mandated by formal


Java language specifications but essential for writing readable and professional
programs.

Our labs and case studies aim to demonstrate the most appropriate uses of the
programming techniques and data structures we cover. OOP is widely believed to
facilitate team work, software maintenance, and software reuse. While it is not
possible for an introductory textbook to present a large-scale real-world project as a
case study, the case studies and labs in this book offer a taste of how these OOP
benefits can play out in larger projects.

We assume that at least two or three class periods each week will be held in a
computer lab with students working independently or in small groups. The Student
“disk” (a zip file downloadable from the book’s web site) contains files for all the
case studies, labs, and exercises in the book; the Teacher’s “disk,” available to
teachers, provides complete solutions to all the labs and exercises.

Still, with all the examples and case studies, we leave a lot of work to you, the
student. This is not a Java-in-n-days book or an n-hours-to-complete book. It is a
book for learning essential concepts and technical skills at a comfortable pace, for
acquiring a repertoire of techniques and examples to work from, and for consulting
once in a while when you start writing your own Java programs professionally or for
fun.

Working through this book will not make you a Java expert right away — but it will
bring you to the level of an entry-level Java programmer with a better than average
understanding of the fundamental concepts. Object-oriented programming was
invented to make software development more accessible to beginners, and Java
Methods A & AB is written in that spirit.

Our sincere thanks to...

Our special thanks to Margaret Litvin for her thorough and thoughtful editing.

Without further delay, let us begin learning object-oriented programming in Java!

Draft. Copyright © 2006 by Skylight Publishing.


PREFACE xix

Draft. Copyright © 2006 by Skylight Publishing.


xx PREFACE

About the Authors

Maria Litvin has taught computer science and mathematics at Phillips Academy
in Andover, Massachusetts, since 1987. She is an Advanced Placement Computer
Science exam reader and question leader and, as a consultant for The College Board,
provides AP training for high school computer science teachers. Maria is a recipient
of the 1999 Siemens Award for Advanced Placement for Mathematics, Science, and
Technology for New England and of the 2003 RadioShack National Teacher Award.
Prior to joining Phillips Academy, Maria taught computer science at Boston
University. Maria is a co-author of C++ for You++: An Introduction to
Programming and Computer Science, which became one of the leading high school
textbooks for AP Computer Science courses, and of the earlier editions of Java
Methods and Java Methods AB. Maria is also the author of Be Prepared for the AP
Computer Science Exam in Java.

Gary Litvin is a co-author of C++ for You++, Java Methods, and Java Methods
AB and a contributor to the 2006 edition of Be Prepared for the AP Computer
Science Exam in Java. Gary has worked in many areas of software development
including artificial intelligence, pattern recognition, computer graphics, and neural
networks. As founder of Skylight Software, Inc., he developed SKYLIGHTS/GX,
one of the first visual programming tools for C and C++ programmers. Gary led in
the development of several state-of-the-art software products including interactive
touch screen development tools, OCR and handwritten character recognition systems,
and credit card fraud detection software.

Draft. Copyright © 2006 by Skylight Publishing.


How to Use This Book

The Java Methods A & AB companion web site —

http://www.skylit.com/javamethods

— is an integral part of this book. It contains four chapters and several appendices.
It also has a downloadable Student “disk” with all the student files for case studies,
labs, and exercises. Also on the book’s web site are “footnotes,” web links, errata,
supplemental papers, and syllabi and technical support information for teachers.

We have chosen to place Chapters 1, 14, 16, and 17 and the appendices on the web
either because they rely on many web links or because the material they cover is less
theoretical and handy to have online for reference.

The web symbol indicates a “footnote” that is on the book’s web site in the
alphabetical list of “footnote” links.

JM refers to the Java Methods student disk. For example, “you can find
HelloWorld.java in JM\Ch02\Hello” means the HelloWorld.java
file is located in the Ch02\Hello folder on your student disk.

This icon draws your attention to a lab exercise or a hands-on exploration of


an example.

“Parentheses” like these, in the margin, mark supplementary material


intended for a more inquisitive reader. This material either gives a glimpse
of things to come in subsequent chapters or adds technical details.

1. , 2. In exercises, a square indicates an “intermediate” question that may require


more thought or work than an ordinary question or exercise. A diamond
indicates an “advanced” question that could be treacherous or lead to
unexplored territory — proceed at your own risk.

A checkmark at the end of a question in an exercise means that a solution is


included on your student disk. We have included solutions to about one-
third of the exercises. They can be found in JM\SolutionsToExercises
(click on index.html).

Draft. Copyright © 2006 by Skylight Publishing.


xxii HOW TO USE THIS BOOK

A Teacher’s “disk” with complete solutions to all the exercises and labs is available
for downloading free of charge to teachers who use this book as a textbook in their
schools (click on the “Teachers’ Room” link at skylit.com/javamethods for
details).

(To a slightly different subject...)

How you use this book will depend on your background in computers. If you are
familiar with computers and programming, you can glance quickly at Chapters 1 and
2 to see whether they fill any gaps. Chapters 3 (Objects and Classes), 4
(Algorithms), and 5 (Java Syntax and Style) can be covered in any order, depending
on your taste. If you know C++, Chapters 6, 7, and 8 will be easy for you. But do
still look at them for the sake of the case studies and labs, which cover broader
concepts than the chapter headings imply. Chapters 14 (Streams and Files), 15
(Graphics), 16 (GUI Components and Events), and 17 (Mouse, Keyboard, Sounds,
and Images) are optional as far as the AP exams are concerned. Chapter 18 begins
the discussion of more advanced “AB” topics: big-O, the Java collections framework,
and data structures. The concluding chapter, Design Patterns, broadens the horizon,
but it is optional, too.

Draft. Copyright © 2006 by Skylight Publishing.


ch 001
1 An Introduction to Hardware,
Software, and the Internet
1.1 Prologue 2
1.2 Hardware Overview
1.2.1 The CPU
1.2.2 Memory
1.2.3 Secondary Storage Devices
1.2.4 Input and Output Devices
1.3 Software Overview
1.4 What Do Programmers Do?
1.5 Representation of Information in Computer Memory
1.4.1 Numbers
1.4.2 Characters
1.6 The Internet
1.7 Summary
Exercises 5

Draft. Copyright © 2006 by Skylight Publishing.


2 CHAPTER 1 ~ AN INTRODUCTION TO HARDWARE, SOFTWARE, AND THE INTERNET

1.1 Prologue
Have you ever opened that inconspicuous gray or black (or purple) box sitting on or
beside your desk, with tangled wires snaking out of it in all directions? If you do,
you might find a mostly empty box, with a power supply, a printed circuit board on
the bottom connected by tape cables to a small disk drive and a couple of other
devices neatly tucked away in their bays. And that’s all. But it brings you an entire
world.

The most important piece of a typical computer is the Central Processing Unit or
CPU. In a personal computer, the CPU is a microprocessor made from a tiny chip of
silicon, sometimes as small as half an inch square. Immensely precise manufacturing
processes etch a huge number of semiconductor devices, called transistors, into the
silicon wafer. Each transistor is a microscopic digital switch and together they
control, with almost perfect precision, billions of signals — little spikes of electricity
— that arise and disappear every second. The size of the spikes doesn’t matter, only
their presence or absence. The transistors in the CPU recognize only two states of a
signal, “on” or “off,” “high” or “low,” “1” or “0,” “true” or “false.” This is called
digital electronics, as opposed to analog electronics where the actual amplitudes of
signals carry information.

The transistors on a chip combine to form logical devices called gates. Gates
implement Boolean operations (named after the British mathematician George Boole,
1815-1864, boole who studied the properties of logical relations). For example, an
AND gate takes two inputs and combines them into one output signal. The output is
set to “true” if both the first and the second input are “true,” and to “false” otherwise
(Figure 1-1 (a)). In an OR gate, the output is set to “true” if either the first or the
second (or both) inputs are true (Figure 1-1 (b)). A NOT gate takes one input and
sets the output to its opposite (Figure 1-1 (c)). Note the special shapes used to denote
each type of gate.

These three basic types of gates can be combined to make other Boolean operations
and logical circuits. Figure 1-2, for example, shows how you can combine AND, OR
and NOT gates to make an XOR (“eXclusive OR”) operation. This operation sets the
output to “true” if exactly one of its two inputs is “true.” In the late 1940s, John von
Neumann, neumann a great mathematician and one of the founding fathers of computer
technology, showed that all arithmetic operations can be reduced to AND, OR, and
NOT logical operations.

Draft. Copyright © 2006 by Skylight Publishing.


CHAPTER 1 ~ AN INTRODUCTION TO HARDWARE, SOFTWARE, AND THE INTERNET 3

A A
A AND B A OR B A NOT A
B B

A B A AND B A B A OR B A NOT A
T T T T T T T F
T F F T F T F T
F T F F T T
F F F F F F

(a) (b) (c)


AND gate OR gate NOT gate

Figure 1-1. AND, OR, and NOT gates

B °
A XOR B

°
A B A XOR B
T T F
T F T
F T T
F F F

Figure 1-2. XOR circuit made of AND, OR and NOT gates

The microprocessor is protected by a small ceramic case mounted on a PC board


(Printed Circuit board) called the motherboard. Also on the motherboard are
memory chips. The computer memory is a uniform pool of storage units called bits.
A bit stores the smallest possible unit of information: “on” or “off,” “1” or “0.” For
practical reasons, bits are grouped into groups of eight, called bytes.

Draft. Copyright © 2006 by Skylight Publishing.


4 CHAPTER 1 ~ AN INTRODUCTION TO HARDWARE, SOFTWARE, AND THE INTERNET

One byte is eight bits.

There is no other structure to memory: the same memory is used to store numbers
and letters and sounds and images and programs. All these things must be encoded,
one way or another, in sequences of 0s and 1s. A typical personal computer made in
the year 2005 had 256 “megs” (megabytes; 1 megabyte is 1,048,576 bytes) to 1 “gig”
(gigabyte; 1 gigabte is 1,024 megabytes) of RAM (Random-Access Memory) packed
in a few SIMMs (Single In-Line Memory Modules).

The CPU interprets and carries out computer programs, or sequences of instructions
stored in the memory. The CPU fetches the next instruction, interprets its operation
code, and performs the appropriate operation. There are instructions for arithmetic
and logical operations, for copying bytes from one location to another, and for
changing the order of execution of instructions. The instructions are executed in
sequence unless a particular instruction tells the CPU to “jump” to another place in
the program. Conditional branching instructions tell the CPU to continue with the
next instruction or jump to another place depending on the result of the previous
operation.

Besides the CPU, a general-purpose computer system also includes peripheral


devices that provide input and output and secondary mass storage. In a notebook
(laptop) computer, the “peripheral” devices are no longer quite so peripheral: a
keyboard, a display, a hard drive, a CD-ROM or DVD drive, a fax/modem, a touch
pad, a microphone, and speakers are all built into one portable unit.

CPU, memory, peripherals — all of this is called hardware. It is a lot of power


concentrated in a small device. But to make it useful, to bring life into it, you need
programs, software. Computer programs are also miracles of engineering, but of a
different kind: software engineering. They are not cast in iron, nor even silicon, but
in intangible texts that can be analyzed, modified, translated from one computer
language into another, copied into various media, transmitted over networks, or lost
forever. Software is to a computer as tunes are to a band: the best musicians will be
silent if they haven’t got music to play.

Take this amazing device with its software and connect it to the Internet, a network
of millions of computers of all kinds connected to each other via communication
lines of all kinds and running programs of all kinds, and you end up with a whole
new world. Welcome to cyberspace!

In the rest of this chapter we will briefly discuss

Draft. Copyright © 2006 by Skylight Publishing.


CHAPTER 1 ~ AN INTRODUCTION TO HARDWARE, SOFTWARE, AND THE INTERNET 5

• The main hardware components: CPU, memory, peripheral devices


• What software is
• How numbers and characters are represented in computer memory
• What the Internet is

1.2 - 1.7
These sections are online at http://www.skylit.com/javamethods.

Exercises
1. Mark T (true) or F (false) the output of each of the following circuits with the
given inputs.

T F
F T °
(a) (b)

T
°
T
°
(c)

2. Let’s say that two circuits are equivalent if they produce the same outputs for
the same inputs. Draw a circuit equivalent to the one in Question 1.1-(b)
using two NOT gates and one AND gate.

3. Simplify the circuit in Question 1.1-(c) to an equivalent one that has only two
gates: one NOT gate and one AND gate.

Draft. Copyright © 2006 by Skylight Publishing.


6 CHAPTER 1 ~ AN INTRODUCTION TO HARDWARE, SOFTWARE, AND THE INTERNET

4. (a) Draw an alternative XOR circuit, different from the one in Figure 1-2,
using two NOT gates, two OR gates, and one AND gate. Hint: at
least one of the inputs, A OR B, must be true, AND at least one of the
negated inputs, NOT A OR NOT B, must be true, too.

(b) Draw a third XOR circuit using four gates: one OR gate, two AND
gates, and one NOT gate.

5. Computer memory is called RAM because:

A. It provides rapid access to data.


B. It is mounted on the motherboard.
C. It is measured in megabytes.
D. Its bytes can be addressed in random order.
E. Its chips are mounted in a rectangular array.

6. Mark true or false and explain:

(a) One meg of RAM can hold exactly as much information as one meg on
a floppy disk. _____

(b) A factory-formatted floppy disk is split into a fixed number of files.


_____

(c) In personal computers the operating system resides in ROM. _____

7. Find an old discarded computer, unplug the power cord and disconnect all
other cables. Open the cover and identify the motherboard, CPU, RAM,
serial and parallel ports (sockets for cable connectors), hard disk, CD-ROM,
and other components and adapters, if present.

8. Identify the following entities or devices as part of a computer system’s


hardware (H) or software (S).

(a) Operating system ______


(b) CPU ______
(c) GUI (Graphical User Interface) ______
(d) Modem ______
(e) Bus ______
(f) RAM ______
(g) File ______

Draft. Copyright © 2006 by Skylight Publishing.


CHAPTER 1 ~ AN INTRODUCTION TO HARDWARE, SOFTWARE, AND THE INTERNET 7

9. Identify the operating system that is running on your current computer and
some software applications installed on it: a word processor, an Internet
browser, a spreadsheet program, e-mail, an image processing application,
games, and so on.

10. Mark true or false and explain:

(a) Only data but not CPU instructions can be stored in RAM. _____

(b) In ASCII code each character is represented in one byte. _____

(c) 16-bit binary numbers can be used to represent all non-negative


integers from 0 to 216-1. ______

(d) Programs stored in ROM are referred to as “firmware.” _____

11. What is the maximum number of different codes or numbers that can be
represented in

(a) 3 bits? ______


(b) 8 bits? ______
(c) 2 bytes? ______

12. Assume that these binary numbers represent unsigned integers in the usual
way, with the least significant bit on the right. Write the decimal value and
the hex representation of these binary numbers. Example:

Binary Decimal Hex

00001000 8 08
00011100 28 1C

(a) 00000010 _______ _______


(b) 00000111 _______ _______
(c) 10000000 _______ _______
(d) 00001011 _______ _______
(e) 11000011 _______ _______
(f) 11110101 _______ _______

(g) 00000101 10010010


_______ _______

Draft. Copyright © 2006 by Skylight Publishing.


8 CHAPTER 1 ~ AN INTRODUCTION TO HARDWARE, SOFTWARE, AND THE INTERNET

13. An experiment consists of tossing a coin 10 times and its outcome is a


sequence of heads and tails. How many possible outcomes are there?

14. How much memory does it take to hold a 512-by-512 gray-scale image with
256 levels of gray?

15. When a printer runs out of paper, the eight-bit printer status register of the
parallel interface adapter gets the following settings: bit 7 (leftmost bit),
"BUSY," is set to 1; bit 5, "PE" ("paper end"), is set to 1; and bit 3,
"ERROR," is set to 0. Bit 4 is always 1 when a printer is connected, bit 6 is
0, and bits 0-2 are not used. Write the hex value equal to the setting of the
printer status register when the printer runs out of paper, assuming that bits
0-2 are 0.

16. Design a method for representing the state of a tic-tac-toe board in computer
memory. Can you fit your representation into three bytes?

17. In the game of Nim, stones are arranged in piles of arbitrary size. Each
player in turn takes a few stones from any one pile. Every player must take
at least one stone on every turn. The player who takes the last stone wins.

Games of this type often have a winning strategy. This strategy can be
established by tagging all possible positions in the game with two tags,
“plus” and “minus,” in such a way that any move from a “plus” position
always leads to a “minus” position, and from any “minus” position there is
always a possible move into some “plus” position. The final winning
position must be tagged “plus.” Therefore, if the first player begins in a
“minus” position, she can win by moving right away into a “plus” position
and returning to a “plus” position on each subsequent move. If, however, the
first player begins in a “plus” position, then the second player can win,
provided he knows how to play correctly.

In the Nim game, we can convert the number of stones in each pile into a
binary number and write these binary numbers in one column (so that the
“units” digits are aligned on the right). We can tag the position “plus” if the
number of 1’s in each column is even and “minus” if the count of 1’s in at
least one column is odd. Prove that this method of tagging “plus” and
“minus” positions defines a winning strategy. Who wins starting with four
piles of 1, 3, 5, and 7 stones — the first or the second player? What’s the
correct response if the first player takes five stones from the pile of 7?

Draft. Copyright © 2006 by Skylight Publishing.


CHAPTER 1 ~ AN INTRODUCTION TO HARDWARE, SOFTWARE, AND THE INTERNET 9

18. The table below is called a Greco-Roman square: each of the three Latin
letters occurs exactly once in each row and each column; the same is true for
each of the three Greek letters; and each Latin-Greek combination occurs
exactly once in the table:

Aγ Bα Cβ
Bβ Cγ Aα
Cα Aβ Bγ

Substitute the digits 0, 1 and 2 for A, B, C and for α, β, γ (in any order).
Convert the resulting base-3 numbers into decimal (base-10) numbers. The
base-3 system uses only three digits: 0, 1, and 2. The numbers are
represented as follows:

Decimal Base 3
0 0
1 1
2 2
3 10
4 11
5 12
6 20
7 21
8 22
9 100
... ...

Add 1 to each number. You will get a table in which the numbers 1 through
9 are arranged in such a way that the sum of the numbers in each row and
column is the same. Explain why you get this result and find a way to
substitute the digits 0, 1, and 2 for letters so that the sum of numbers in each
of the two diagonals is also the same as in the rows and columns. What you
get then is called a magic square. Using a similar method, build a 5 by 5
magic square.

Draft. Copyright © 2006 by Skylight Publishing.


10 CHAPTER 1 ~ AN INTRODUCTION TO HARDWARE, SOFTWARE, AND THE INTERNET

19. (a) Write the ASCII codes for the following characters in decimal, hex and
binary:

Decimal Hex Binary


'A' _______ ______ _________
'a' _______ ______ _________
'Z' _______ ______ _________
'z' _______ ______ _________

(b) Note that the binary representations of the ASCII codes for the lower
and upper case of the same letter differ in only one bit. Write the
binary and hex representations of a byte where that bit is set to 1 and
all other bits are set to 0.

20. What does TCP stand for?

A. Telnet Control Program


B. Transmission Control Protocol
C. Transport Compression Protocol
D. Telephone Connectivity Program
E. None of the above

21. Are the following entities or devices hardware (H) or software (S)?

(a) Host ______


(b) LAN ______
(c) Browser ______
(d) Search engine ______
(e) Router ______
(f) TCP/IP Adapter ______

22. Find and explore the home pages of some Internet and World Wide Web
pioneers.

Draft. Copyright © 2006 by Skylight Publishing.


Chapter 2

2 An Introduction to Software
Development
2.1 Prologue 2
2.2 Compilers and Interpreters 4
2.3 Software Components and Packages 10
2.4 Lab: Three Ways to Say Hello 12
2.5 Object-Oriented Programming 18
2.6 Lab: More Ways to Say Hello 21
2.7 Summary 28
Exercises 29

Draft. Copyright © 2006 by Skylight Publishing.


2 CHAPTER 2 ~ AN INTRODUCTION TO SOFTWARE DEVELOPMENT

2.1 Prologue
One of the first computers, ENIAC, eniac developed in 1942-1946 primarily for
military applications, was programmed by people actually connecting hundreds of
wires to sockets (Figure 2-1) — hardly a “software development” activity as we
know it. (ENIAC occupied a huge room, had 18,000 vacuum tubes, and could
perform 300 multiplications per second.) In 1946, John von Neumann developed the
idea that a computer program can be stored in the computer memory itself in the
form of encoded CPU instructions, together with the data on which the program
operates. Then the modern computer was born: a “universal, digital, program-stored”
computer that can perform calculations and process information.

Figure 2-1. Two technicians wiring the right side of ENIAC


(Courtesy of U. S. Army Research Laboratory)

Once program-stored computers were developed, it made sense to talk about


programs as “written.” In fact, at the beginning of the computer era, programmers
wrote programs in pencil on special forms; then technicians punched the programs
into punch cards or perforated tape. A programmer entering a computer room with a
deck of punch cards was a common sight. Fairly large programs were written
entirely in machine code using octal or hexadecimal instruction codes and memory
addresses. It is no coincidence that the same word, “coding,” is used for writing
programs and encrypting texts. Programmers were often simply mathematicians,
electrical engineers, or scientists who learned the skill on their own when they

Draft. Copyright © 2006 by Skylight Publishing.


CHAPTER 2 ~ AN INTRODUCTION TO SOFTWARE DEVELOPMENT 3

needed to use a computer for their work.

In those days computers and “computer time” (that is, the time available for running
programs) were very expensive, much more expensive than a programmer’s time,
and the high computer costs defined the rules of the game. For instance, only fairly
important computer applications could be considered, such as military and scientific
computations, large information systems, and so on. Programmers strove to make
their programs run faster by developing efficient algorithms (the concept of an
algorithm is described in Chapter <…>). Often one or two programmers wrote the
entire program and knew all about it, while no one else could understand it.
Computer users were happy just to have access to a computer and were willing to
learn cryptic instructions and formats for using programs.

Now, when computers are so inexpensive that they have become a household
appliance, while programmers are relatively scarce and expensive, the rules of the
game have changed completely. This change affects which programs are written,
how they are created, and even the name by which programmers prefer to be called
— “software engineers.” There is still a need, of course, for understanding and
optimizing algorithms. But the emphasis has shifted to programmers’ productivity,
professionalism, and teamwork — which requires using standard programming
languages, tools, and software components.

Software applications that run on a desktop computer are loaded with features and
must be very interactive and “user-friendly,” (that is, have an intuitive and fairly
conventional user interface). They must also be portable (i.e., able to run on
different computer systems) and internationalized (that is, easily adaptable for
different languages and local conventions). Since a large team may work on the
same software project, it is very important that teams follow standard development
methodologies, and that the resulting programs be understandable to others and well
documented. Thus software engineering has become as professionalized as other
engineering disciplines: there is a lot of emphasis on knowing and using professional
tools in a team environment, and virtually no room for solo wizardry.

A typical fairly large software project may include the following tasks:

• Interaction with customers, understanding customer needs, refining and


formalizing specifications
• General design (defining a software product’s parts, their functions and
interactions)
• Detailed design (defining objects, functions, algorithms, file layouts, etc.)
• Design/prototyping of the user interface (designing screen layouts, menus,
dialog boxes, online help, reports, messages, etc.)

Draft. Copyright © 2006 by Skylight Publishing.


4 CHAPTER 2 ~ AN INTRODUCTION TO SOFTWARE DEVELOPMENT

• Coding and debugging


• Performance analysis and code optimization
• Documentation
• Testing
• Packaging and delivery
• User technical support

(And, in the real world:

• Bug fixes, patches and workarounds, updated releases, documentation updates,


etc.)

Of course there are different levels and different kinds of software engineers, and it is
not necessary that the same person combine all the skills needed to design and
develop good software. Usually it takes a whole team of software designers,
programmers, artists, technical writers, and specialists in quality assurance (“QA”)
and technical support.

In this chapter we will first discuss general topics related to software development,
such as high-level programming languages and software development tools. We will
discuss the difference between compilers and interpreters and Java’s hybrid
compiler + interpreter approach. Then we will learn how to compile and run simple
Java applications and applets and take a first look at the concepts involved in object-
oriented programming.

2.2 Compilers and Interpreters


Computer programmers very quickly realized that the computer itself was the perfect
tool to help them write programs. The first step towards automation was made when
programmers began to use assembly languages instead of numerically coded CPU
instructions. In an assembly language, every CPU instruction has a short mnemonic
name. A programmer can give symbolic names to memory locations and can refer to
these locations by name. For example, a programmer using Intel’s 8086 assembly
language can write:

Draft. Copyright © 2006 by Skylight Publishing.


CHAPTER 2 ~ AN INTRODUCTION TO SOFTWARE DEVELOPMENT 5

index dw 0 ; "Define word" –– reserve 2 bytes


; for an integer and call it "index".
...
mov si,index ; Move the value of index into
; the SI register.
...

A special program, called the assembler, converts the text of a program written in
assembly language into the machine code expected by the CPU.

Obviously, assembly language is totally dependent on a particular CPU; porting a


program to a different type of machine would require rewriting the code. As the
power of computers increased, several high-level programming languages were
developed for writing programs in a more abstract, machine-independent way.
FORTRAN (Formula Translation Language) was defined in 1956, COBOL
(Common Business-Oriented Language) in 1960, and Pascal and C in the 1970s.
C++ gradually evolved from C in the 1980s, adding OOP (object-oriented
programming) features to C. languagehistory Java was introduced in the mid-1990s and
eventually gained popularity as a fully object-oriented programming language for
platform-independent development, in particular for programs transmitted over the
Internet. Java and OOP are of course the main subjects of this book, so we will start
looking at them in detail in the following chapters.

A program written in a high-level language obeys the very formal syntax rules of the
language. This syntax produces statements so unambiguous that even a computer
can interpret them correctly. In addition to strict syntax rules, a program follows
style conventions; these are not mandatory but make the program easier to read and
understand for fellow programmers, demonstrating its author’s professionalism.

A programmer writes the text of the program using a software program called an
editor. Unlike general-purpose word-processing programs, program editors may
have special features useful for writing programs. For example, an editor may use
colors to highlight different syntactic elements in the program or even have built-in
tools for entering standard words or expressions common in a particular
programming language.

The text of a program in a particular programming language is referred


to as source code, or simply the source. The source code is stored in a
file, called the source file.

Draft. Copyright © 2006 by Skylight Publishing.


6 CHAPTER 2 ~ AN INTRODUCTION TO SOFTWARE DEVELOPMENT

In compiled languages, such as COBOL, Pascal, or C++, a program is converted into


machine language by a special software tool called a compiler. The compiler is
specific to a particular programming language and a particular CPU. It analyzes the
source code and generates appropriate CPU instructions. The result is saved in
another file, called the object module. A large program may include several source
modules that are compiled into object modules separately. Another program, a
linker, combines all the object modules into one executable program and saves it in
an executable file (Figure 2-2).

Editor Compiler Linker

Source Object Executable


code code program

hello.cpp hello.obj hello.exe


C>hello
Hello,World!

Figure 2-2. Compiled language development cycle:


edit-compile-link-run

For a compiled language, once a program is built and tested, the executable file is
distributed to program users. The users do not need access to the program’s source
code and do not need to have a compiler.

In an alternative approach, instead of compiling, a program in a high-level language


can be interpreted by a software tool called an interpreter. The difference between a
compiler and an interpreter is subtle but important. An interpreter looks at the high-
level-language program, figures out what instructions it needs to execute, and
executes them. But it does not generate an object-code file and does not save any
compiled or executable code. It is like a live concert as opposed to a studio
recording. A user of an interpreted program needs access to the program’s source
code and an interpreter, and the program has to be interpreted again each time it is
run.

Draft. Copyright © 2006 by Skylight Publishing.


CHAPTER 2 ~ AN INTRODUCTION TO SOFTWARE DEVELOPMENT 7

To better understand the difference between a compiler and an interpreter, consider a


program that contains the statement:

R = P + Q; // set R to the sum of P and Q

A compiler, when it sees this statement, will parse the statement (analyze the
structure and extract its elements) and then generate object code according to the
following algorithm:

Generate and save an instruction that moves P into a register


Since the operation sign is '+', generate and save an
instruction that adds Q to that register
Generate and save an instruction that moves the result from that
register into R

In 8086 assembly language the resulting code could look like this:

mov ax, P ; move the value of P into the AX register


add ax, Q ; add the value of Q to the AX register
mov R, ax ; move the contents of the AX register into R

An interpreter will also parse the statement and implement a similar algorithm, but
instead of generating and saving the instructions it executes them right away:

Move P into a register


Since the operation sign is '+', add Q to that register
Move the result from the register into R

A particular programming language is usually established as either a compiled


language or an interpreted language (that is, is either more suitable or more often
used with a compiler or an interpreter), but there is really no clear-cut distinction.
BASIC, for example, was initially an interpreted language, but soon BASIC
compilers were developed. C is a compiled language, but C interpreters also exist.

Java uses a mixed compiler-plus-interpreter approach. A Java compiler first


compiles the program into bytecodes, instructions that are pretty close to a machine
language. But a machine with this machine language does not exist! It is an abstract
computer, a Java Virtual Machine (JVM)). The bytecodes are then interpreted on a
particular computer by the Java interpreter for that particular CPU. A program in
bytecodes is not object code, because it is still platform-independent (it does not use
instructions specific to a particular CPU). It is not source code, either, because it is
not readable by humans. It is something in-between.

Draft. Copyright © 2006 by Skylight Publishing.


8 CHAPTER 2 ~ AN INTRODUCTION TO SOFTWARE DEVELOPMENT

Why does Java use a combination of a compiler and an interpreter? There is no


reason why a regular Java compiler couldn’t be created for a particular type of
computer. But one of the main purposes of Java is to deliver programs to users via
the Internet. A Java-enabled browser (that is, a browser that has a Java interpreter
built into it) can run little Java programs, called applets (little “applications”). The
many applets available free on the Internet, often with their source code, are one of
the reasons why Java has become so popular so fast. When you connect to a web site
and see some action on your screen, it probably means your computer has received a
Java applet and is running it.

Java designers had to address the key question: Should users receive Java source
code or executable code? The answer they came up with was: neither. If users got
source, their browsers would need a built-in Java compiler or interpreter. That would
make browsers quite big, and compiling or interpreting on the user’s computer could
take a long time. Also, software providers may want to keep their source
confidential. But if users got executables, then web site operators would somehow
need to know what kind of computer each user had (for example, a PC or a Mac) and
deliver the right versions of programs. It would be cumbersome and expensive for
web site operators to maintain different versions of a program for every different
platform. There would also be a security risk: What if someone delivered a
malicious program to your computer?

Bytecodes provide an intermediate step, a compromise between sending source code


or executables to users (Figure 2-3). On one hand, the bytecodes’ language is
platform-independent, so the same version of bytecodes can serve users with
different types of computers. It is not readily readable by people, so it can protect the
confidentiality of the source code. On the other hand, bytecodes are much closer to
the “average” machine language, and they are easier and faster to interpret than
“raw” Java source. Also, bytecode interpreters built into browsers get a chance to
screen programs for potential security violations (for example, they can block reading
of and writing to the user’s disks).

To speed up the loading of applets, a new software technology has emerged, called
JIT (Just-In-Time) compilers. A JIT compiler combines the features of a compiler
and an interpreter. While interpreting bytecodes, it also compiles them into
executable code. (To extend our music analogy, a JIT compiler works like a
recording of a live concert.) This means an applet can be interpreted and start
running as soon as it is downloaded from the Internet. On subsequent runs of the
same applet, it can be loaded and run from its executable file without any delay for
reinterpreting bytecodes.

Draft. Copyright © 2006 by Skylight Publishing.


Exploring the Variety of Random
Documents with Different Content
This book was produced in EPUB format by the Internet Archive.

The book pages were scanned and converted to EPUB format


automatically. This process relies on optical character recognition,
and is somewhat susceptible to errors. The book may not offer the
correct reading sequence, and there may be weird characters, non-
words, and incorrect guesses at structure. Some page numbers and
headers or footers may remain from the scanned page. The process
which identifies images might have found stray marks on the page
which are not actually images from the book. The hidden page
numbering which may be available to your ereader corresponds to
the numbered pages in the print edition, but is not an exact match;
page numbers will increment at the same rate as the corresponding
print edition, but we may have started numbering before the print
book's visible page numbers. The Internet Archive is working to
improve the scanning process and resulting books, but in the
meantime, we hope that this book will be useful to you.

The Internet Archive was founded in 1996 to build an Internet


library and to promote universal access to all knowledge. The
Archive's purposes include offering permanent access for
researchers, historians, scholars, people with disabilities, and the
general public to historical collections that exist in digital format. The
Internet Archive includes texts, audio, moving images, and software
as well as archived web pages, and provides specialized services for
information access for the blind and other persons with disabilities.

Created with hocr-to-epub (v.1.0.0)


Digitized by the Internet Archive in 2007 with funding from
IVIicrosoft Corporation
http://www.archive.org/details/amongprimitivepeOOevanuoft
The text on this page is estimated to be only 5.00%
accurate

(X) ^9 7 7 
AMONG PRIMITIVE PEOPLES IN BORNEO
:KEfF & RECENT 'BOOKS III the Heart of Bantuland. A
Record of 29 Years' Pioneering in Central Africa, with descriptions of
the Native Habits, Customs, Secret Societies, b'c. By Dugald
Campbbll, F.R.A.I. With many Illustrations d)' a Map. 21s. net. Wild
Bush Tribes of Tropical Africa. Adventurt_ 6^ Travel in Tropical
Africa, with descriptions of the Tribes, Customs Rights.Ceremonies,
Secret Societies, Sport &* Warfare. By G. CvRiL Clakidgk. With 41
Illustrations *• a Map. 2i«. net. Amongf Primitive Peoples in Borneo.
The Lives, Habits, Customs, «Vc. of the Piratical Head-Hunters of
North Borneo. By Ivor H. N. Evans, B.A., F.R.A.I. With many
Illustrations iSf a Map. 21s. net. Kashmir in Sunlight and Shade.
Describing its beauties, jV the habits and customs, &> gradual
rebuilding of a once downtrodden people. By C. E. Tyndale-Biscoe,
M.A. (Cantab.) 28 Illustrations &> a Map. Demy 8vo. 12s. 6d. net.
The Rift Valleys and Geology of Bast Africa. By Prof. J. W. Grkgory,
D.Sc, F.R.S. With many Illustrations &* Maps. 33s. net. A Diplomat in
Japan. The Inner History of the Critical Years of Japan when the
Ports were Opened fir* the Monarchy Restored. By The Right Hon.
Sir Ernest Satow, G.C.M.G. With Illustrations. 32s. net. In Farthest
Burma. An Arduous Journey of Exploration through the Frontier
Territory of Burma &' Tibet. By Captain F. Kingdon Ward, B.A.,
F.R.G.S. Illustrations &• Maps. ass. net. Second Edition. The Life and
Explorations of Frederick Stanley Arnot. Authorised Biography of a
Zealous Missionary iSr* Intrepid Explorer. By Erhest Baker. With
many Illustrations iV a Map. Demy 8vo. I as. 6d. net. Stcond Edition.
Unexplored New Guinea. Travels, Adventures &* Experiences of a
Resident Magistrate in the Unexplored Interior of New Guinea. By
Wilfred N. Beaver, with an Introduction by A. C. Haddon, M.A., ScD.,
F.R.S. With 24 Illustrations ** 4 Maps. Demy 8vo. 253. net. Modern
Whaling and BearHunting:. A Record of Pres«nt-day Whaling. By W.
G. Burn Murdoch, F.R.S.G.S. With no Illustrations. Demy 8vo, ass.
net. Third Edition. Prehistoric Man (^ His Story. A Sketch of the
History of Mankind from the Earliest Times. By Prof. G. F. Scott Elliot,
M.A.(Cantab.) B.Sc.fEdin.), F.R.S.E., F.l^S.. F.R.G.S. With 56
Illustrations, los. 6d. net. SEELEY, SERVICE 6* CO. LTD.
^--r.^>: m. I -.i;*i A Lowland Dusun on a Buffalo. This
ungainly looking brute is a favourite steed, and can keep up a jog-
trot for hours, when it is not exposed to the full heat of the sun. The
animal is " steered " by means of the cord attached to the nose-ring.
A saddle with a high wooden peak is generally used in buffalo-riding.
AMONG PRIMITIVE PEOPLES IN BORNEO A DESCRIPTION
OF THE LIVES, HABITS & CUSTOMS OF THE PIRATICAL
HEADHUNTERS OF NORTH BORNEO, WITH AN ACCOUNT OF
INTERESTING OBJECTS OF PREHISTORIC ANTIQUITY DISCOVERED
IN THE ISLAND IVOR H.N. EVANS, B.A Fellonu of the Royal
Anthropological Institute WITH MANY ILLUSTRATIONS &* A MAP
LONDON ^ ^ SEELEY, SERVICE ?5f CO. LIMITED 38 GREAT
RUSSELL STREET 1922 /
CONTENTS CHAPTER I PAOB British North Borneo —
General Description — History — Government . . . . . .17 CHAPTER II
British North Borneo — Population & Races . . 27 CHAPTER HI Trade
& Industries ...... 36 CHAPTER IV The Tuaran & Tempassuk Districts
. . -45 CHAPTER V The Jungle ....... 56 CHAPTER VI Travelling Up-
Country & Elsewhere . . .62 CHAPTER VII The Life of an Out-Station
Officer . . .71 THE DUSUNS CHAPTER VIII Races of the Tuaran &
Tempassuk Districts . 79 CHAPTER IX Dress & Adornment ...... 88
CHAPTER X Houses — Domestic Affairs — Government . . -93
CHAPTER XI Agriculture, Fishing, Hunting & Trapping . .103 II
1 2 Contents CHAPTER XII PAGB Food, Narcotics &
Intoxicants . . . .112 CHAPTER XIII Courtship, Marriage & Divorce,
Burial & Puberty Customs . . . . . . .122 CHAPTER XIV Musical
Instruments, Music & Dancing . . .130 CHAPTER XV Wealth,
Currency, Trading, Markets . . • ^^35 CHAPTER XVI Manufactures . .
. . .146 CHAPTER XVH Religion & Superstitions . . . . .152 CHAPTER
XVIII Legends . . . . . . .170 CHAPTER XIX Warfare, Head-Hunting 6*
Weapons . . .186 THE BAJAUS & ILLANUNS CHAPTER XX Races of
the Tuaran & Tempassuk Districts . .194 CHAPTER XXI Agriculture,
Hunting & Fishing . . . .201 CHAPTER XXII Dress, Domestic Affairs &
Government . . . 209 CHAPTER XXIII Food 6* Intoxicants . . . . .
.221 CHAPTER XXIV Love, Courtship 6* Marriage . . . .225
The text on this page is estimated to be only 28.87%
accurate

Contents 13 CHAPTER XXV PAGE Manufactures . . • • • •


.229 CHAPTER XXVI COCK-FIGHTING, GAMBLING 6* OtHER
AMUSEMENTS . .238 CHAPTER XXVH Religion 6* Folklore . . • ' .247
CHAPTER XXVHI Weapons & Warfare . . • • • -253 CHAPTER XXIX
Antiquities ....••• 266 CHAPTER XXX The Chinese in Borneo . . • • •
^74 CHAPTER XXXI Diary of a Journey to Mount Kinabalu . . .291
APPENDICES A.— Derivations of some Tempassuk Place-Names .
311 B.— Measurements of "Orang Dusun" .312 C— The Malay
Language . . . • .312 Index ...•••• 3^5
LIST OF ILLUSTRATIONS A Lowland Dusun on a Buffalo ....
Frontispiece A Bamboo Bridge over the Kadamaian . . .24 An Up-
country View in the Tempassuk District . 48 Gumpus, the Headman
of Tambatuan . . . .72 The Wife of the Headman of Tambatuan & her
Favourite Pig . 96 Dusun Women at work in the Fields below
Tambatuan . 104 A Dusun Family Party on the march . . .112 A
Dusun Fish-trap in the Kadamaian River . . .112 Bunsud, a Lowland
Dusun . . . . ,136 The Dusun Organ 6* Banjo . . . .136 A Market
Scene in the Tempassuk District . . .144 Dusun Priestess of
Tambatuan in Ceremonial Dress (/fi?«/) . 160 Dusun Priestess of
Tambatuan in Ceremonial Dress (/'gfl!/') . 160 A Dusun Man of
Tambatuan in War Dress . . .192 15
1 6 List of Illustrations A Head-house at Kaung Ulu . . . .
.192 PAGE Drying Padi in a Dusun Village .... 200 Dusuns of
Tempassuk Village ..... 240 Bajau Village at Mengkabong . . . . .288
In a Rice-field near Tambatuan .... 296 Some Dusun Musical
Instruments .... 296 In Kaung Ulu ....... 304
Among Primitive Peoples in Borneo CHAPTER I BRITISH
NORTH BORNEO GENERAL DESCRIPTION HISTORY GOVERNMENT
THE country with which this book deals is the territory of the British
North Borneo Company, and in particular the adjacent districts of the
Tuaran and Tempassuk, called after two rivers that take their rise in
Mount Kinabalu the magnificent, which towers up almost
perpendicularly on its seaward face to a height of 13,400 feet.
Borneo, the second largest island in the world, which is hazily
connected by the crowd with the existence of wild men, lies, roughly
speaking, south of the Philippines, with Java to the south, Celebes to
the east, Sumatra and the Malay Peninsula to the west, while the
Equator cuts almost through the centre. About two-thirds of the
whole island, comprising the two Residencies of South-East and
West Borneo, is under Dutch rule. The remainder is divided into
three states : Sarawak, which occupies a long strip of territory on
the west coast and has an English ruler (Raja Brooke); British North
Borneo, governed by a Chartered Company, towards the northern
end of the island; and the little native state of Brunei, wedged
between these two, which have both enriched themselves at her
expense. The last-named is now protected by Great Britain and
administered by officers of the Straits Settlements Civil Service. The
first European traveller to give an account of the B 17
1 8 British North Borneo manners and customs of any
Bornean tribe was Antonio Pigafetta, who visited the city of Brunei in
1521. The name Bornei, by which he calls that old state, has now
been further corrupted into the modern Borneo. The credit of being
the first Europeans to discover the island rests apparently with the
Portuguese or the Spaniards, somewhere between 1518 and 1526,
but it seems uncertain to which nationality the laurels should be
awarded. Possibly the Italian traveller Varthema may have visited the
country before either the Portuguese or the Spaniards. However,
there is little doubt that the Chinese had been in the habit of visiting
Borneo at least since the sixth century A.D., and possibly much
earlier, as in the works of various of their historians we have
accounts of embassies which were sent from China to the Royal
Court of Brunei, and vice versa. Trade followed, or perhaps
preceded, the ambassadors; but, though old Chinese pottery and
beads are found almost everywhere in Borneo, it is very doubtful if
there was ever a resident Chinese population numerous enough to
have introduced a serious amount of Chinese blood among the
aboriginals, as has been supposed by some writers. But I shall have
something more to say on this subject when I. come to deal with the
question of the races and tribes inhabiting the country. I The total
area of Borneo is about 290,000 square miles. ^ The island is very
compact and has not many bays or* inlets, though there are a few
on its north-eastern coast. A belt of mangrove swamp of varying
breadth fringes most of the shores, and behind this are plains — not
necessarily open country — foot-hills and finally the mountainous
regions of the interior. Among the plains and swamps wind the lower
courses of the rivers, which take their rise in the mountains, and
eventually empty themselves into the sea through deltas formed of
detritus from the uplands.^ • No land is better provided with rivers
than Borneo, but unfortunately the majority of them are not
navigable for
British North Borneo 19 I boats of any size owing to the
formidable bars at their mouths. i The country is thickly covered with
primeval jungle, except where there is, or has been, a considerable
native population. In such districts virgin jungle is found chiefly on
the highest of the lower hills, and on the mountains, while the
valleys are filled with big secondary growth which has sprung up on
the sites of old native clearings. Taking it as a whole, the west coast
is far more thickly populated than the east, wherefore the east is
much more given over to jungle. I I The climate of Borneo very
much resembles that of the Malay Peninsula, but the island is a good
deal less healthy, the north-eastern coast in particular having a very
bad reputation for fever. As is stated by Guillemard and Kean
(Compendium of the Geography of Australasia)^ Borneo, being
bisected by the Equator, " is exposed to the action of four Monsoons,
in the northern portion to the N.E. and S.W., and in the southern to
the S.E. and N.W., but these ^ winds become considerably altered
with the locality." The general climate may be described as hot and
damp, and though severe droughts sometimes occur, there is no true
dry season. Roughly [speaking, the rainiest part of the year in British
North Borneo is from October to February. I The total population of
Borneo was estimated in 1905 to be about 1,820,000. To turn now
to British North Borneo. This state, with ' an area of 31,000 square
miles and a population of 208,000, is governed by a Chartered
Company, formed for the purpose of developing certain lands,
concessions for which had been obtained from the Sultans of Sulu
and Brunei in ' consideration of stipulated annual payments. The
negotiations with these Sultans for the transfer of the territories to a
Provisional Company were concluded by the late Sir Alfred Dent and
Baron Overbeck in 1877. The American Consul in Brunei had already
obtained
20 British North Borneo concessions for some of the
territories which are now under the flag of the British North Borneo
Company, a trading Company had been formed, and, with a view to
opening up the country, Chinese had been imported and settled at
Kimanis. However, neither the settlement nor the Company
flourished, and its rights were finally acquired by Baron Overbeck.
Sir Alfred (then Mr) Dent visited various parts of the territories,
accompanied by representatives of the Brunei and Sulu
Governments, who were empowered to notify the inhabitants that
the rights of bothl Sultans had been transferred to the Company;
European ofl[icers in command of small bodies of police were left at
Sandakan — now the capital — Tempassuk and Papar; the Dent
house flag was hoisted at the stations opened, and the new
territories came, at any rate in name, under the control of the
lessees. In 1 88 1, in spite of bitter opposition on the part of the
Dutch and the Spaniards, a Royal Charter was granted to the
Provisional Company which had been formed to acquire the rights of
the lessees. The Dutch, who had previously done everything in their
power to hinder the aflfairs of Raja Brooke in Sarawak, naturally did
not welcome the formation of yet another British state in Borneo ;
while the Spanish were displeased at the British obtaining any power
in th( northern portion of Borneo which they considered withii their
sphere of influence, as being in juxtaposition to th< southern islands
of the Philippines, and nominally undei the Sultan of Sulu. Indeed
the latter seem to have hac some title to those districts over which
the royal house o Sulu claimed to exercise power, since the Sultan of
Suli had for some time been subject to them. However, th(
concessions from the Sultan were obtained while he was h rebellion
against the Spaniards, and, as he did not make hii peace with them
until later in the year, the moral rights oi the Spaniards, whatever
they might be worth, were nol recognised.
British North Borneo 2i The British North Borneo Provisional
Association was dissolved on the formation of the Chartered
Company in 1882, when Sir Rutherford Alcock, Mr A. Dent, Mr R. B.
Martin, Admiral Mayne and Mr W. H. Read, who had formed the
Board of the Provisional Association, became the first Directors. The
nominal capital of the new Company was ;if 2,000,000 in £10
shares; but only 4500 fully paid shares were issued to the vendors,
while £\i. per share was called up on the remainder. The actual cash,
therefore, with which the Company started its existence, including
;^iooo received for forfeited shares, was only about ;^3 84,000. The
Charter granted to the Company stipulated for the proper treatment
of the natives, and provided that whenever a new Governor was
chosen his name should be submitted to the Secretary of State for
the Colonies for approval before the appointment was confirmed.
The Company was to have sovereign rights within its own territory,
but all dealings with foreign powers were to be conducted with the
sanction of the Home Government, while provision was also made
for maintaining the British character of the body. The Company's
flags were to be the Union Jack "defaced'* with a lion passant in the
centre, and the Blue and Red Ensigns with a lion in the fly. Such,
then, were the beginnings of the new Company : a few European
oflScers holding insecure positions with the aid of small companies
of police, a certain amount of cash, and absolute rights over a large
territory leased to the Company by two Sultans who were practically
without power to enforce their will in the portions of it claimed
respectively by each. At first, however, things went fairly well ;
settlements were founded at Sandakan, Kudat, Gaya Island and ,
elsewhere; while these three stations — the Gaya Island settlement
having since been removed to the mainland and given the name of
Jesselton — are still the most important towns in the Company's
territory, though Kudat, the old capital, has lagged somewhat behind
the other two.
22 British North Borneo Luckily for the Company, the
natives of British North Borneo are neither so warHke nor so well
organised as those of Sarawak; consequently there have been fewer
wars. The two most troublesome tribes have been the Bajaus and
Illanuns of the west coast, who are by nature and education
undisciplined robbers, sea-rovers and freebooters. In the old days
the Illanuns were the most notorious pirates in the Archipelago, and
their very name was a terror even to people living so far away as the
Malay Peninsula, to the inhabitants of which probably a good many
piracies were credited, which were really the work of the former. The
Illanuns are resident in the Tempassuk district, while the Bajaus are
found on both coasts, those on the west having settled villages,
while those on the east live the lives of seagipsies. From among the
Bajaus of Inanan in the Tuaran district arose one leader to withstand
the rising power of the Chartered Company. Mat Sal eh, a man of
good birth, partly by appealing to the predatory instincts of the more
disorderly tribes, partly by trading on the natives' mistrust of the
Chartered Company, which was assuming control of large tracts of
country without consulting the wishes of the inhabitants, was able to
raise considerable forces, and for a number of years gave the
Directors many uneasy moments. Among his chief exploits, or those
of his lieutenants, were the plundering of Gaya Treasury, a march on
Sandakan and the sacking and burning of Kudat " Arsenal." By some
Mat Saleh has been condemned as a treacherous and crafty enemy
and a rebel against the government of the country; by others — the
love-your-enemy-and-hate-yourneighbour party in Parliament — he
has been canonised as a patriot saint, defending his country against
the encroachments of a Company of chartered freebooters. Neither
of these estimates is correct. He appears to have been a man of
good presence, considerable activity and great courage, who,
besides being a born leader, was possessed of consider 
British North Borneo 23 able powers of persuasive
eloquence. Patriotism, in the sense in which it is understood in
Europe, or indeed in any sense, is unknown among the native tribes
of Borneo; but Mat Saleh well represented the prevailing Bajau
feeling with regard to the new government, which was both disliked
and feared, since it threatened to put bounds to the Bajaus'
immemorial right of doing exactly as they chose, and to their equally
venerable custom of oppressing and cheating the natives of the
interior. On the other hand, it cannot be said that the Chartered
Company had morally — even supposing that its legal rights were
above suspicion — any right to possess itself of its present
territories. Except in the case of a few small districts acquired at a
later date, which were taken over from minor chiefs in consideration
of annual payments, the titles to the country were obtained from the
Sultans of Sulu and Brunei. These Sultans were claimants to nearly
all the territory which is now under the rule of the Chartered
Company; but, except perhaps for one or two valleys not far from
the present border of the state of Brunei, their claims were of the
most shadowy description, neither potentate being able to enforce
his orders even in the coastal regions, while practically the only
tangible sign of the Sultan of Sulu's existence, as far as Borneo was
concerned, were raids by Sulu pirates and the settlements formed,
chiefly on the east coast, by his somewhat undesirable subjects. The
Sultan of Brunei seems to have been occasionally able to exact
tribute from some of the people of the west coast, but this was
rather in the nature of blackmail extorted by war prahus. Natives
who made themselves useful to him were often given high-sounding
titles. He had absolutely no control over the interior. Naturally both
Sultans were only too glad to transfer their doubtful claims in
exchange for what was to them a liberal yearly payment, for they
lost little or nothing by surrendering all rights in the territory, and
obtained a
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookname.com

You might also like