Java How to Program
Preface
Live in fragments no longer. Only
connect.
Edward Morgan Forster
Welcome to Java and the exciting world of
Internet and World Wide Web programming! This book is by an old guy and a
young guy. The old guy (HMD; Massachusetts Institute of Technology 1967)
has been programming and/or teaching programming for 35 years. The young
guy (PJD; MIT 1991) has been programming for a dozen years and has caught
the teaching and writing "bug." The old guy programs and teaches
from experience; the young guy does so from an inexhaustible reserve of
energy. The old guy wants clarity; the young guy wants performance. The
old guy appreciates elegance and beauty; the young guy wants results. We
got together to produce a book we hope you will find informative,
interesting, and entertaining.
In November 1995 we attended an
Internet/World Wide Web conference in Boston to hear about Java. A Sun
Microsystems representative spoke on Java in one of the convention
ballrooms. We were lucky to get seats. During the next hour, we saw the
future of programming unfold. Java How to Program was born at that
moment.
Before Java appeared, we were convinced
that C++ would replace C as the dominant application development language
and systems programming language for the next decade. But the combination
of the World Wide Web and Java now increases the prominence of the
Internet in information systems strategic planning. Organizations want to
integrate the Internet "seamlessly" into their information
systems. Java is much more appropriate than C++ for this purpose.
Why We Wrote Java How to Program
Dr. Harvey M. Deitel taught introductory
programming courses in universities for 20 years with an emphasis on
developing clearly written, well-structured programs. Much of what is
taught in these courses is the basic principles of programming with an
emphasis on the effective use of control structures and functionalization.
We present these topics in Java How to Program exactly the way HMD
has done in his university courses. Our experience has been that students
handle the material in the early chapters on control structures and
methods (Java's term for functions) in about the same manner as they
handle introductory Pascal or C courses. There is one noticeable
difference though: students are highly motivated by the fact that they are
learning a leading-edge language (Java) and a leading-edge programming
paradigm (object-oriented programming) that will be immediately useful to
them as they leave the university environment and head into a world in
which the Internet has a massive new prominence. This increases their
enthusiasm for the materiala big help when you consider that there is
much more to learn in a Java course given that students must now master
both the base language and substantial class libraries as well. But
students quickly discover that they can do great things with Java, so they
are willing to put in the extra effort.
Our goal was clear: produce a Java textbook
for introductory university-level courses in computer programming for
students with little or no programming experience, yet offer the depth and
the rigorous treatment of theory and practice demanded by traditional,
upper-level C and C++ courses and that satisfies professionals' needs. To
meet these goals, we produced a comprehensive book because our text also
patiently teaches the principles of control structures, object-oriented
programming, the Java language and Java class libraries.
Java How to Program is the first
college textbook on Java. We wrote it fresh on the heels of C How to
Program:Second Edition and C++ How to Program, each of which
has become the world's leading introductory textbook in its respective
field. Approximately 200,000 students worldwide have learned C and/or C++
from these texts. We taught 25 Java courses to approximately 400 students
as we were writing Java How to Program and monitored student
reaction to Java and to our materials. We have prepared a Windows-based,
interactive CD-ROM multimedia edition of this book, the Java Multimedia
Cyber Classroom (available November 1996). [Prentice Hall offers a
"value pack" edition of both Java How to Program and the Java
Multimedia Cyber Classroom at a discount for people who want to use
both the book and the multimedia CD.]
We believe in Java. Its conceptualization
by Sun Microsystems, the creators of Java, is brilliant: base a new
language on two of the world's most widely used implementation languages,
C and C++. This immediately gives Java a huge pool of highly skilled
programmers who are currently responsible for implementing most of the
world's new operating systems, communications systems, database systems
and personal computer applications systems software. Remove the messier,
more complex and error-prone features (such as pointers, templates,
operator overloading and multiple inheritance, among others). Keep the
language as concise as is reasonable by removing special-purpose features
that are used by only small segments of the programming community. Make
the language truly portable so it is appropriate for implementing
Internet-based and World-Wide-Web-based applications, and build in the
features people really need such as strings, graphics, graphical user
interface components, exception handling, multithreading, multimedia
(audio, images, animationand eventually video), file processing,
Internet-based client/server networking and prepackaged data structures.
Then make the language available at no charge to tens of millions of
potential programmers worldwide.
Java was originally promoted as a means of
adding "dynamic content" to World-Wide-Web pages. Instead of Web
pages with only text and static graphics, people's Web pages "come
alive" with audios, animations, interactivityand soon, video and
three-dimensional imaging. But we saw much more than this. These features
are precisely what businesses and organizations really need to meet
today's information processing requirements. So we immediately viewed Java
as having the potential to become one of the world's key general-purpose
programming languages.
There are a number of for-sale Java
products available. However, you do not need them to get started with
Java. We intentionally wrote Java How to Program using only the
free Java software available from Sun Microsystems over the Internet. We
have seen many excellent Java for-sale products that will certainly be
attractive to businesses and individuals programming in Java.
Java is empowering people and organizations
to unleash their creativity. We have seen this in the 25 Java courses we
taught prior to publishing Java How to Program. Once our students enter
lab, we can't hold them back. They are eager to experiment and explore
portions of the Java class libraries that we haven't as yet covered in
class. They produce applications that go well beyond anything we've ever
tried in our introductory C and C++ courses. And they tell us about
projects they "can't wait" to try after the course.
Java has weaknesses that we discuss
frankly. But we should not lose sight of the fact that Java is "just
a baby"it needs time to mature. Interest in Java is huge. People
really want the "Java model" to work. The apparent weaknesses
are being addressed and solutions are forthcoming. For example,
organizations and individuals want to transact business over the Internet.
The Internet is a fundamentally insecure communications channel. But
techniques exist and are being refined for performing secure transmission
over insecure channelsa contradiction in terms, perhaps, but
nevertheless soon to be reality.
The computer field has never seen anything
like the Internet/World Wide Web/Java "explosion" occurring
today. People want to communicate. People need to communicate. Sure they
have been doing that since the dawn of civilization, but computer
communications have been mostly limited to digits, alphabetic characters
and special characters passing back and forth. The next major wave is
surely multimedia. People want to transmit pictures and they want those
pictures to be in color. They want to transmit voices, sounds and audio
clips. They want to transmit full motion color video. And at some point,
they will insist on three-dimensional, moving-image transmission. Our
current flat, two-dimensional televisions will eventually be replaced with
three-dimensional versions that turn our living rooms into
"theaters-in-the-round." Actors will perform their roles as if
we were watching live theater. Our living rooms will be turned into
miniature sports stadiums. Our business offices will enable video
conferencing among colleagues half a world apart as if they were sitting
around one conference table. The possibilities are intriguing and Java is
sure to play a key role in making many of these possibilities become
reality.
There have been predictions that the
Internet could eventually replace the telephone system. Well, why stop
there? It could also replace radio and television as we know them today.
It's not hard to imagine the Internet replacing the newspaper with
completely electronic news media. This textbook you are reading may
someday appear in a museum alongside radios, TVs and newspapers in an
"early media of ancient civilization" exhibit.
Teaching Approach
Java How to Program contains a rich
collection of examples, exercises, and projects drawn from many fields to
provide the student with a chance to solve interesting real-world
problems. The book concentrates on the principles of good software
engineering and stresses program clarity. We avoid arcane terminology and
syntax specifications in favor of teaching by example. Each of our code
examples has been carefully tested on several Java platforms including
those for Sun's Solaris and Microsoft's Windows 95 and Windows NT. This
book is written by two educators who spend most of their time teaching
edge-of-the-practice topics in industry classrooms worldwide. The text
emphasizes pedagogy.
Introducing Object
Orientation and Applets from Chapter One!
Java How to Program "jumps
right in" with object-oriented programming, applets and even basic
graphical user interface design from Chapter 1! People tell us this is a
"gutsy" move. But Java students really want to "cut to the
chase." There is great stuff to be done in Java so let's get right to
it! Java is not trivial by any means, but it's fun and students can see
immediate results. Students can get graphical, animated, multimedia-based,
audio-intensive, multithreaded, network-based programs running quickly
through Java's extensive class libraries of "reusable
components." They can implement impressive projects. They can be much
more creative and productive in a one- or two-semester course than is
possible in C and C++ introductory courses.
Live-Code Teaching Approach
The book is loaded with live-code examples.
This is the focus of the way we teach and write about programming, and the
focus of each of our multimedia Cyber Classrooms as well. Virtually every
new concept is presented in the context of a complete, working Java
program (applet or application) immediately followed by a window showing
the program's output. We call this style of teaching and writing our
live-code approach. We use the language to teach the language. Reading
these programs is much like entering and running them on a computer.
World Wide Web Access
All of the code for Java How to Program
is on the Internet at the Prentice Hall Web site http://www.prenhall.com/deitel
and at the Deitel & Associates, Inc. Web site http://www.deitel.com.
Please download all the code then run each program as you read the text.
Make changes to the code examples and see what happens. See how the Java
compiler "complains" when you make various kinds of errors.
Immediately see the effects of making changes to the code. It's a great
way to learn programming by doing programming. [You must respect the fact
that this is copyrighted material. Feel free to use it as you study Java,
but you may not republish any portion of it without explicit permission
from the authors and Prentice Hall.]
Objectives
Each chapter begins with a statement of
Objectives. This tells the student what to expect and gives the student an
opportunity, after reading the chapter, to determine if he or she has met
these objectives. It is a confidence builder and a source of positive
reinforcement.
Quotations
The learning objectives are followed by
quotations. Some are humorous, some are philosophical, and some offer
interesting insights. Our students enjoy relating the quotations to the
chapter material. The quotations are worth a "second look" after
you read each chapter.
Outline
The chapter Outline helps the student
approach the material in top-down fashion. This, too, helps students
anticipate what is to come and set a comfortable and effective learning
pace.
12,087 lines of code in 200 Example
Programs (with Program Outputs)
We present Java features in the context of
complete, working Java programs. This is the focus of our teaching and our
writing. We call it our "live-code" approach. Each program is
followed by a window with the output produced when the program runs. This
enables the student to confirm that the programs run as expected. Reading
the book carefully is much like entering and running these programs on a
computer. The programs range from just a few lines of code to substantial
examples with several hundred lines of code. Students should download all
the code for the book from our Web sites and run each program while
studying that program in the text. The programs are available at both http://www.deitel.com
and http://www.prenhall.com/deitel.
166 Illustrations/Figures
An abundance of charts, line drawings and
program outputs is included. The discussion of control structures, for
example, features carefully drawn flowcharts. [Note: We do not teach the
use of flowcharting as a program development tool, but we do use a brief,
flowchart-oriented presentation to specify the precise operation of Java's
control structures.]
369 Programming Tips
We have included programming tips to help
students focus on important aspects of -program development. We highlight
hundreds of these tips in the form of Good
Programming Practices, Common
Programming Errors, Testing
and Debugging Tips, Performance
Tips, Portability
Tips, and Software
Engineering Observations. These
tips and practices represent the best we have been able to glean from a
combined four-and-one-half decades of programming and teaching experience.
One of our studentsa mathematics majortold us recently that she
feels this approach is like the highlighting of axioms, theorems, and
corollaries in mathematics books; it provides a basis on which to build
good software.
62 Good
Programming Practices
When we teach introductory courses, we
state that the "buzzword" of each course is "clarity,"
and we highlight as Good Programming Practices techniques for writing
programs that are clearer, more understandable, more debuggable, and more
maintainable.
139
Common Programming Errors
Students learning a language tend to make
certain errors frequently. Focusing the students' attention on these
Common Programming Errors helps the student avoid making the same errors.
It also helps reduce the long lines outside instructors' offices during
office hours!
29
Testing and Debugging Tips
When we first designed this "tip
type," we thought we would use it strictly to tell people how to test
and debug Java programs. In fact, many of the tips describe aspects of
Java that reduce the likelihood of "bugs" and thus simplify the
testing and debugging process for Java programs compared to that required
for C and C++ programs.
50
Performance Tips
In our experience, teaching students to
write clear and understandable programs is by far the most important goal
for a first programming course. But students want to write the programs
that run the fastest, use the least memory, require the smallest number of
keystrokes, or dazzle in other nifty ways. Students really care about
performance. They want to know what they can do to "turbo
charge" their programs. So we have included 50 Performance Tips that
highlight opportunities for improving program performance.
8
Portability Tips
Some programmers assume that if they
implement an application in Java, the application will automatically be
"perfectly" portable across all Java platforms. Unfortunately,
this is not always the case. We include Portability Tips to help students
write portable code and also to provide insights on how Java achieves its
high degree of portability. We had many more portability tips in C How
to Program and C++ How to Program. We needed fewer Portability
Tips in Java How to Program because Java is designed to be portable
top-to-bottom, so much less conspicuous effort is required on the Java
programmer's part to achieve portability than with either C or C++.
81
Software Engineering Observations
The object-oriented programming paradigm
requires a complete rethinking about the way we build software systems.
Java is an effective language for performing good software engineering.
The Software Engineering Observations highlight architectural and design
issues that affect the construction of software systems, especially
large-scale systems. Much of what the student learns here will be useful
in upper-level courses and in industry as the student begins to work with
large, complex real-world systems.
Summary
Each chapter ends with additional
pedagogical devices. We present a thorough, bullet-list-style Summary of
the chapter. On average, there are 34 summary bullets per chapter. This
helps the students review and reinforce key concepts.
Terminology
We include in a Terminology section an
alphabetized list of the important terms defined in the chapteragain,
further reinforcement. On average, there are 87 terms per chapter.
Summary of Tips, Practices, and Errors
For ease of reference, we collect and
reiterate the Good Programming Practices, Common Programming Errors,
Testing and Debugging Tips, Performance Tips, Portability Tips, and
Software Engineering Observations.
346 Self-Review Exercises and Answers
(Count Includes Separate Parts)
Extensive self-review exercises and answers
are included for self-study. This gives the student a chance to build
confidence with the material and prepare for the regular exercises.
Students should be encouraged to do all the self-review exercises and
check their answers.
879 Exercises (Solutions in Instructor's
Manual; Count Includes Separate Parts)
Each chapter concludes with a substantial
set of exercises including simple recall of important terminology and
concepts; writing individual Java statements; writing small portions of
Java methods and classes; writing complete Java methods, classes, applets
and applications; and writing major term projects. The large number of
exercises across a wide variety of areas enables instructors to tailor
their courses to the unique needs of their audiences and to vary course
assignments each semester. Instructors can use these exercises to form
homework assignments, short quizzes, and major examinations. The solutions
for the exercises are included in the Instructor's Manual and on the disks
available only to instructors through their Prentice-Hall representatives.
Solutions to approximately half of the exercises are included on the Java
Multimedia Cyber Classroom CD
(available November 1996 in bookstores and computer stores; it can be
ordered from Prentice
Hall at 1-800-922-0579).
4613 Index Entries (with a Total of 7824
Page References)
We have included an extensive Index at the
back of the book. This helps the student find any term or concept by
keyword. The Index is useful to people reading the book for the first time
and is especially useful to practicing programmers who use the book as a
reference. Each of the 1584 terms in the Terminology sections appears in
the Index (along with many more index items from each chapter). Students
can use the Index in conjunction with the Terminology sections to be sure
they have covered the key material of each chapter.
"Double Indexing" of All Java
Live-Code Examples and Exercises
Java How to Program has 200
live-code examples and 1225 exercises (including parts). Many of the
exercises are challenging problems or projects requiring substantial
effort. We have "double indexed" all of the live-code examples
and most of the more challenging projects. For every Java source-code
program in the book, we took the file name with the .java
extension, such as LoadAudioAndPlay.java and indexed it
both alphabetically (in this case under "L") and as a subindex
item under "Examples. This makes it easier to find examples using
particular features. The more substantial exercises, such as "Maze
Generator and Walker," are indexed both alphabetically (in this case
under "M") and as subindex items under "Exercises."
Bibliography
An extensive bibliography is included to
encourage further reading.
A Tour of the Book
Chapter
1Introduction to Computers and Java Appletsdiscusses what
computers are, how they work and how they are programmed. The chapter
gives a brief history of the development of programming languages from
machine languages, to assembly languages, to high-level languages. The
origin of the Java programming language is discussed. The chapter includes
an introduction to a typical Java programming environment and gives a
concise introduction to writing Java programs. A detailed treatment of
decision making and arithmetic operations in Java is presented. After
studying this chapter, the student will understand how to write simple,
but complete, Java programs. A distinguishing feature of Chapter 1 is that
we "jump right in" with object-oriented programming in Java; our
first program uses inheritance to create a Java applet, then displays the
applet window. We introduce some basics of HTML programming and discussion
the relationship among HTML, the World Wide Web and the Internet. We waste
no time in getting to Labels and TextFields
to prompt for inputs and read them from the keyboard. With Java you can
write two kinds of programs namely, applets designed to be transported
over the Internet and executed in World Wide Web browsers like Netscape
Navigator, and stand-alone applications designed to execute on your own
computer. Because of the intense interest in Java applets and the World
Wide Web, we present Java programs as applets whenever possible. Because
of certain stringent security restrictions related to file processing and
networking the examples in those chapters (15 and 16) are presented as
Java applications.
Chapter 2Developing
Java Applicationsfocuses on the program development process. The
chapter discusses how to take a problem statement (i.e., a requirements
document) and from it develop a working Java program, including
performing intermediate steps in pseudocode. The chapter introduces some
fundamental data types and simple control structures used for decision
making (if and if/else) and repetition (while).
We examine counter-controlled repetition, sentinel-controlled repetition,
and introduce Java's increment, decrement and assignment operators. We
have had a positive experience assigning problems 2.11 through 2.14 in our
introductory courses. Since these four problems have similar structure,
doing all four is a nice way for students to "get the hang" of
the program development process. Students will enjoy the challenges of the
"mystery programs." The more mathematically inclined students
will enjoy problems on palindromes, binary-to-decimal conversion,
encryption and decryption, and calculating factorials.
Chapter 3Control
Structuresdiscusses much of the C portion of Java, especially the
sequence, selection (if, if/else and switch)
and repetition (while, for and do/while)
control structures. The chapter uses simple flowcharts to show the flow of
control through each of the control structures. The techniques discussed
in Chapter 2 and Chapter 3 constitute a large part of what has been
traditionally taught in the universities under the topic of structured
programming. With Java we do object-oriented programming. In doing so, we
discover that the insides of the objects we build make abundant use of
control structures. Chapter 3 examines repetition in detail and compares
the alternatives of counter-controlled loops and sentinel-controlled
loops. This chapter helps the student develop good programming habits in
preparation for dealing with the more substantial programming tasks in the
remainder of the text. The chapter clearly explains the labeled break
and continue statements with live-code examples. The
chapter concludes with a discussion of logical operators&&
(logical AND), & (boolean logical AND), ||
(logical OR), | (boolean logical inclusive OR), ^
(boolean logical exclusive OR) and ! (NOT). There is a
substantial exercise set including mathematical, graphical business
applications. Students will enjoy Exercise 3.26 that asks them to write a
program with repetition and decision structures that prints the iterative
song, "The Twelve Days of Christmas." The more mathematically
inclined students will enjoy problems on binary, octal, decimal and
hexadecimal number systems, calculating the mathematical constant p with
an infinite series, Pythagorean triples and De Morgan's Laws. Our students
particularly enjoy the challenges of triangle-printing and
diamond-printing in Exercises 3.10 and 3.21; these problems really help
students learn to deal with nested repetition structuresa complex topic
to master in introductory courses.
Chapter 4Methodstakes
a deeper look inside objects. Objects contain data which we will generally
refer to as instance variables and executable units called methods (these
are often called functions in non-object-oriented procedural programming
languages like C). We explore methods in depth and include a discussion of
methods that "call themselves," so-called recursive methods. We
discuss class library methods, programmer-defined methods, recursion,
call-by-value and call-by-reference capabilities. The techniques presented
in Chapter 4 are essential to the production of properly structured
programs, especially the kinds of larger programs and software that system
programmers and application programmers are likely to develop in
real-world applications. The "divide and conquer" strategy is
presented as an effective means for solving complex problems by dividing
them into simpler interacting components. Students enjoy the treatment of
random numbers and simulation, and they appreciate the discussion of the
dice game of craps that makes elegant use of control structures (this is
one of our most successful lectures in our introductory courses). The
chapter offers a solid introduction to recursion and includes a table
summarizing the dozens of recursion examples and exercises distributed
throughout the remainder of the book. Some texts leave recursion for a
chapter late in the book; we feel this topic is best covered gradually
throughout the text. The topic of method overloading (i.e., allowing
multiple methods to have the same name as long as they have different
"signatures") is motivated and explained clearly. The extensive
collection of exercises at the end of the chapter includes several
classical recursion problems such as the Towers of Hanoi; we revisit this
problem later in the text where we employ graphics, animation and sound to
make the problem "come alive." There are many mathematical and
graphical examples. Our students particularly enjoy the development of a
"Computer-Assisted Instruction" system in exercises 4.31 and
4.32; we ask students to develop a multimedia version of this system later
in the book.
Chapter 5Arraysexplores
the processing of data in lists and tables of values. Arrays in Java are
processed as objects, further evidence of Java's commitment to almost 100%
object-orientation. We discuss the structuring of data into arrays, or
groups, of related data items of the same type. The chapter presents
numerous examples of both single-subscripted arrays and double-subscripted
arrays. It is widely recognized that structuring data properly is just as
important as using control structures effectively in the development of
properly structured programs. Examples in the chapter investigate various
common array manipulations, printing histograms, sorting data, passing
arrays to functions and an introduction to the field of survey data
analysis (with simple statistics). A feature of this chapter is the
discussion of elementary sorting and searching techniques and the
presentation of binary searching as a dramatic improvement over linear
searching. The 44 end-of-chapter exercises include a variety of
interesting and challenging problems such as improved sorting techniques,
the design of an airline reservations system, an introduction to the
concept of turtle graphics (made famous in the LOGO programming language)
and the Knight's Tour and Eight Queens problems that introduce the notions
of heuristic programming so widely employed in the field of artificial
intelligence. The exercises conclude with a series of recursion problems
including the selection sort, palindromes, linear search, binary search,
the eight queens, printing an array, printing a string backwards and
finding the minimum value in an array. The chapter exercises include a
delightful simulation of the classic race between the tortoise and the
hare, card shuffling and dealing algorithms, recursive quicksort and
recursive maze traversals. A special section entitled "Building Your
Own Computer" explains machine language programming and proceeds with
the design and implementation of a computer simulator that allows the
reader to write and run machine language programs. This unique feature of
the text will be especially useful to the reader who wants to understand
how computers really work. Our students enjoy this project and often
implement substantial enhancements; many enhancements are suggested in the
exercises. In Chapter 17, another special section guides the reader
through building a compiler; the machine language produced by the compiler
is then executed on the machine language simulator produced in Chapter 5.
Information is communicated from the compiler to the simulator in
sequential files (which the students will master in Chapter 15).
Chapter
6Object-Based Programmingbegins our deeper discussion of
classes. The chapter represents a wonderful opportunity for teaching data
abstraction the "right way"through a language (Java)
expressly devoted to implementing abstract data types (ADTs). The chapter
focuses on the essence and terminology of classes and objects. What is an
object? What is a class of objects? What does the inside of an object look
like? How are objects created? How are they destroyed? How do objects
communicate with one another? Why are classes such a natural mechanism for
packaging software as reusable componentry? The chapter discusses
implementing ADTs as Java-style classes, accessing class members,
enforcing information hiding with private instance
variables, separating interface from implementation, using access methods
and utility methods, initializing objects with constructors (and using
overloaded constructors). The chapter discusses declaring and using
constant objects, compositionthe process of building classes that have
references to objects as members, the this reference that
enables an object to "know itself," dynamic memory allocation,
static class members for containing and manipulating class-wide data and
examples of popular abstract data types such as stacks and queues. The
chapter exercises challenge the student to develop classes for complex
numbers, rational numbers, times, dates, rectangles, huge integers, a
class for playing Tic-Tac-Toe, a savings account class and a class for
holding sets of integers.
Chapter
7Object-Oriented Programmingdiscusses the relationships among
classes of objects and programming with related classes. How can we
exploit commonality between classes of objects to minimize the amount of
work it takes to build large software systems? What is polymorphism? What
does it mean to "program in the general" rather than
"programming in the specific?" How does programming in the
general make it easy to modify systems and add new features with minimal
effort? How can we program for a whole category of objects rather than
programming individually for each type of object? The chapter deals with
one of the most fundamental capabilities of object-oriented programming
languages, inheritance, which is a form of software reusability in which
new classes are developed quickly and easily by absorbing the capabilities
of existing classes and adding appropriate new capabilities. The chapter
discusses the notions of superclasses and subclasses, protected
members, direct superclasses, indirect superclasses, use of constructors
in superclasses and subclasses, and software engineering with inheritance.
The chapter compares inheritance ("is a" relationships) with
composition ("has a" relationships). A feature of the chapter is
its several substantial case studies. In particular, a lengthy case study
implements a point, circle and cylinder class hierarchy. The exercises ask
the student to compare the creation of new classes by inheritance vs.
composition; to extend the inheritance hierarchies discussed in the
chapter; to write an inheritance hierarchy for quadrilaterals, trapezoids,
parallelograms, rectangles and squares; and to create a more general shape
hierarchy with two-dimensional shapes and three-dimensional shapes. The
chapter explains polymorphic behavior. When many classes are related
through inheritance to a common superclass, each subclass object may be
treated as a superclass object. This enables programs to be written in a
general manner independent of the specific types of the subclass objects.
New kinds of objects can be handled by the same program, thus making
systems more extensible. Polymorphism enables programs to eliminate
complex switch logic in favor of simpler
"straight-line" logic. A screen manager of a video game, for
example, can simply send a "draw" message to every object in a
linked list of objects to be drawn. Each object knows how to draw itself.
A new type of object can be added to the program without modifying that
program as long as that new object also knows how to draw itself. This
style of programming is typically used to implement today's popular
graphical user interfaces. The chapter distinguishes between abstract
classes (from which objects cannot be instantiated) and concrete classes
(from which objects can be instantiated). Abstract classes are useful for
providing an inheritable interface to classes throughout the hierarchy. A
feature of the chapter is its two major polymorphism case studiesa
payroll system and shape, point, circle, cylinder hierarchy headed up by
an abstract class. The chapter exercises ask the student to discuss a
number of conceptual issues and approaches, work with abstract classes,
develop a basic graphics package, modify the chapter's employee
classand pursue all these projects with polymorphic programming.
Chapter 8Strings
and Charactersdeals with processing words, sentences, characters
and groups of characters. The key difference between Java and C here is
that Java strings are objects. This makes string manipulation more
convenient and much safer than in C where string and array manipulations
are based on dangerous pointers. We present classes String,
StringBuffer, Character and StringTokenizer.
For each we provide extensive live-code examples demonstrating most of
their methods "in action." In all cases we show output windows
so the reader can see the precise effects of each of the string and
character manipulations we discuss. Students will enjoy the card shuffling
and dealing example (which they will enhance in the exercises to the later
chapters on graphics and multimedia). A key feature of the chapter is an
extensive collection of challenging string manipulation exercises related
to limericks, pig Latin, text analysis, word processing, printing dates in
various formats, check protection, writing the word equivalent of a check
amount, Morse Code and metric-to-English conversions. Students will enjoy
the challenges of developing their own spell checker and crossword puzzle
generator.
Advanced Topics
Chapters 9, 10 and 11 were co-authored
with our colleague, Mr. Tem Nieto of Deitel & Associates, Inc. Tem's
infinite patience, attention to detail, illustration skills and creativity
are apparent throughout these chapters. [Take a fast peek at Figure 10.27
to see what happens when we turn Tem loose!]
Chapter
9Graphicsbegins a run of chapters that present the multimedia
"sizzle" of Java. We consider Chapters 9 through 18 to be the
book's advanced material. Professors who have been teaching C and/or C++
at the introductory level will find that the Java topics open all kinds of
opportunities to explore new areas. This is "fun stuff."
Traditional C and C++ programming are pretty much confined to
character-mode input/output. Some versions of C++ are supported by
platform-dependent class libraries that can do graphics, but using these
libraries makes your applications nonportable. Java's graphics
capabilities are platform independent and hence, portableand we mean
portable in a worldwide sense. You can develop graphics-intensive Java
applets and distribute them over the World Wide Web to colleagues
everywhere and they will run nicely on the local Java platforms. We
discuss graphics contexts and graphics objects; drawing strings,
characters and bytes; color and font control; screen manipulation and
paint modes; and drawing lines, rectangles, rounded rectangles,
3-dimensional rectangles, ovals, arcs and polygons. The chapter has 39
figures that painstakingly illustrate each of these graphics capabilities
with live-code examples, appealing screen outputs, detailed features
tables and detailed line art. Some of the 33 exercises challenge students
to develop graphical versions of their solutions to previous exercises on
Turtle Graphics, the Knight's Tour, the Tortoise and the Hare simulation,
Maze Traversal and the Bucket Sort.
Chapter 10Basic
Graphical User Interface Componentsintroduces the creation of
applets and applications with user-friendly graphical user interfaces
(GUIs). Once again, the key to Java's treatment of these subjects is that
Java is platform independent. A GUI-based applet or application developed
once will run on all Java platforms. Actually, the user interface
components will appear a bit different on each platform, because Java
"ties into" the local GUI system, be it Microsoft's Windows,
Apple's Macintosh, Motif, Sun's OpenWindows, OS/2's Warp or any other
system. So Java applications running on a platform with which you are
familiar will take on the appearance of GUI applications running on that
platform. GUI development is a huge topic, so we divided into two
chapters. These chapters truly cover the material in depth to enable you
to build "industrial-strength" GUI interfaces. Through its 49
programs, tables and line drawings, the chapter illustrates GUI design
principles, the java.awt (Abstract Windowing Toolkit)
hierarchy, labels, push buttons, lists, text fields, choice buttons, check
boxes, radio buttons, panels, handling mouse events, handling keyboard
events and using three of Java's simpler GUI layout managers, namely FlowLayout,
BorderLayout and GridLayout. The 26
exercises challenge the student to create specific GUIs, exercise various
GUI features, develop drawing programs that let the user draw with the
mouse and control fonts.
Chapter 11Advanced
Graphical User Interface Componentscontinues the discussion started
in Chapter 10. Here, we continue the detailed walkthrough of Java's GUI
capabilities. The 30 figures walk the reader through the creation and
manipulation of more advanced GUI components including text areas,
canvases, scrollbars, custom components, frames, menus and dialog boxes.
The chapter concludes with discussions of Java's more sophisticated layout
managers, namely CardLayout and GridBagLayout,
and shows how to develop custom layout mangers. The exercises encourage
the reader to develop more substantial GUIs with the advanced components
presented in the chapter.
Chapter
12Exception Handlingis one of the most important chapters in the
book from the standpoint of building so-called
"mission-critical" or "business-critical" applications
that require high degrees of robustness and fault tolerance. Things do go
wrong, and at today's computer speedscommonly 100 million operations
per secondif they can go wrong they will, and rather quickly at that.
Programmers are often a bit naive about using components. They ask,
"How do I request that a component do something for me?" They
also ask "What value(s) does that component return to me to indicate
it has performed the job I asked it to do?" But programmers also need
to be concerned with, "What happens when the component I call on to
do a job experiences difficulty? How will that component signal that it
had a problem?" In Java, when a component (i.e., a class object)
encounters difficulty, it can "throw an exception." The
environment of that component is programmed to "catch" that
exception and deal with it. Java's exception handling capabilities are
geared to an object-oriented world in which programmers construct systems
largely from reusable, prefabricated components built by other
programmers. To use a Java component, you need to know not only how that
component behaves when "things go well," but also what
exceptions that component throws when "things go poorly." The
chapter distinguishes between rather serious system Errors
(normally beyond the control of most programs) and Exceptions
that programs generally want to deal with to ensure robust operation. The
chapter discusses the vocabulary of exception handling. The try
block executes program code that may execute properly or may throw
an exception if something goes wrong. Associated with each try
block are one or more catch blocks that handle thrown
exceptions attempting to restore order and keep systems "up and
running" rather than letting them "crash." Even if order
can not be fully restored, the catch blocks may perform
operations that enable a system to continue executing, albeit at reduced
levels of performancesuch activity is often referred to as
"graceful degradation." Regardless of whether exceptions are
thrown or not, a finally block accompanying a try
block will always execute; the finally block normally
performs cleanup operations like closing files and releasing resources
acquired in the try block. The chapter does contain
several nice live-code examples, but its material is more crucial to many
of the live-code examples in Chapters 13 through 18. A feature of the
chapter is the enumeration of the various Errors and Exceptions
of the various Java packages. The chapter has some of the most appropriate
quotes in the book thanks to the painstaking research performed by Barbara
Deitel. You recall that we added Testing and Debugging Tips as a new
feature to Java How to Program over the set of tips we had used in
our C and C++ books. The vast majority of these Testing and Debugging Tips
fell naturally out of the material in Chapter 12 which has 16 of the 29
mentioned in the entire text. Please take exception handling seriously.
The mechanism chosen by Java's designers is similar to that used by C++.
It is certain to be widely employed in the object-oriented programming
community.
Chapter
13Multithreadingdeals with how to program applets and
applications that can perform multiple activities in parallel. Although
our bodies are quite good at this (breathing, eating, blood circulation,
vision, hearing, etc. can all occur in parallel), our conscious minds have
trouble with this. Computers used to be built with a single rather
expensive processor. Today processors are becoming so inexpensive that it
is possible to build computers with many processors that work in
parallelsuch computers are called multiprocessors. The trend is clearly
towards computers that can perform many tasks in parallel. Most of today's
programming languages, including C and C++, do not include features for
expressing parallel operations. These languages are often referred to as
"sequential" programming languages or
"single-thread-of-control" languages. Java includes capabilities
to enable multithreaded applications, i.e., applications that can specify
that multiple activities are to occur in parallel. This makes Java better
prepared to deal with the more sophisticated multimedia, networked-based
multiprocessor-based applications programmers will be introducing in the
mid-to-late 1990s. As we will see, multithreading is even effective on
single-processor systems. This is one of the key capabilities of Java that
convinced us to invest in this language and write Java How to Program. For
years, the "old guy" taught operating systems courses and wrote
operating systems textbooks, but he never had a multithreaded language
like Java available to demonstrate the concepts. In this chapter, we
really enjoyed presenting multithreaded programs that demonstrate clearly
the kinds of problems that can occur in parallel programming. There are
all kinds of subtleties that develop in parallel programs that you simply
never think about when writing sequential programs. A feature of the
chapter is the extensive set of examples that show these problems and how
to solve them. Another feature is the implementation of the "circular
buffer," a popular means of coordinating control between
asynchronous, concurrent "producer" and "consumer"
processes that, if left to run without synchronization, would cause data
to be lost and/or duplicated incorrectly, most likely with devastating
results. We discuss the monitor construct developed by C. A. R. Hoare and
implemented in Java; this is a standard topic in operating systems
courses. The chapter discusses threads and thread methods. It walks
through the various thread states and state transitions with a detailed
line drawing showing the life-cycle of a thread. We discuss thread
priorities and thread scheduling and use a line drawing to show Java's
fixed-priority scheduling mechanism. We examine a producer/consumer
relationship without synchronization, observe the trouble it causes and
then solve the problem with thread synchronization. We implement a
producer/consumer relationship with a circular buffer and proper
synchronization with a monitor. We discuss daemon threads that kind of
"hang around" and do useful work (like "garbage
collection" of discarded memory) when excess processor time is
available. We discuss the Runnable interface that enables
you to run objects as threads without having to subclass them from class Thread
and we indicate that the notion of "interface" is Java's
replacement for the dangerous (albeit powerful) feature of C++ called
multiple inheritance. We close with a discussion of thread groups which,
for example, enable separation to be enforced between system threads like
the garbage collector and user threads. The chapter has a nice complement
of 26 exercises. The featured exercise is the classic readers and writers
problem, a favorite in upper-level computer science courses in operating
systems; citations appear in the exercises for students who wish to
research this topic. This is an important problem in database-oriented
transaction-processing systems. It raises subtle issues of solving
problems in concurrency control while ensuring that every separate
activity that needs to receive service does indeed do so without the
possibility of "indefinite postponement" which could cause some
activities never to receive servicea condition also referred to as
"starvation." Operating systems professors will enjoy having
Java-literate students. We can expect all kinds of progress in the field
of parallel programming as Java's multithreading capabilities enable large
numbers of computing students to pursue parallel-programming class
projects. When these students enter industry over the next several years,
we expect a surge in parallel systems programming and parallel
applications programming. We have been predicting this for decadesJava
will make it a reality.
If this is your first
Java book and you are an experienced computing professional, you may well
be thinking, "Hey, this just keeps getting better and better. I can't
wait to get started programming in this language. It will let me do all
kinds of stuff I'd like to do, but that was never easy for me to do with
the other languages I've used." You've got it right. Java is an
enabler. So if you liked the multithreading discussion, hold onto your
hat, because Java will let you program multimedia applications and make
them available instantaneously over the World Wide Web. Chapter
14Multimedia: Images, Animation and Audiodeals with Java's
capabilities for making computer applications come alive. It is remarkable
that students in first programming courses will be writing applications
with all these capabilities. The possibilities are intriguing. Imagine
having access (over the Internet and through CD-ROM technology) to vast
libraries of graphics images, audios and videos and being able to weave
your own together with those in the libraries to form creative
applications. Already more than half the new computers sold come
"multimedia equipped." Within just a few years, new machines
equipped for multimedia will be as common as machines with floppy disks
today. We can't wait to see the kinds of term papers and classroom
presentations students will be making when they have access to vast public
domain libraries of images, drawings, voices, pictures, videos, animations
and the like. A "paper" when most of us were in the earlier
grades was a collection of characters, possibly handwritten, possibly
typewritten. A "paper" in just a few short years will become a
multimedia "extravaganza" that makes the subject matter come
alive. It will hold your interest, pique your curiosity, make you feel
what the subjects of the paper felt when they were making history.
Multimedia will make your science labs much more exciting. Textbooks will
come alive. Instead of looking at a static picture of some phenomenon, you
will watch that phenomenon occur in a colorful, animated, presentation
with sounds, videos and various other effects. It will leverage the
learning process. People will be able to learn more, learn it in more
depth and experience more viewpoints. The chapter discusses images and
image manipulation, audios, animation, flicker elimination and the
monitoring of "media clips" with MediaTracker
objects. When we first learned Java, we decided to put a spinning Deitel
& Associates, Inc. logo up on our Web site. We enjoyed using Java's
features to do this and rapidly ran into the kinds of flicker problems
than can hurt the effectiveness of animations. We evolved a sequence of
programs that incrementally applied Java's flicker-elimination techniques.
So the programs in this chapter are genuine hands-on, real-world solutions
by real programmers solving a common problem (flicker elimination) in
multimedia applications. A feature of the chapter is the discussion of
image maps that enable a program to sense the presence of the mouse cursor
over a region of an image, even without clicking the mouse. We present a
live-code image map application with the icons Prentice Hall artists
created for our Java Multimedia Cyber Classroom programming tips.
As the user moves the mouse cursor across the six icon images of our bug
character, the type of tip is displayed, either "Good Programming
Practice" for the thumbs-up icon, "Portability Tip" for the
bug with the suitcase icon, and so on. Once you have read the chapter, you
will be eager to try out all these techniques, so we have included 67 (!)
problems to challenge and entertain you. Here are the exercises that you
may want to turn into term projects:
- 15 Puzzle
- Analog Clock
- Arithmetic Tutor
- Artist
- Automated Teller Machine
- Background Audio
- Bubble Help
- Calendar/Tickler File
- Calling Attention to an Image
- Coloring B/W Photographs
- Craps
- Crossword
- Digital Clock
- Dynamic Customized Newsletter
- Dynamic Kaleidoscope
- Dynamic Stock Evaluator
- Fashion Designer
- Fireworks Designer
- Flight Simulator
- Floor Planner
- Game of Pool
- Horse Race
- Image Flasher
- Image Zooming
- Jigsaw Puzzle Generator
- Juggling Teacher
- Karaoke
- Knight's Tour Walker
- Limericks
- Maze Generator and Walker
- Multimedia Aerobics
- Multimedia Authoring System
- Multimedia Simpletron Simulator
- Music Teacher
- One-Armed Bandit
- Pendulum
- Physics Demo: Bouncing Ball Animation
- Physics Demo: Kinetics
- Pinball Machine
- Player Piano
- Random Inter-Image Transition
- Randomly Erasing an Image
- Reaction Time Tester
- Rotating Image
- Roulette
- Screensaver
- Scrolling Image Marquee
- Scrolling Test Marquee
- Sheet Music Generator/Player
- Shuffleboard
- Story Teller
- Synthesizer
- Text Flasher
- Tortoise and the Hare
- Towers of Hanoi
- Video Games
You are going to have a great time
attacking some of these problems! Some will take a few hours, some are
great term projects and some will probably seem unconquerable. We see all
kinds of opportunities for multimedia electives starting to appear in the
university computing curriculum. We really hope that you will have
contests with your classmates to develop the best solutions to several of
these problems.
Chapter 15Files
and Streamsdeals with input/output that is accomplished through
streams of data directed to and from files. This is one of the most
important chapters for programmers who will be developing commercial
applications. The chapter begins with an introduction to the data
hierarchy from bits, to bytes, to fields, to records, to files. Next,
Java's simple view of files and streams is presented. We then present a
walkthrough of the 23 classes of Java's extensive input/output files and
streams class hierarchy. We put many of these classes to work in live-code
examples in this chapter and in Chapter 16, "Networking." We
show how programs pass data to secondary storage devices like disks and
how programs retrieve data already stored on those devices.
Sequential-access files are discussed using a series of three programs
that show how to open and close files, how to store data sequentially in a
file and how to read data sequentially from a file. Random-access files
are discussed using a series of four programs that show how to
sequentially create a file for random access, how to read and write data
to a file with random access, and how to read data sequentially from a
randomly accessed file. The fourth random-access program combines many of
the techniques of accessing files both sequentially and randomly into a
complete transaction processing program. We discuss buffering and how it
helps programs that do significant amounts of input/output perform better.
We discuss class File that programs use to obtain a variety of information
about files and directories. We explain how objects can be output to, and
input from, secondary storage devices. Students in our industry seminars
have told us that after studying the material on file processing, they
were able to produce substantial file-processing programs that were
immediately useful to their organizations. The exercises ask the student
to implement a variety of programs that build and process both
sequential-access files and random-access files.
Chapter
16Networkingdeals with applets and applications that can
communicate over computer networks. What is a client? What is a server?
How do clients ask servers to perform their services? How do servers give
results back to clients? What is a URL (uniform resource locator)? How can
a Java program load other World Wide Web pages? How can I use Java to
develop collaborative applications? This chapter gives you what you need
to begin implementing client/server networked Java programs immediately.
We show how to write programs that "walk the Web." We discuss
manipulating URLs, using a URL stream connection to read a file on a
server, establishing simple clients and servers using stream sockets,
client/server interaction with stream sockets, connectionless
client/server interaction with datagrams, security and the network, and
forthcoming networking and security APIs. A key feature of the chapter is
the live-code implementation of a collaborative client/server Tic-Tac-Toe
game in which two clients play Tic-Tac-Toe with one another arbitrated by
multithreaded servergreat stuff! The multithreaded server architecture
is exactly what is used today in popular UNIX, OS/2 and Windows NT network
servers. The chapter has a nice collection of exercises including several
suggested modifications to the multithreaded server example.
Chapter 17Data
Structuresis particularly valuable in second- and third-level
university courses. The chapter discusses the techniques used to create
and manipulate dynamic data structures such as linked lists, stacks,
queues (i.e., waiting lines) and trees. The chapter begins with
discussions of self-referential classes and dynamic memory allocation. We
proceed with a discussion of how to create and maintain various dynamic
data structures. For each type of data structure, we present live-code
programs and show sample outputs. Although it is valuable to know how
these classes are implemented, Java programmers will quickly discover that
many of the data structures they need are already available in class
libraries such as Java's own java.util that we discuss in
Chapter 18. The chapter helps the student master Java-style references
(i.e., Java's replacement for the more dangerous pointers of C and C++).
One problem when working with references is that students may have trouble
visualizing the data structures and how their nodes are linked together.
So we have included illustrations that show the links and sequence in
which they are created. The binary tree example is a nice capstone for the
study of references and dynamic data structures. This example creates a
binary tree; enforces duplicate elimination; and introduces recursive
preorder, inorder and postorder tree traversals. Students have a genuine
sense of accomplishment when they study and implement this example. They
particularly appreciate seeing that the inorder traversal prints the node
values in sorted order. The chapter includes a substantial collection of
exercises. A highlight of the exercises is the special section
"Building Your Own Compiler." This exercise is based on earlier
exercises that walk the student through the development of an
infix-to-postfix-conversion program and a postfix-expression-evaluation
program. We then modify the postfix evaluation algorithm to generate
machine-language code. The compiler places this code in a file (using
techniques the student mastered in Chapter 15). Students then run the
machine language produced by their compilers on the software simulators
they built in the exercises of Chapter 5! The 34 exercises include a
supermarket simulation using queueing, recursively searching a list,
recursively printing a list backwards, binary tree node deletion,
level-order traversal of a binary tree, printing trees, writing a portion
of an optimizing compiler, writing an interpreter, inserting/deleting
anywhere in a linked list, analyzing the performance of binary tree
searching and sorting and implementing an indexed list class.
Chapter 18Java
Utilities Package and Bit Manipulationwalks through the classes of
the java.util package and discuss each of Java's bitwise
operators. This is a nice chapter for reinforcing the notion of reuse.
When classes already exist, it is much faster to develop software by
simply reusing these classes than by "reinventing the wheel."
Classes are included in class libraries because the classes are generally
useful, correct, performance tuned, portability certified and/or for a
variety of other reasons. Someone has invested considerable work in
preparing these classes so why should you write your own? We believe the
world's class libraries will grow at a phenomenal rate. If this is the
case, then your skill and value as a programmer will depend on your
familiarity with what classes exist and how you can reuse them cleverly to
develop high-quality software rapidly. University data structures courses
will be changing drastically over the next several years because most
important data structures are already implemented in widely available
class libraries. This chapter discusses many classes. Two of the most
useful are Vector (a dynamic array that can grow and
shrink as necessary) and Stack (a dynamic data structure
that allows insertions and deletions from only one endcalled the
topthus ensuring last-in-first-out behavior). The beauty of studying
these two classes is that they are related through inheritance as
discussed in Chapter 7, so the java.util package itself
implements some classes in terms of others thus avoiding reinventing that
wheel and taking advantage of reuse. We also discuss classes Dictionary,
Hashtable, Date, Observable,
Observer (actually an interface), Properties
(for creating and manipulating persistent Hashtables), Random
and BitSet. The discussion of BitSet
include live code for one of the classic applications of BitSets,
namely the Sieve of Eratosthenes used for determining prime numbers. The
chapter discusses in detail Java's powerful bit manipulation capabilities
that enable programmers to exercise lower-level hardware capabilities.
This helps programs process bit strings, set individual bits on or off and
store information more compactly. Such capabilitiesinherited from
Care characteristic of low-level assembly languages and are valued by
programmers writing system software such as operating systems and
networking software. The chapter concludes with 19 exercises.
Appendix AJava
Demospresents a huge collection of the best Java demos Abbey Deitel
was able to track down on the Web. Many of these sites make their source
code available to you, so you can download the code and add your own
featuresa truly great way to learn Java! We encourage our students to
do this and we're amazed at the results! Abbey has requested that you send
her the URLs of your favorite sites that you would like to share with
others. Please write to Abbey c/o deitel@deitel.com.
She will put links to them in our "Best Java Demos" list on our
Web sites. You should start your search by checking out Gamelan's treasure
trove at http://www.gamelan.com.
You can save time finding the best demos by checking out the Java Applet
Rating Service at http://www.jars.com.
Here's a list of Abbey's current recommendations (the URLs and
descriptions of each are in Appendix A):
- Angry Fish
- Animated Netscape Logo
- Animated SDSU Logo
- Animation
- ASTERNOID!
- Ataxx Game
- Audio Files
- Black Jack
- Celebrity Painter
- Centipedo
- Chat
- Chess
- Cool Beans Java Programming
- Connect4
- Crazy Counter
- Dethtris Game by Ultramaster
- Drive a Tank
- Featured Games of the Week
- 15 Puzzle
- Froggie
- Graffitti
- Iceblox Game
- Java Piano
- Java Slider
- Jigsaw Puzzle
- Knights Tour
- Marble Solitaire Game
- Mazda Miata Animation
- Missile Commando
- Mr. Potato Head
- Pong
- Rubiks Cube
- San Francisco Subway Map
- Santas Jolly Laughter
- Slot Machine
- Solitaire
- Starbase
- Stereoscopic 3D Hypercube
- Tennis
- 3-D Cube
- Traffic Simulation
- 3D Tetris
- Video Movie Clips
- Visible Human Body Sections
Appendix BJava
Resourcespresents the best resources Abbey was able to track down
on the Web. This is a great way for you to get into the "world of
Java." The appendix lists various Java resources (such as consortia,
journals and companies that make various key Java-related products).
- animated applets
- applets
- applications
- arts and entertainment
- audio sites
- books
- Café Del Sol Java resource
- Candle Web (links to Java sites)
- class hierarchy diagrams
- class libraries
- conferences
- consultants
- contests
- current information
- databases
- demos (many with source code)
- developers kit
- development tools
- Digital Espresso (resources)
- discussion groups
- software
- Sun Microsystems
- SunWorld magazine online
- "The Java Developer"
- trade shows
- training (please call us!)
- tutorial called "Brewing Java"
- documentation
- downloadable applets
- examples
- events
- exercises
- FAQs (frequently asked ?s)
- Gamelan (3000 java resources)
- games
- graphics
- hottest new Java sites
- Hot Java documentation
- HotJava newsgroup
- IDEs
- information
- Java Applet Rating Service
- java@java.sun.com (get
help)
- JavaSoft
- Java tools
- Java Users Group (JUGs)
- Java World magazine
- tutorials for learning java
- URLs for Java applets
- user interface
- utility classes
- video sites
- Yahoo (Web search engine)
- VRML (Virtual Reality)
- learning Java
- links to Java sites
- lists of resources
- lists of what is new and cool
- live chat sessions on Java
- mailing lists
- message exchange center
- news
- news:comp.lang.java
- newsgroups
- newsletters
- products
- projects
- publications
- puzzles
- reference materials
- resources
- search for applets by keywords
- seminars
- sites
- VRML browsers
- VRML sites
- VRML 3D graphics animations
- www.gamelan.com
- www.javasoft.com
- www.javaworld.com
Appendix COperator
Precedence Chartlists each of the Java operators and indicates
their relative precedence and associativity. We list each operator on a
separate line and include the full name of the operator.
Appendix DASCII
Character Setlists the characters of the ASCII (American Standard
Code for Information Interchange) character set and indicates the
character code value for each. Java uses the Unicode character set with
16-bit characters for representing all of the characters in the world's
"commercially significant" languages. Unicode includes ASCII as
a subset. Currently, most English-speaking countries are using ASCII and
just beginning to experiment with Unicode. We will say more about Unicode
in the Second Edition of Java How to Program.
Appendix ENumber
Systemsdiscusses the binary (base 2), decimal (base 10), octal
(base 8) and hexadecimal (base 16) number systems. This material is
valuable for introductory courses in computer science and computer
engineering. The appendix is presented with the same pedagogic learning
aids as the chapters of the book. A nice feature of the appendix is its 32
exercises, 19 of which are self-review exercises with answers.
Appendix
FObject-Oriented Elevator Simulatorwalks the student through a
carefully paced and substantial term project. The appendix begins with a
simple introduction to object-oriented thinking so the instructor can
assign the elevator case study in parallel with the early chapters of the
book. These sections introduce the concepts and terminology of object
orientation to help students become familiar with what objects are and how
they behave. Next we present a requirements specification for a
substantial object-oriented system project, namely building the elevator
simulator, and we carefully guide the student through the typical phases
of the object-oriented design process. By the time the student has
finished the early assignments, he or she has completed a careful
object-oriented design of the elevator simulator and is readyif not
anxiousto begin programming the elevator in Java. This appendix forms
the basis of a carefully paced term project that many instructors will
choose to assign. A complete, multimedia-based implementation of the
elevator with graphics, animation and audios is in the Instructor's Manual
(that even has the elevator play "elevator music" when it's
moving between floors!).
This appendix is one of the most important
components of the Java How to Program learning experience. It is
intended as a term project for intense first programming courses and for
most second-level programming courses. We have divided the appendix into
12 carefully paced assignments that enable the student to develop the
elevator in parallel with reading the appropriate chapters of the
textbook. Section F.1 begins with an introduction to object orientation.
We will see that object orientation is a natural way of thinking about the
world and writing computer programs. Section F.2 presents the elevator
"requirements document" that describes the elevator in
sufficient detail for the student to begin the design process.
In Elevator Assignment 1 (Prerequisites:
Chapters 13) the student begins the object-oriented design process by
identifying the classes in the requirements document. Classes have
attributes and behaviors. Class attributes are represented in Java
programs by data.
In Elevator Assignment 2 (Prerequisite:
Chapter 4) the student concentrates on determining the attributes of the
classes needed to implement the elevator simulator. In Elevator
Assignment 3 (Prerequisite: Chapter 6) we concentrate on determining
the behaviors of the classes needed to implement the elevator simulator.
Behaviors are implemented in Java as methodsJava's term for the member
functions with which C++ programmers are familiar.
Elevator Assignment 4 (Prerequisite:
Chapter 6) concentrates on the interactions between class objects.
In Elevator Assignment 5 (Prerequisite:
Chapter 6) you begin programming the elevator simulator. For each of the
classes you identified in the previous assignments, you write an
appropriate class definition. Each class definition is written in a
separate file with the.java extension. You then write a "driver"
applet that tests each of these classes and attempts to run the complete
elevator simulation. For this first version of the simulator, you design
only a simple, text-oriented output that displays a message for each
significant event that occurs.
Elevator Assignment 6 (Prerequisite:
Chapter 6) discusses composition, a capability that allows you to create
classes that have as members references to objects. Composition enables
you to create a building class that contains references to the elevator
and to the floors, and, in turn, create an elevator class that contains
references to buttons.
Elevator Assignment 7 (Prerequisites:
Chapters 911) focuses on enhancing the elevator's graphical user
interface.
Elevator Assignment 8 (Prerequisites:
Chapters 911) builds on the GUI you developed in Assignment 7; you will
add to the GUI and begin graphically representing the events occurring in
your simulation.
Elevator Assignment 9 (Prerequisite:
Chapter 13) covers the steps necessary to provide interaction between the
GUI and events generated by your simulator. The interaction in many cases
will be done with multithreading.
Elevator Assignment 10 (Prerequisite:
Chapter 13) covers the steps necessary to provide animation for your
simulator.
Elevator Assignment 11 (Prerequisite:
Chapter 14) covers the steps necessary to provide additional animation as
well some audio for your simulator.
Elevator Assignment 12 (Prerequisite:
Chapter 14) enhances the animation of the previous assignment.
In Section F.15 we list nine
significant modifications that can be made to your elevator simulator;
some of these require the data structures techniques of Chapters 17 and
18.
The Java
Multimedia Cyber Classroom
We have implemented an interactive,
CD-ROM-based, Windows version of Java How to Program called the Java
Multimedia Cyber Classroom. It is loaded with features for learning
and reference. The Cyber Classroom is available separately from the
textbook, and is available wrapped with the textbook at a discount.
There is an introductory video with the
authors overviewing the Cyber Classroom's features. The 200 live-code
example Java programs in the textbook truly "come alive" in the
Cyber Classroom. We have placed executables for all these examples
"under the hood" of the Cyber Classroom, so if you are viewing a
program and want to execute it, you simply click on the lightning bolt
icon and the program will run. You will immediately seeand hear for the
audio-based multimedia programsthe program's outputs. If you want to
modify a program and see and hear the effects of your changes, simply
click on the floppy-disk icon that causes the source code to be
"lifted off" the CD and "dropped into" one of your own
directories so you can edit the text, recompile the program and try out
your new version. Click on the audio icon and Paul Deitel will talk about
the program and "walk you through" the code. [You will not hear
Harvey Deitel's voice in these audiosour friends at Prentice Hall like
Paul's voice better!]
The Cyber Classroom also provides all kinds
of navigational aids including extensive hyperlinking. The Cyber Classroom
remembers in a "history list" recent sections you have visited
and allows you to move forward or backward in that history list. The
thousands of index entries are hyperlinked to their text occurrences. You
can key in a term and the Cyber Classroom will locate its occurrences
throughout the text. The Table of Contents entries are "hot," so
clicking on a chapter name immediately takes you to that chapter. You can
insert "bookmarks" at places to which you may want to return.
You can even add "notes" just as you would in the margin of a
textbook.
Students and professional users of our
Cyber Classrooms tell us they like the interactivity and that the Cyber
Classroom is an effective reference because of the extensive hyperlinking
and other navigational features. We recently had an email from a person
who said that he lives "in the boonies" and can not take a live
course at a university, so the Cyber Classroom was the solution to his
educational needs.
Professors have sent us emails indicating
their students enjoy using the Cyber Classroom, spend more time on the
course and master more of the material than in textbook only courses.
Also, the Cyber Classroom helps shrink lines outside professors' offices
during office hours. We have published the C & C++ Multimedia Cyber
Classroom and hope to publish Cyber Classroom editions of our
forthcoming Visual Basic How to Program and Visual C++ How to
Program textbooks.
Acknowledgments
One of the great pleasures of writing a
textbook is acknowledging the efforts of many people whose names may not
appear on the cover, but whose hard work, cooperation, friendship, and
understanding were crucial to the production of the book.
Three other people at Deitel &
Associates, Inc. devoted long hours to this project. We would like to
acknowledge the efforts of Tem Nieto, Barbara Deitel and Abbey Deitel.
Tem Nieto, a graduate of the Massachusetts
Institute of Technology, is one of our full-time colleagues at Deitel
& Associates, Inc. Tem teaches C, C++ and Java seminars and works with
us on textbook writing, course development and multimedia authoring
efforts. He is co-authoring our next book, Visual Basic How to Program.
Tem co-authored Chapters 9, 10 and 11; Appendix F on the object-oriented,
multimedia-based elevator simulator project and the Special Section
entitled "Building Your Own Compiler" in Chapter 17.
Barbara Deitel managed the preparation of
the manuscript and coordinated with Prentice Hall all the efforts related
to production of the book. Barbara's efforts are by far the most
painstaking of what we do to develop books. She has infinite patience. She
handled the endless details involved in publishing an 1100-page, two-color
book; a 500-page instructor's manual and the 650 megabyte CD Cyber
Classroom. She used FrameMaker page-layout software to prepare the book.
Barbara mastered this complex software package and did a marvelous job
giving the book its clean style. She spent several months researching the
quotes that appear at the beginning of each chapter. Barbara prepared
every one of the 7824 page references in the 45-page index. She did all of
this in parallel with handling her extensive responsibilities at Deitel
& Associates, Inc.
Abbey Deitel, a recent graduate of Carnegie
Mellon University's industrial management program, and now pursuing a
management career in fashion and retailing, wrote Appendix A, "Java
Demos," and Appendix B, "Java Resources" and suggested the
title for the book. We asked Abbey to surf the World Wide Web and track
down the best Java sites. She didn't have to go far. She immediately
discovered Gamelan, a wonderful site that at the time of this writing
already listed approximately 3000 significant Java resources including
many nice demos. She used every major Web search engine and collected this
information for you in Appendices A and B. For each resource and demo,
Abbey has provided a brief explanation. She rejected hundreds of sites and
has listed for you the best she could find. Abbey will be maintaining
current versions of these resources and demo listings on our Web sites http://www.prenhall.com/deitel
and http://www.deitel.com.
She asks that you send URLs for your favorite sites to her by email at deitel@deitel.com Abbey
Deitel, a recent graduate of Carnegie
Mellon University's industrial management program, and now pursuing a
management career in fashion and retailing, wrote Appendix A, "Java
Demos," and Appendix B, "Java Resources" and suggested the
title for the book. We asked Abbey to surf the World Wide Web and track
down the best Java sites. She didns bossone of the best friends we've ever had in publishingMarcia
Horton, Vice President and Editor-in-Chief of Prentice-Hall's Engineering
and Computer Science Division. Laura Steele coordinated the complex
reviewer effort on the manuscript. Sondra Chavez served as developmental
editor and was always incredibly helpful when we needed assistanceher
ebullience and good cheer are sincerely appreciated. Camille Trentacoste
did a marvelous job as production manager.
The Java Multimedia Cyber Classroom
is being developed in parallel with Java How to Program. We
sincerely appreciate the multimedia insight, savvy and technical expertise
of our editor Mark Taub. He did a remarkable job bringing Prentice Hall's
first multimedia textbook, the C & C++ Multimedia Cyber Classroom, to
publication under a tight schedule. We also want to thank Logan Campbell,
President of the Prentice Hall Professional and Technical Reference
Division, for his trust and confidence in us, and for making impressive
resources available to our projects. Logan, too, is one of the best
friends we've had in publishing.
We owe special thanks to the creativity of
Tamara Newnam who did the art work for our programming tips icons and the
cover. She created the delightful creature who shares with you the book's
programming tips. Please help us name this endearing little bug. Some
early suggestions: D. Bug, InterGnat, DeetleBug (an unfortunate moniker
that was attached to the old guy in high school) and the "drunk bug
on the cover."
We sincerely appreciate the efforts of our
reviewers:
- Peter Jones (JavaSoft)
- Ian Smith (Georgia Institute of
Technology)
- Jim Roberts (Carnegie-Mellon University)
- Andrew M. Brown (Bell Laboratories)
- Gordon Bradley (Naval Postgraduate
School)
- Richard Enbody (Michigan State
University)
- Ken Merson (Borland)
- Mark Ellis (Reuters)
Under an impossibly tight time schedule,
they scrutinized every aspect of the text and made countless suggestions
for improving the accuracy and completeness of the presentation.
We would sincerely appreciate your
comments, criticisms, corrections, and suggestions for improving the text.
Please send your suggestions for improving and adding to our list of Good
Programming Practices, Common Programming Errors, Testing and Debugging
Tips, Performance Tips, Portability Tips, and Software Engineering
Observations. We will acknowledge all contributors in the next edition of
our book. Please address all correspondence to our email address:
or write us as follows:
- Harvey M. Deitel (author)
Paul J. Deitel (author)
c/o Computer Science Editor
College Book Editorial
Prentice Hall
1 Lake Street
Upper Saddle River, New Jersey 07458
We will respond immediately. Well, that's
it for now. Welcome to the new and exciting world of Java programming. We
hope you enjoy this look at contemporary applications development using
the Internet, the World Wide Web, multimedia and multithreading. Good
luck!
Dr. Harvey M. Deitel
Paul J. Deitel
About the Authors
Dr. Harvey M. Deitel, CEO of Deitel &
Associates, Inc., has 35 years experience in the computing field including
extensive industry and academic experience. He is one of the world's
leading computer science instructors and seminar presenters. Dr. Deitel
earned B.S. and M.S. degrees from the Massachusetts Institute of
Technology and a Ph.D. from Boston University. He worked on the pioneering
virtual memory operating systems projects at IBM and MIT that developed
techniques widely implemented today in systems like UNIX, OS/2, and
Windows NT. He has 20 years of college teaching experience including
earning tenure and serving as the Chairman of the Computer Science
Department at Boston College. He is author or co-author of more than a
dozen books and is currently writing five more. With translations
published in Japanese, Russian, Spanish, Chinese, Korean, and French, Dr.
Deitel's texts have earned international recognition.
Paul J. Deitel, Executive Vice President of
Deitel & Associates, Inc., is a graduate of the Massachusetts
Institute of Technology's Sloan School of Management where he received a
B.S. in Management with a specialization in Information Technology.
Through Deitel & Associates, Inc. he has delivered Java, C and C++
courses for industry clients including Digital Equipment Corporation, Sun
Microsystems, Rogue Wave Software, Software 2000, Computervision,
Cambridge Technology Partners, Open Environment Corporation, One Wave,
Hyperion Software, Lucent Technologies, Adra Systems, Entergy, CableData
Systems and IBM. He has lectured on C++ for the Boston Chapter of the
Association for Computing Machinery and will be delivering intermediate
and advanced Java courses at the C++ World conference presented by SIGS
Publications. He teaches Java internationally. He is the co-author of nine
books with Harvey Deitel and is currently writing five more.
The Deitels are co-authors of the world's
best-selling introductory college computer science textbooks, C How to
Program: Second Edition and C++ How to Program (both
published in 1994 by Prentice Hall). The Deitels are also co-authors of
the C
& C++ Multimedia Cyber ClassroomPrentice
Hall's first multimedia-based textbookand the forthcoming Java
Multimedia Cyber Classroom.
About Deitel & Associates, Inc.
Deitel & Associates, Inc. is an
internationally recognized firm specializing in programming languages and
object technology education. The company provides courses on Java, C++, C,
Visual Basic, and Object-Oriented Analysis and Design. The principals of
Deitel & Associates, Inc. are Dr. Harvey M. Deitel and Paul J. Deitel.
The company's clients include some of the world's largest computer
companies and business organizations. Through its publishing partnership
with Prentice Hall, Deitel & Associates, Inc. publishes leading-edge
programming textbooks, professional books and interactive, CD-ROM based
multimedia Cyber Classrooms.
Deitel & Associates, Inc. can be
reached via email at deitel@deitel.com
To learn more about Deitel &
Associates, Inc. and its on-site course curriculum, visit: http://www.deitel.com
To learn more about Deitel & Deitel
Prentice Hall publications, visit: http://www.prenhall.com/deitel
|