Instant Download Java Methods A Ab Object oriented Programming and Data Structures Maria Litvin PDF All Chapters
Instant Download Java Methods A Ab Object oriented Programming and Data Structures Maria Litvin PDF All Chapters
com
https://ebookname.com/product/java-methods-a-ab-object-
oriented-programming-and-data-structures-maria-litvin/
OR CLICK BUTTON
DOWNLOAD EBOOK
https://ebookname.com/product/object-oriented-data-structures-using-
java-chip-weems/
ebookname.com
https://ebookname.com/product/a-comprehensive-introduction-to-object-
oriented-programming-with-java-1st-edition-c-thomas-wu/
ebookname.com
https://ebookname.com/product/object-oriented-programming-using-c-
fourth-edition-joyce-farrell/
ebookname.com
https://ebookname.com/product/contexts-of-metaphor-current-research-
in-the-semantics-pragmatics-interface-1st-edition-m-leezenberg/
ebookname.com
Modern Times India 1880s 1950s Environment Economy Culture
First Edition Sumit Sarkar
https://ebookname.com/product/modern-times-
india-1880s-1950s-environment-economy-culture-first-edition-sumit-
sarkar/
ebookname.com
https://ebookname.com/product/the-political-philosophy-of-zionism-
trading-jewish-words-for-a-hebraic-land-1st-edition-eyal-chowers/
ebookname.com
https://ebookname.com/product/the-siege-ljuba-merlina-bortolani/
ebookname.com
https://ebookname.com/product/decomposition-methods-for-differential-
equations-theory-and-applications-1st-edition-juergen-geiser/
ebookname.com
https://ebookname.com/product/the-examined-life-philosophical-
meditations-1st-simon-schuster-paperb-ed-edition-robert-nozick/
ebookname.com
Transcultural Cities Border Crossing and Placemaking isbn
9780415631426 1st Edition Jeffrey Hou
https://ebookname.com/product/transcultural-cities-border-crossing-
and-placemaking-isbn-9780415631426-1st-edition-jeffrey-hou/
ebookname.com
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]
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
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
Preface xvii
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
Index
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),
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 special thanks to Margaret Litvin for her thorough and thoughtful editing.
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.
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.
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).
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.
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.
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
B °
A XOR B
°
A B A XOR B
T T F
T F T
F T T
F F F
Language: English
UP FROM
METHODISM
ALFRED · A · KNOPF
NEW YORK
1926
Copyright 1926 by Alfred A. Knopf, Inc.
AGENTS OF GOD
2
We were a musical family. My elder brother and I played the
harmonica, or French harp, as we called it then, and my sister
performed capably upon the organ, the guitar and the mandolin. She
was particularly adept upon the guitar, and enjoyed an enviable
reputation for the way she whanged out the fandango pieces and the
tune descriptive of the Battle of Sebastopol, which requires much
banging and thumping and difficult fingering. My father was a fiddler.
He did not know one note from another, but he could tuck his fiddle
under his chin, tap the floor with his foot and play with great spirit
such tunes as “Fisher’s Hornpipe,” “Billy in the Low Ground,” “Turkey
in the Straw” and “The Arkansas Traveler.” But his muse was dumb if
he could not pat his foot. I could also beat a snare drum passably,
and later I learned to play the violin, the cornet and the alto horn, so
that we had quite a family orchestra, and our house was frequently
filled with music. Anyhow we played these instruments.
But not on Sunday. Our Preacher assured us that music on Sunday,
except in church, was sinful and an affront to the Heavenly Father,
and on Saturday night, after a final orgy of melody, my mother
gathered up the guitars and mandolins, the fiddles, the drums and
the harmonicas and all of the other musical instruments, even the
jew’s-harp, and put them under lock and key until Monday morning.
We could not even play a comb on Sunday, although on rare
occasions, usually when the Preacher was there and gave
permission and absolution from sinful consequences, I was
permitted to bring out my big harmonica, from which I could produce
the sonorous tones of an organ, and play church hymns such as
“Rock of Ages” and “Nearer, My God, to Thee.” But I was forbidden
to play “Turkey in the Straw” or “The Mocking Bird” with variations.
The latter was my favorite tune, because by jiggling my hand over
the harmonica I could produce a very effective trill which I fondly
believed was as beautiful as the singing of a canary, but if I launched
into such a tune on Sunday I had debauched the Sabbath, and my
harmonica was taken from me. And frequently I myself was taken
into the woodshed and taught a proper respect for the Lord’s Day.
Under no circumstances could we play the fiddle in our house on
Sunday, because of all music, that which came from the fiddle was
the most sinful. It was the Devil’s instrument. No fiddling on Sunday
had been a cardinal rule of my father’s family since Colonial days in
Virginia, and later in Mississippi and in North Carolina my
grandmother had compelled her Negro slaves to put up their musical
instruments from Saturday night to Monday morning. Eventually I
took lessons from the music teacher in Farmington and learned to
call the fiddle a violin, and as I grew older I played when I pleased,
although not very successfully. But so long as the instrument
remained a fiddle it was played in our house on Sunday on only one
occasion. And then the performance was a neighborhood scandal,
and only the fact that the instrument had been played by a Preacher
saved us from getting into trouble with God and His representatives
in Farmington.
This tweaking of the heavenly nose occurred during a District
Conference, when the visiting preachers were parceled out among
the faithful of the local Methodist church. Two came to us, one a
young man filled with good works and a constant, fretful worry over
the low estate of the human race, and the other an old man who had
been a wicked sinner in his time and who had never been able to
resist an occasional temptation to have a good time. He was a
Virginian and an accomplished fiddler, but he could play nothing but
dance music, which the darkies had taught him. The first Sunday
they were at our house my father admitted that we had a fiddle, and
the old Preacher demanded that it be brought out for him to perform
upon. My father and mother were in terror all afternoon for fear that
the neighbors would hear the wailing of the fiddle, although they
prevailed upon the old man to use a mute and the music could
hardly be heard outside the room. We were particularly afraid that a
devout Sister, who lived next door to us and whose principal
occupation was going to church, might hear it; if she had it would
have been nothing short of a catastrophe, for the tale would have
been all over town before nightfall. So we closed the windows and
the doors, muted the fiddle and put the old Preacher in the parlor,
where he fiddled until he had sinned enough. But even then several
people passing along the street heard it, and I do not think that we
ever quite lived it down. We could convince no one that the fiddle
had been played by a Man of God. Everyone knew better; Men of
God did not do such things.
3
Every Wednesday night we attended prayer meeting, and on
Sundays we went to Sunday school and twice to church. And on
Sunday afternoon, and on week days, there were the sessions of the
various church organizations. We had grace before meat in our
home, and when the Preacher came to dinner he delivered long-
winded prayers on the universal theme of “gimme.” We did not have
that emotional orgy called family prayer, but I did not escape it; I
encountered it in many Farmington homes and in the houses of
almost all of my relatives.
It was particularly oppressive in the home of an oppressively devout
kinsman whom I called uncle. He was not actually my uncle; he was
related to my father by marriage, and I do not believe there was any
blood kinship, but I thought of him as uncle, and he had a certain
measure of authority over me, so that to a considerable extent I was
under his control and subject to his influence until I became
intelligent enough to have an occasional thought of my own.
My uncle was an extraordinarily pious man, an official of our church
and of our Sunday school, and a leader in every movement designed
to entice the sinner from his wicked ways and lead him to the true
religion of the Wesleyans. He was intent upon salvation for
everyone, and let no opportunity pass to serve the Lord. He frowned
upon laughter, and although he had a very charming family, there
was little joy in his home; a laugh seemed to make him
uncomfortable and start a train of dismal religious thought, and I
gathered the impression that all mirth was a direct and studied
affront to God.
Every night after dinner, or supper, as we called it then, his living
room was given over to family prayer. I frequently spent the night
with his youngest son, my chum for many years, and was compelled
to attend with the others and absorb my nightly dose of religion, and
listen to a solemn account of the fearful things that God would do to
us if we strayed from the path of righteousness. There was no
laughter, and there were no jokes; the whole atmosphere of the
house turned gray and gloomily oppressive when my uncle rose from
his seat, glanced sorrowfully at his family, and announced:
“We will now have prayers.”
He turned and with bowed head passed into the living room. We sat
at the supper table for a moment in silence, myself seeing goblins
and fearsome avenging creatures of God leering at me from every
shaded corner of the room, and my mind racing madly over the day’s
activities to discover what I had done that required an alibi. In a few
moments my aunt arose and went slowly into the other room, and
then one by one the others. We marched solemnly, with downcast
eyes; we might have been going to a funeral. Indeed, it seems to me
now that we must in truth have been going to a funeral; here was a
fine house built for the warmth of human happiness, turned into a
forbidding mausoleum by the mere mention of God.
In the living room Uncle awaited us, standing beside the small table
on which, always, there was nothing but the Family Bible. He waited
in silence until we had taken our places, and then he laid reverent
hands upon the Book and began fumbling with the pages, glancing
sharply over his spectacles to make sure that everyone was
undergoing some sort of emotional upheaval, and looking particularly
for some sign of revolt from his son and myself. I doubt if he ever
knew it, but when I attended family prayer in his house I did not think
of revolt. I was in an agony of fright; I felt as if something was
crushing me, and that something was my uncle’s God, an avenging
monster ready to devour me for my sins. God was in the house and I
was afraid.
The most uncomfortable chairs in the house were used for family
prayer, and we perched upon their edges, afraid to sink back and
relax, because we had been told many times that discomfort and
righteousness were well-nigh synonymous. God would have been
scandalized and indignant had we made ourselves comfortable to
listen to His Word. And then my uncle read from the Bible. He read
without joy; he held in his hand the Book which in his eyes was the
sole hope of humanity, the Book that contained the glad news that
for all mankind there was salvation, but he read it as if it were a
sentence of death, slowly and solemnly, dwelling with horrible clarity
upon those phrases that promised punishment. The Bible seemed to
have no effect upon him but to make him gloomy and miserable.