Object Oriented Design and Patterns 2nd Edition Cay S. Horstmann - Download the ebook now to never miss important content
Object Oriented Design and Patterns 2nd Edition Cay S. Horstmann - Download the ebook now to never miss important content
com
https://ebookgate.com/product/object-oriented-design-and-
patterns-2nd-edition-cay-s-horstmann/
OR CLICK BUTTON
DOWLOAD EBOOK
https://ebookgate.com/product/python-for-everyone-2nd-edition-cay-
horstmann/
ebookgate.com
https://ebookgate.com/product/python-for-everyone-1st-edition-cay-s-
horstmann/
ebookgate.com
https://ebookgate.com/product/actionscript-3-0-design-patterns-object-
oriented-programming-techniques-1st-ed-edition-william-sanders/
ebookgate.com
https://ebookgate.com/product/java-concepts-late-objects-3rd-edition-
edition-cay-s-horstmann/
ebookgate.com
https://ebookgate.com/product/object-oriented-oracle-wenny-rahayu/
ebookgate.com
https://ebookgate.com/product/object-oriented-analysis-and-design-
understanding-system-development-with-uml-2-0-first-edition-mike-
odocherty/
ebookgate.com
https://ebookgate.com/product/the-principles-of-object-oriented-
javascript-zakas/
ebookgate.com
https://ebookgate.com/product/c-design-patterns-and-derivatives-
pricing-2nd-edition-m-s-joshi/
ebookgate.com
Obj ect .. Oriented
Design
&
Patterns
Second Edition
Cay Horstmann
San Jose State University
@
WILEY
This book was set in Adobe Caslon by Publishing Services and printed and bound by Malloy,
Inc. The cover was printed by Phoenix Color Corporation.
Copyright © 2006 John Wiley & Sons, Inc. All rights reserved.
No part of this publication may be reproduced, stored in a retrieval system, or transmitted in
any form or by any means, electronic, mechanical, photocopying, recording, scanning, or oth
erwise, except as permitted under Section 107 or 108 of the 1976 United States Copyright
Act, without either the prior written permission of the Publisher, or authorization through
payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood
Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher
for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc.,
111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008.
To order books or for customer service, please call 1-800-CALL-WILEY (225-5945).
ISBN 978-0-471-74487-0
Printed in the United States of America
10 9 8 7 6 5
Preface
Making Obj e c t,Oriented D e s ign Accessible
This book is an introduction to object-oriented design and design patterns at an
elementary level. It is intended for students with at least one semester of program
ming in an object-oriented language such as Java or C++.
I wrote this book to solve a common problem. When students first learn an
object-oriented programming language, they cannot be expected to instantly mas
ter object-oriented design. Yet, students should learn the principles of object-ori
ented design early enough to put them to work throughout the computer science
curriculum.
This book is suitable for a second or third course in computer science-no back
ground in data structures is required, and students are not assumed to have experi
ence with developing large software systems. Alternatively, the book can be used
as a companion text in a course in software engineering. (If you need a custom
version of this book for integration into another course, please contact your Wiley
sales representative.)
This second edition is fully updated for Java 5.0, including
• the use of generic collections and the "for each" loop
• a detailed discussion of parameterized type constraints
• auto-boxing and varargs methods, particularly in the reflection API
• multithreading with the j ava . uti 1 . concu r rent package
Without memorable examples, design patterns are just words. In order to visualize
design patterns, this book uses examples from graphical user interface programming.
Students will remember how a component is decorated by scroll bars, and how layout
managers carry out different strategies. (A small and carefully selected subset of Swing is
used for this purpose.)
1. Object-oriented design
• A simple design methodology
• CRC cards and UML diagrams
• Design patterns
2. Advanced Java language
• Interface types, polymorphism, and inheritance
• Inner classes
• Reflection
• Generic types
• Multithreading
• Collections
3. User interface programming
• Building Swing applications
• Event handling
• Java 2D graphics programming
These skills clearly form a useful foundation for advanced computer science courses. In
fact, students who have completed this book will have encountered all features of the Java
language (but not, of course, the entire standard Java library, which is too huge for any
one person to master). One advantage of using Java is indeed that students can compre
hend the entire language. Contrast that with C++, a language that is so complex that
virtually no one can truthfully claim to understand all of its subdeties.
In summary: Use this book if you want your students to understand object-oriented
design and design patterns early in the curriculum. As a bonus, your students will gain a
complete overview of the Java language, and they will be able to program simple Swing
user interfaces.
environment, the Java culture has embraced the use of different tools such as BlueJ,
j avadoc, and ]Unit. Due to the reflective nature of the Java language, there are many
interesting experimental tools. I highlight a number of them in the hope that students
will gain an interest and aptitude in evaluating and selecting tools that fit their working
style.
Students who learn object-oriented design also should become familiar with drawing
UML diagrams. An easy-to-use and no-cost tool for this purpose, the V iolet UML edi
tor, is provided for their use. Chapter 8 of this book introduces the framework on which
V iolet is based. All UML diagrams in this book were drawn with V iolet.
A Tou r o f t h e B o o k
Chapter I A Crash Course i n Java
This chapter introduces the basic syntax ofJava and can serve either as a refresher or as a
transition for students with a background in C++. Topics covered include
• Defining classes and methods
• Documentation comments
• Packages
• Exception handling
• CRC cards
• Case study
PREFACE
Chapter 8 Frameworks
This capstone chapter culminates in the development of a graph editor framework and
its specialization to a UML class diagram editor. Topics covered include
• The framework concept
• Applets as a simple framework
• The collections framework
• Application frameworks
• The graph editor framework
PREFACE
Chapter 9 Multithreading
This chapter introduces the multithreading pnmltlves of the Java language, thus
completing the students' introduction to Java language semantics. The synchronization
primitives can be challenging for students to grasp because they tightly combine several
related features. I first cover the Lock and (ondi ti on classes in the j ava . uti l . concu r
rent package, then use that background to explain the built-in locks and wait sets.
Topics covered include
• Threads and the Runnab 1 e interface type
• Interrupting threads
• Thread synchronization
• The j ava . uti l . conc ur rent package
• An application: Algorithm animation
P e da g o g i c a l S tr u c t u r e
Each chapter begins with an introduction and listing of the chapter topics. Concepts and
principles are presented in the context of programming examples, and many example
programs are printed in their entirety in the text to encourage students to read and
understand code listings. Complete source code for all of the examples in the text is
available from the book's Web site at http : //www . wi l ey . com/col l ege/horstmann (see
pages xvii-xix for a listing of the example programs that accompany this book).
Throughout the chapters, there are several kinds of special features to help your students.
These features are specially marked so they don't interrupt the flow of the main material.
Margin notes highlight important topics and help students navigate
Key concepts are highlighted
with margin notes. the core material of each chapter by highlighting where new concepts
are introduced.
Preface
1
A Crash Course in Java
(optional)
2
The Object-Oriented
Design Process
3
Guidelines for
Class Design
4 9
Interface Types and Multithreading
Polymorphism (optional)
5
Patterns and
Gill Programming
6 10
Inheritance and More Design Patterns
Abstract Classes (optional)
7.7
.-- Generic Types
(optional)
7.1-7.5 7.6
The Java Reflection -
Object Model (optional)
7.8
'-- JavaBeans Components
(optional)
8.1-8.4
I 8.5
Enhancing the Graph
Frameworks
Editor Framework (optional)
Figure 1
Special Topics introduce background material or advanced subjects that can be skipped.
Several data structures that students in a second course may not have been introduced to
are presented in these Special Topics, making them available as needed. Other Special
Topics address features of languages other than Java that relate to the design principles in
the chapter. (See page xvi for a list of these topics by chapter.)
Design Patterns are specially marked with this icon. Each design pattern is presented in a
standard format that includes the context in which the pattern is useful, the solution that
the pattern provides, and a UML diagram of the pattern elements. Most design patterns
are then followed by a table that shows students how the pattern's structure is applied to
the example discussed in that section. (See page xvi for a list of patterns by chapter.)
NOTE Notes highlight important or interesting material, such as tips or pointers for further
reading.
INTERNET Internet notes contain links to further information on the Internet, including
locations for downloadable programming tools, documentation, and articles related to chap
ter topics.
TIP Tips are used liberally throughout the text to explain good programming practices and
to help students avoid common errors.
Web R e s o u r c e s
Additional resources can be found on the book's Web site at http : //www . wi l ey . com/
col l ege/horstmann. These resources include:
• Solutions to selected exercises (accessible to students)
• Solutions to all exercises (for instructors only)
• Help with common compilers
• Presentation slides for lectures
• Source code for all examples in the book
The Vio l e t U M L E d i t o r
Students may download V iolet, an easy-to-use and no-cost UML editor, at htt p : //
ho rstmann . com/vi 01 et. V iolet was used to draw the UML diagrams in the text, so
students can use this same tool to create similar diagrams for the programs they design.
Preface
Acknowledgments
Many thanks to Bruce Spatz, Bill Zobrist, Bridget Morrisey, Catherine Shultz, Phyllis
Cerys, Ken Santor, and Lisa Gee at John Wiley & Sons for their support for this book
project.
I am very grateful to the many individuals who reviewed the manuscript, found embar
rassing errors, made valuable suggestions, contributed to the supplements, and helped
me make the book more student friendly:
Carl G. Alphonce, UniversityoJBuffalo
Bill Bane, Tarleton State University
Dwight Barnette, Virginia Polytechnic Institute and State University
Alfred Benoit, Johnson & Wales University
Richard Borie, University ojAlabama
Bruce Char, Drexel University
Chia Chen, Tuskegee University
Ashraful Chowdhury, Georgia Perimeter College
David M. Dacus, Mountain View College
Roger deBry, Utah Valley State College
Preetam Desai, UniversityojMissouri, St. Louis
Chris Dovolis, UniversityojMinnesota
Robert Duvall, Duke University
Anne B. Horton, AT&T Laboratories
Robert Kelly, State University oJNew York, Stony Brook
Walter W. Kirchherr, SanJose State University
Blayne Mayfield, Oklahoma State University
Marlene Miller
Evelyn Obaid, SanJose State University
Edward G. Okie, Radford University
Jong-Min Park, San Diego State University
Richard Pattis, Carnegie Mellon University
Hao Pham, SanJose State University
Gary Pollice, Worcester Polytechnic Institute
Saeed Rajput, Florida Atlantic University
Gopal Rao, California State University, Sacramento
Mike Rowe, Universityoj Wisconsin, Platteville
Ken Slonneger, University oJIowa
PREFACE
Glossary 427
Index 437
Photo Credits 45 1
SPECIAL FEATURES
� C o d e i n Tex t � C o m p a n i o n C od e
A Crash Course in helioworld/GreeterTester.java 3 inputllnputTester.java
Java helloworld/Greeter.java 6
� C od e i n Tex t � C om p a n i o n C od e
6 Inheritance and car/CarComponent.java 226 car/CarShape.java
Abstract Classes car/CarMover.java 227 scene1/CarShape.java
scene1/SceneComponent.java 232 scene1/HouseShape.java
scene1/SceneEditor.java 233 scene1/SceneShape.java
scene2/SelectableShape.java 238 scene1/SelectableShape.java
scene2/HouseShape.java 238 scene2/CarShape.java
scene3/CompoundShape.java 240 scene2/SceneComponent.java
scene2/SceneEditor.java
scene2/SceneShape.java
scene3/CarShape.java
scene3/CompoundShape.java
scene3/HouseShape .java
scene3/SceneComponent.java
scene3/SceneEditor.java
scene3/SceneShape.java
scene3/SelectableShape.java
A-Crasn Course
inJava
� Documentation Comments
� Primitive Types
� Object References
� Parameter Passing
� Packages
� Strings
� Reading I nput
� Arrays
� Programming Style
The purpose of this chapter is to teach you the elements of the Java
programming language-or to give you an opportunity to review them
assuming that you know an object-oriented programming language. In
CHAPTER 1 A Crash Course in Java
particular, you should be familiar with the concepts of classes and objects.
If you know C++ and understand classes, member functions, and construc
tors, then you will find that it is easy to make the switch to Java.
Mter you obtain an instance of a class, you can call (or invoke) methods on it. The call
(new Greet e r ( "Wo r l d " ) ) . sayHe11 0 0
creates a new object and causes the sayHe 1 10 method t o b e executed. The result i s the
string "He110 , Wo rl d ! , the concatenation of the strings " Hel l o , " , name, and" ! " .
"
The code that invokes a method is often called the client code. We
Object-oriented programming
follows the "client-server" think of the object as providing a service for the client.
model. The client code You often need variables to store object references that are the result
requests a service by invoking of the new operator or a method call:
a method on an object.
Greeter wo rl dGreeter new Greete r ( "Worl d " ) ;
=
II!! _=
I
Chr/helloworld/GreeterTester.java
1 __
1 publ i c cl ass Greete rTester
2 {
3 publ i c stati c voi d mai n (Stri ng [ ] args)
4 {
5 G reete r wo rl dGreeter = new G reete r ( "Wo r l d " ) ;
6 Stri ng g reeti ng = wo rl dGreete r . sayHel l o () ;
7 System . out . pri ntl n (g reeti ng) ;
8 }
9 }
This class has a rna i n method, which is required to start a Java applica
Execution of a Java program
starts with the mai n method tion. The mai n method is static, which means that it doesn't operate on
of a class. an obj ect. (We will discuss static methods-also called class meth-
ods---- i n greater detail later in this chapter.) When the application is
launched, there aren't any objects yet. It is the job of the mai n method to construct the
objects that are needed to start the program.
The args parameter of the mai n method holds the command-line arguments, which are
not used in this example. We will discuss command-line arguments in the section on
arrays.
You have already seen the first two statements inside the mai n method. They construct a
G reet e r object, store it in an object variable, invoke the sayHel l o method, and capture
the result in a string variable. The last statement invokes the pri ntl n method on the
System . out object. The result is to print the message and a line terminator to the
standard output stream.
To build and execute the program, put the Greete r class inside a file G reete r . j ava and
the Greet e rTester class inside a separate file Greete rTeste r . j ava. The directions for
compiling and running the program depend on your development environment.
The Java Software Development Kit (SDK) from Sun Microsystems is a set of
command-line programs for compiling, running, and documenting Java programs.
CHAPTER 1 A Crash Course in Java
Versions for several platforms are available at http : //j ava . sun . corn/j 2 se. If you use the
Java SDK, then follow these instructions:
1. Create a new directory of your choice to hold the program files.
2. Use a text editor of your choice to prepare the files Greete r . j ava and
GreeterTeste r . j ava. Place them inside the directory you just created.
3. Open a shell window.
4. Use the cd command to change to the directory you just created.
5. Run the compiler with the command
j avac GreeterTeste r . j ava
If the Java compiler is not on the search path, then you need to use the full path
(such as lusr1 1 oca 1 Ij dkl . 5. O/bi n/j avac or c : \jdkl . 5. O\bi n\j avac) instead of
just j avac. Note that the Greete r . j ava file is automatically compiled as well since
the G reeterTester class requires the Greeter class. If any compilation errors are
reported, then make a note of the file and line numbers and fix them.
6. Have a look at the files in the current directory. Verify that the compiler has gen
erated two classfiles, Greete r . c1 ass and GreeterTeste r . c1 ass.
7. Start the Java interpreter with the command
j ava Greete rTester
Now you will see a message "Hello, World!" in the shell window (see Figure 1).
The structure of this program is typical for a Java application. The program consists of a
collection of classes. One class has a rnai n method. You run the program by launching the
Java interpreter with the name of the class whose rnai n method contains the instructions
for starting the program activities.
-$ cd oodp/Chl/helloworld
-/oodp/Chl/helloworld$ javac GreeterTester.java .... ------ Run compiler
�-�d$ -----------
-/oodp/Chl/helloworld$ java GreeterTester ...
...
____
>--- ___
Figure 1
Some programming environ The Blue] development environment, developed at Monash Univer
ments allow you to execute sity, lets you test classes without having to write a new program for
Java code without requiring a every test. Blue] supplies an interactive environment for constructing
mai n method. objects and invoking methods on the objects. You can download Blue]
from http : //www . b 1 uej . o rg.
With Blue], you don't need a GreeterTester class to test the G reete r class. Instead, just
follow these steps.
1. Select "Project -+ New . . . " from the menu; point the file dialog box to a directory
of your choice and type in the name of the subdirectory that should hold your
classes-this must be the name of a new directory. Blue] will create it.
2. Click on the "New Class . . . " button and type in the class name Greeter. Right
click on the class rectangle and type in the code of the Greeter class.
3. Click on the "Compile" button to compile the class. Click on the "Close" button.
4. The class is symbolized as a rectangle. Right-click on the class rectangle and select
"new Greeter(aName)" to construct a new object. Call the object wor1 dG reete r
and supply the constructor parameter "Wor 1 d" (including the quotation marks).
5. The object appears in the object workbench. Right-click on the object rectangle
and select "String sayHello( )" to execute the sayHe 1 1 0 method.
6. A dialog box appears to display the result (see Figure 2).
As you can see, Blue] lets you think about objects and classes without fussing with
publ i c stati c voi d mai n.
��
frojtct Edit Iools �It!w Help
rNewclass ,l
_ _ Class
[ -;:]
Gru.er
...---
C----El
[ ;P � ]
CO il
worldGrttter.s;ayHelloO
returned:
Object workbench
Figure 2
D o c u m e n tation C o m m e n t s
Java has a standard form for comments that describe classes and their features. The Java
development kit contains a tool, called j avadoc, that automatically generates a conve
nient set of HTML pages that document your classes.
Documentation comments are delimited by /** and * /. Both class and method com
ments start with freeform text. The j avadoc utility copies the first sentence of each
comment to a summary table. Therefore, it is best to write that first sentence with some
care. It should start with an uppercase letter and end with a period. It does not have to be
a grammatically complete sentence, but it should be meaningful when it is pulled out of
the comment and displayed in a summary.
Method and constructor comments contain additional information. For each parameter,
supply a line that starts with @param, followed by the parameter name and a short expla
nation. Supply a line that starts with @retu rn to describe the return value. Omit the
@param tag for methods that have no parameters, and omit the @return tag for methods
whose return type is voi d .
Here i s the Greeter class with documentation comments for the class and its public
interface.
Chr/helloworld/Greeter.java
1 /**
2 A class for producing simple greetings.
3 */
4 publ i c cl ass Greeter
5 {
6 /**
7 Constructs a Greeter object that can greet a person or entity.
8 @param aName the name of the person or entity who should
9 be addressed in the greetings.
10 */
11 publ i c Greete r (Stri ng aName)
12 {
13 name aName ;
=
14 }
15
16 /**
17 Greet with a "Hello" message.
18 @ret u rn a message containing "Hello" and the name of
19 the greeted person or entity.
20 */
21 publ i c Stri ng sayHel l o ()
22
+ "!";
{
23 return "Hel l o , " + name
24 }
25
26 pri vate St ri ng name ;
27 }
1.2 Documentation Comments
Your first reaction may well be "Whoa! I am supposed to write all this stuffi" These com
ments do seem pretty repetitive. But you should still take the time to write them, even if
it feels silly at times. There are three reasons.
First, the j avadoc utility will format your comments into a nicely formatted set of
HTML documents. It makes good use of the seemingly repetitive phrases. The first
sentence of each method comment is used for a summary table of all methods of your
class (see Figure 3). The @param and @ret:urn comments are neatly formatted in the detail
descriptions of each method (see Figure 4). If you omit any of the comments, then
j avadoc generates documents that look strangely empty.
Next, it is possible to spend more time pondering whether a comment
Supply comments for all
methods and public fields of is too trivial to write than it takes just to write it. In practical pro
a class. gramming, very simple methods are rare. It is harmless to have a triv-
ial method overcommented, whereas a complicated method without
any comment can cause real grief to future maintenance programmers. According to the
standard Java documentation style, every class, every method, every parameter, and every
return value should have a comment.
Finally, it is always a good idea to write the method comment first, before writing the
method code. This is an excellent test to see that you firmly understand what you need to
program. If you can't explain what a class or method does, you aren't ready to implement
it.
...
I� fileJ/lhomelcayloodpICh1IhelloworidIGreeter.html Cl fjJ
.
Class Greeter -
LGreeter
java.lang.Object
Constructor Summary
Stringl.saYHCllO ()
Method Summary
ja
... lang.
Figure 3
:
I� fileJllhomelcay/oodpIChl lheIiOWOridIGn1eter.html 1:11 III
IConstructor Detail I
Greeter
Parameters:
aName - the name of the person or entil¥ who should be addressed in the greeting.<.
IMethod Detail I
sayHello
public java.lang. String sayHello()
Returns:
a m�sage containing "Hello" and the name of the greeted person or entil¥.
Figure 4
Mter you have written the documentation comments, invoke the j avadoc utility.
1 . Open a shell window.
2 . Use the cd command to change to the directory you just created.
3. Run the j avadoc utility
j avadoc * . j ava
If the Java development tools are not on the search path, then you need to use the
full path (such as /usr /1 oca 1 /j dkl . 5. O/b; n/j avadoc or c : \j dkl . 5 . O\b; n\j ava
doc) instead ofjust j avadoc.
The j avadoc utility then produces one HTML file for each class
The j avadoc utility extracts
documentation comments and (such as Greete r . htm1 and Greete rTeste r . htm1 ) as well as a file
produces a set of cross-linked ; ndex . htm1 and a number of other summary files. The ; ndex . htm1 file
HTML files. contains links to all classes.
The j avadoc tool is wonderful because it does one thing right: It allows you to put the
documentation together with your code. That way, when you update your programs, you
can see immediately which documentation needs to be updated. Hopefully, you will then
update it right then and there. Mterwards, run j avadoc again and get a set of nicely for
matted HTML pages with the updated comments.
INTERNET The DocCheck program reports any missing j avadoc comments. Download it
from http : //j ava . sun . com/j 2 se/j avadoc/doccheck/.
1.3 Primitive Types
.
.. fUe .Edit Yl8'¥l yO UOokmarts Ioois :l!lindow Help
·
·
Iv file:lllusrltocalljdk.1 S OIdocslaplllndex.ntml al [Em
. .
ava,beans
ava,beans,beanC( -
Overview Package mEmUse Tree Deprecated Index !:!!!!p J_
St.
�
� � t:fl.6Mll I!l!...E!!8Mil
�
SUMMARY, NESTED I EID..Il I � I MilI:JQJl DETAIL' EID..Il I � I MilI:JQJl
ava.la
na.annotatl
Ja....lang
ava.lana.instru me •
Class String
�able
tateEdit
�
�-
reamable All Implemented Interfaces:
reamableValU6 Serializable. Olar$eguence, Comparable<String>
treamCorruDted
Str ing
treamHandler
treamPrintServic pub l i c final class
extends Object
implemen ts Ser i a l i z able, Comparable<String> , CharSequence
treamPrintServi
treamResult
treamSource
The S t r ing class represents character strings. All string lirerals in Java
treamT okenizer
�
programs, such as "abc", are implemented as instances of this class.
• ,
c •. .
• •
I1iI Q (>'1' ihomeJlcIpMdk I .s.�tri'l9 html
flo'"
-=�
F i g u re 5
The Java development kit contains the documentation for all classes in the Java library,
also called the application programming interface or API. Figure 5 shows the documen
tation of the St ri ng class. This documentation is directly extracted from the library
source code. The programmers who wrote the Java library documented every class and
method and then simply ran j avadoc to extract the HTML documentation.
TIP Download the SDK documentation from http : //j ava . sun . com/j 2se. Install the doc
umentation into the same location as the Java development kit. Point your browser to the
docs/api Ii ndex . html file inside your Java development kit directory, and make a bookmark.
Do it now! You will need to access this information frequently.
P r i m i t i v e Typ e s
In Java, numbers, characters, and Boolean values are not objects but
Java has eight primitive types
for integers, floating-paint values of a primitive type. Table 1 shows the eight primitive types of
numbers, bytes, characters, the Java language.
and bool ean values. To indicate l ong constants, use a suffix L, such as 10000000000L. Sim
ilarly, fl oat constants have a suffix F, such as 3 . 141S92 7F.
CHAPTER 1 A Crash Course in Java
Characters are encoded in Unicode, a uniform encoding scheme for characters in many
languages around the world. Character constants are enclosed in single quotes, such as
, a ' . Several characters, such as a newline ' \n ' , are represented as two-character escape
Ta b l e 1
\b backspace (\uOOO8)
\n newline (\uOOOA)
\r return (\uOOOD)
\\ backslash
Ta b l e 2
sequences. Table 2 shows the most common permitted escape sequences. Arbitrary
Unicode characters are denoted by a \u, followed by four hexadecimal digits enclosed in
single quotes. For example, ' \u 2 12 2 ' is the trademark symbol (TM) .
INTERNET You can find the encodings of tens of thousands of letters in many alphabets at
http : //www . uni code . o rg.
Conversions that don't incur information loss (such as short to i nt or fl oat to doubl e)
are always legal. Values of type char can be converted to i nt. All integer types can be
converted to fl oat or doubl e, even though some of the conversions (such as l ong to
doubl e ) lose precision. All other conversions require a cast:
doub 1 e x = 10 . 0 / 3 . 0 ; // sets x to 3.3333333333333335
i nt n = (i nt) x ; / / sets n to 3
fl oat f = (fl oat) x ; // sets f to 3.3333333
It is not possible to convert between the bool ean type and number types.
The Math class implements useful mathematical methods. Table 3 contains some of the
most useful ones. The methods of the Math class do not operate on objects. Instead,
numbers are supplied as parameters. (Recall that numbers are not objects in Java.) For
example, here is how to call the sq rt method:
doubl e y = Math . sq rt (x) ;
Since the method doesn't operate on an object, the class name must be supplied to tell
the compiler that the sqrt method is in the Math class. In Java, every method must
belong to some class.
Method Description
Ta b l e 3
Mathematical Methods
CHAPTER 1 A Crash Course in Java
C o n t r o l F l o w S ta t e m e n t s
The i f statement is used for conditional execution. The el se branch is optional.
i f (x >= 0) y = Math . sq rt (x) ; el se y = 0 ;
The whi 1 e and do statements are used for loops. The body of a do loop is executed at least
once.
whi l e (x < target)
{
x = x * a;
n++ ;
}
do
{
x = x * a;
n++ ;
}
whi l e (x < target) ;
The for statement is used for loops that are controlled by a 100F counter.
fo r (i = 1 ; i <= n ; i ++ )
{
x = x * a;
sum sum + x ;
}
A variable can be defined in a fo r loop. Its scope extends to the end of the loop.
for ( i n t = 1; i <= n ; i ++)
{
x = x * a;
sum sum + x ;
}
// i no longer defined here
Java 5.0 introduces an enhanced form of the fo r loop. We will discuss that construct later
in this chapter.
Obj e c t R e f e r e n c e s
In Java, an object value is always a reference to an object, or, i n other words, a value that
describes the location of the object. For example, consider the statement
G reete r wo rl dGreete r = new Greete r ( "Wo rl d " ) ;
wo rl dGreet e r
G re e t e r
F i g u re 6
An Object Reference
There can be multiple variables that store references to the same object. For example,
after the assignment
Greeter anothe rGreete r = wo r l dG reete r ;
the two object variables refer to the same object (see Figure 7).
� G reet e r
wo rl dGreete r
Figure 7
A Shared Object
CHAPTER 1 A Crash Course in Java
It can happen that an object has no references pointing to it, namely when all object vari
ables that previously referred to it are filled with other values or have been recycled. In
that case, the memory that was used for storing the object will be automatically
reclaimed by the garbage collector. In Java, you never need to manually recycle memory.
NOTE If you are familiar with the C++ programming language, you will recognize that object
references in Java behave just like pointers in C++. In C++, you can have multiple pointers to
the same value, and a NULL pointer points to no value at all. Of course, in C++, pointers strike
fear in the hearts of many programmers because it is so easy to create havoc with invalid
pointers. It is sometimes said that Java is easier than C++ because it has no pointers. That
statement is not true. Java always uses pointers (and calls them references), so you don't have
to worry about the distinction between pointers and values. More importantly, the pointers in
Java are safe. It is not possible to create invalid pointers, and the garbage collector automati
cally reclaims unused objects.
P a r a m e t e r P a s s in g
The object reference on which you invoke a method is called the implicit parameter. In
addition, a method may have any number of explicitparameters that are supplied between
parentheses. For example, in the call
myG reete r . setName ("Mars" ) ;
the reference stored in myG reete r is the implicit parameter, and the string "Mars" is the
explicit parameter. The explicit parameters are so named because they are explicitly
defined in a method, whereas the implicit parameter is implied in the method definition.
Occasionally, you need to refer to the implicit parameter of a method by its special name,
thi s. For example, consider the following implementation of the setName method:
publ i c cl ass Greete r
{
/**
Sets this greeter's name to the given name.
@param name the new name for this greeter
*/
publ i c voi d setName (Stri ng name)
{
thi s . name = name ;
}
}
The thi s reference refers to the object on which the method was
The t hi s reference refers to
the object on which a method invoked (such as myG reete r in the call myGreete r . setName ( "Mar s " ) ) .
was invoked. The name field i s set to the value o f the explicit parameter that i s also
called name. In the example, the use of the thi s reference was neces
sary to resolve the ambiguity between the name field and the name parameter.
1.6 Parameter Passing
Occasionally, the thi s reference is used for greater clarity, as in the next example.
}
N ow consider this call:
G reete r wo rl dGreete r = new Greete r ( "Worl d " ) ;
G reete r daveG reete r = new Greet e r ( " Dave " ) ;
wo rl dGreete r . copyNameTo (daveGreete r) ;
Figure 8 shows how the other parameter variable is initialized with the daveGreete r
reference. The copyNameTo method changes othe r . name, and after the method returns,
daveG reete r . name has been changed.
However, in Java, a method can never update the contents ofa variable that is passed as a
parameter. For example, after the call
wo rl dGreete r . copyNameTo(daveG reete r) ;
the contents of daveGreete r is the same object reference before and after the call. It is
not possible to write a method that would change the contents of daveG reeter to
another object reference. In this regard, Java differs from languages such as C++ and C#
that have a "call by reference" mechanism.
To see that Java does not support call by reference, consider yet another set of contrived
methods. These methods try to modifY a parameter, but they have no effect at all.
� G reete r
daveG reete r
F i g u re 8
/* ;'
Tries to copy the length of this greeter's name into an integer variable.
@param n the variable into which the method tries to copy the length
*/
publ i c voi d copyLengthTo (i nt n)
{
/ / this assignment has no effect outside the method
n = name . l ength () ;
}
/**
Tries to set another Greeter object to a copy of this object.
@param other the Greeter object to initialize
*/
publ i c voi d copyG reete rTo (Greeter other)
{
// this assignment has no effect outside the method
(
other = new G reete r (name) ;
}
}
Let's call these two methods:
i nt l ength = 0 ;
G reete r wo rl dGreete r = new G reete r ( "Wo rl d " ) ;
G reete r daveG reet e r = new Greete r ( "Dave " ) ;
wo rl dGreete r . copyLengthTo(l ength) ;
/ / has no effect on the contents of 1 ength
wo rl dGreete r . copyG reete rTo (daveG reeter) ;
/ / has no effect on the contents of daveG reete r
Neither method call has any effect. Changing the value of the param
Java uses "call by value" when
passing parameters. eter variable does not affect the variable supplied in the method call.
Thus, Java has no call by reference. Java uses the "call by value" mech
anism for both primitive types and object references.
Packages
Java classes can be grouped into packages. Package names are dot-separated sequences of
identifiers, such as
j ava . uti l
j avax . swi ng
com . su n . mi sc
edu . sj su . cs . cs1 5 1 . al i ce
1.7 Packages
}
Any class without a package statement is in the "default package" with no package name.
ThefoIl name of a class consists of the package name followed by the class name, such as
edu . sj su . cs . cs15 1 . al i ce . Greete r . Some full class name examples from the Java library
are j ava . uti l . Ar rayLi st and j avax . swi ng . J Opti onPane.
Organize your class files in Large programs consist of many classes in multiple packages. The
directories that match the class files must be located in subdirectories that match the package
package names. names. For example, the class file G reete r . c l ass for the class
edu . sj su . cs . cs 1 51 . al i ce . G reete r
must be in a subdirectory
edu/sj s u/cs/cs151/al i ce
or
edu\sj s u\cs\cs151\al i ce
of the project's base directory (see Figure 9). The base directory is the directory that con
tains all package directories as well as any classes that are contained in the default pack
age (that is, the package without a name).
CHAPTER 1 A Crash Course in Java
Base directory - [j
? [j edu
9 [j cs
� [j cs151
? [j alice
D Greeter.java
F i g u re 9
B a s i c E x c e p ti o n Handling
When a program carries out a n illegal action, an exception i s generated. Here i s a com
mon example. Suppose you initialize a variable with the nul l reference, intending to
assign an actual object reference later, but then you accidentally use the variable when it
is still nu 1 1 .
St ri ng name = nul l ;
i nt n = name . l ength () ; II Illegal
Different programming errors lead to different exceptions. For example, trying to open a
file with an illegal file name causes a Fi 1 eNotFound Excepti on.
1.8 Basic Exception Handling
You can also throw your own exceptions ifyou find that a programmer
Throw an exception to indicate
makes an error when using one of your classes. For example, if you
an error condition that the cur
rent method cannot handle. require that the parameter of one of your methods should be positive,
and the caller supplies a negative value, you can throw an II I ega 1 -
ArgumentExcepti on:
i f (n <= 0) throw new Il l egal ArgumentExcepti on ( " n shou l d be > 0 " ) ;
}
If there is no file with the given name, the Fi l eReade r constructor throws a
Fi 1 eNotFoundExcepti on. Because it is a checked exception, the compiler insists that you
handle it. However, the implementor of the read method probably has no idea how to
correct this situation. Therefore, the optimal remedy is to let the exception propagate to its
caller. That means that the read method terminates, and that the exception is thrown to
the method that called it.
Whenever a method propagates a checked exception, you must declare the exception in
the method header, like this:
CHAPTER 1 A Crash Course in Java
TIP There is no shame associated with acknowledging that your method might throw a
checked exception-it is just "truth in advertising".
If a method can throw multiple exceptions, you list them all, separated by commas. Here
is a typical example. As you will see in Chapter 7, reading objects from an object stream
can cause both an IOExcepti on (if there is a problem with reading the input) and a
Cl assNotFound Excepti on (if the input contains an object from an unknown class). A
read method can declare that it throws both exceptions:
publ i c voi d read (Stri ng fi l ename)
th rows IOExcept i on , Cl assNotFoundException
When you tag a method with a th rows clause, the callers of this method are now put on
notice that there is the possibility that a checked exception may occur. Of course, thost,
calling methods also need to deal with these exceptions. Generally, the calling methods
also add th rows declarations. When you carry this process out for the entire program, the
ma i n method ends up being tagged as well:
publ i c stati c voi d mai n (Stri ng [ ] args)
throws IOExcepti on , Cl assNotFoundExcepti on
{
}
If an exception actually occurs, the mai n method is terminated, a stack trace is displayed,
and the program exits.
However, if you write a professional program, you do not want the program to terminate
whenever a user supplies an invalid file name. In that case, you want to catch the excep
tion. Use the following syntax:
t ry
{
code that might throw an IOExcepti on
}
catch (IOExcepti on excepti on)
{
take corrective action
}
An appropriate corrective action might be to display an error message
When an exception is thrown,
the program jumps to the clos and to inform the user that the attempt to read the file has failed.
est matching catch clause. In most programs, the lower-level methods simply propagate excep
tions to their callers. Some higher-level method, such as mai n or a part
of the user interface, catches exceptions and informs the user.
1.9 Strings
For debugging purposes, you sometimes want to see the stack trace. Call the pri nt
StackTrace method like this:
t ry
{
}
catch (IOExcepti on excepti on)
{
excepti on . p ri ntStackTrace () ;
take corrective action
}
Occasionally, a method must carry out an action even if a prior statement caused an
exception. A typical example is closing a file. A program can only open a limited number
of files at one time, and it should close all files that it opened. To ensure that a file is
closed even if an exception occurred during file processing, use the fi na 1 1 y clause:
Fi l eReade r reader = nu l l ;
reader = new Fi l eRead e r (name) ;
t ry
{
}
fi nal l y
{
reade r . cl oseO ;
}
Code in a fi na 1 1 y clause
The fi na 1 1 y clause is executed when the t ry block exits without an
is executed during normal exception, and also when an exception is thrown inside the t ry block.
processing and when an In either case, the cl ose method is called. Note that the Fi 1 eReader
exception is thrown. constructor is not contained inside the t ry block. If the constructor
throws an exception, then reade r has not yet been assigned a value, and
the cl ose method should not be called.
S tr i n g s
Java strings are sequences of Unicode characters. The charAt method yields the individ
ual characters of a string. String positions start at O.
St ri ng g reeti ng "Hel l o" ;
=
A Java string is an
Java strings are immutable. Once created, a string cannot be changed.
immutable sequence of Thus, there is no setCharAt method. This may sound like a severe
Unicode characters. restriction, but in practice it isn't. For example, suppose you initialized
g reeti ng to " Hel l o " . You can still change your mind:
g reeti ng = "Goodbye" ;
The string object " Hel l o " hasn't changed, but g reeti ng now refers to a different string
object.
The 1 ength method yields the length of a string. For example, " Hel l o " 1 engt h O is 5.
.
CHAPTER 1 A Crash Course in Java
Figure 1 0
I' H 'I' e '1' 1 '1' 1 'I' 0 'I
o 1 2 3 4
Extracting a Substrin g '-y---'
Note that the empty string .. .. oflength 0 is different from nu1 1-a reference to no string
at all.
The substri ng method computes substrings of a string. You need to specifY the positions
of the first character that you want to include in the substring and the first character that
you no longer want to include. For example, "Hel l o " . substri n g C 1 , 3) is the string "e1 "
(see Figure 10). Note that the difference between the two positions equals the length of
the substring.
Since strings are objects, you need to use the equal s method to compare whether two
strings have the same contents.
i f Cg reeti ng . equa1 s C "Hel l o" ) ) . . . II OK
If you use the == operator, you only test whether two string references have the identical
location. For example, the following test fails:
i f C " Hel l o" . substri n g C 1 , 3) == "e1 " ) . . . II NO
The substring is not at the same location as the constant string "e1 " , even though it has
the same contents.
You have already seen the string concatenation operator: " Hel l o , + name is the con ..
catenation of the string " He 1 1 0 , and the string object to which name refers.
..
If either argument of the + operator is a string, then the other is converted to a string. For
example,
i nt n = 7 ;
Stri ng g reeti ng = " He l l o , .. + n;
constructs the string " He 1 1 0 , 7 " .
I f a string and a n object are concatenated, then the object i s converted to a string by
invoking its toSt ri ng method. For example, the toStri ng method of the Date class in
the j ava . uti 1 package returns a string containing the date and time that is encapsulated
in the Date object. Here is what happens when you concatenate a string and a Date
object:
II default Date constructor sets current date/time
Date now =new Date C) ;
St ri ng g reeti ng = " He l l o , + now ;
..
R e ading I n p u t
The Scanner class can be Starting with Java 5.0, the simplest way to read input in a Java pro
used to read input from the gram is to use the Scanner class. To read console input, construct a
console or a file. Scan ner from System . i n . Call the nextInt or nextDoubl e method to
read an integer or a floating-point number. For example,
Scanner i n new Scanner(System . i n) ;
System . out . pri n t ( " How ol d are you? " ) ;
i nt age = i n . nextlnt () ;
If the user types input that is not a number, an (unchecked) InputMi smatchExcepti on is
thrown. You can protect yourself against that exception by calling the hasNextlnt or has
NextDou bl e method before calling nextInt or nextDoubl e.
The next method reads the next whitespace-delimited token, and nextL i ne reads the
next input line.
You can read input from a file by constructing a Scanne r from a Fi 1 eReade r. For exam
ple, the following loop reads all lines from the file i nput . txt:
Scanner i n = new Scanner (new Fi l eRead e r ( " i n put . txt ") ) ;
whi l e (i n . hasNextLi n e ( ) )
{
Stri ng l i ne = i n . nextLi n e () ;
Array L i s t s and L i n k e d L i s t s
The Ar rayL i st class of the j ava . uti 1 package lets you collect a sequence of objects of
any type. The add method adds an object to the end of the array list.
ArrayLi st<Stri ng> count ri es = new Ar rayLi st<St r i ng> () ;
countri es . ad d ( " Bel gi um") ;
countri es . add(" Ital y" ) ;
countri es . add ( "Thai l and " ) ;
Starting with Java 5.0, the Ar rayL i st class is a generic class with a type parameter. The
type parameter ( Stri ng in our example) denotes the type of the list elements. You can
form array lists of any type, except for primitive types. For example, you can use an
Ar rayL i st<Date> but not an Ar rayL i st<i nt>.
The s i ze method returns the number of elements in the array list. The get method
returns the element at a given position; legal positions range from ° to s i ze O - 1. For
example, the following loop prints all elements of the countri es list:
for (i nt i = 0 ; i < countri es . s i ze () ; i ++)
{
St ri ng country countri es . get ( i ) ;
System . out . pri ntl n (count ry) ;
}
CHAPTER 1 A Crash Course in Java
Figure 1 1
New value
t===::
t===
�
==:
This loop is so common that Java 5.0 introduces a convenient shortcut: the enhanced fo r
loop or "for each" loop:
fo r (Stri ng country : countri es)
System . out . p ri ntl n (count ry) ;
In each loop iteration, the variable before the : is set to the next element of the cou n
tri es list.
The set method lets you overwrite an existing element with another:
count ri es . set ( l , " F rance " ) ;
If you access a nonexistent position « 0 or >= s i z e O ) , then an IndexOutOfBounds
Excepti on is thrown.
Finally, you can insert and remove elements in the middle of the array list.
countri es . add ( l , "Ge rmany " ) ;
countri es . remove (O) ;
These operations move the remammg elements up or down. The
An array list is a collection of
objects that supports efficient name "array list" signifies that the public interface allows both array
access to all storage locations. operations ( get/set ) and list operations ( add/ remove ) .
Inserting and removing elements in the middle of an array list is not
A linked list is a collection of
efficient. All elements beyond the location of insertion or removal
objects that supports efficient
insertion and removal of ele- must be moved (see Figure 11). A linked list is a data structure that
ments. You use an iterator to supports efficient insertion and removal at any location. When insert
traverse a linked list. ing or removing an element, all elements stay in place, and only the
neighboring links are rearranged (see Figure 12). The standard Java
library supplies a class L i nkedL i st implementing this data structure.
Figure 1 2
As with array lists, you use the add method to add elements to the end of a linked list.
However, accessing elements in the middle of the linked list is not as simple. You don't
want to access a position by an integer index. To find an element with a given index, it is
necessary to follow a sequence of links, starting with the head of the list. That process is
not very efficient. Instead, you need an iterator, an object that can access a position any
where in the list:
The next method advances the iterator to the next position of the list and returns the
element that the iterator just passed (see Figure 13). The hasNext method tests whether
the iterator is already past the last element in the list. Thus, the following loop prints all
elements in the list:
To remove an element from the list, call next until you jump over the element that you
want to remove, then call remove. For example, this code removes the second element of
the countri es list.
Figure 1 3
Iterator Movement
The development of the papacy led directly to the Dark Ages, for
“the noontide of the papacy was the world’s moral midnight.” The
papacy was the logical working out of an educational scheme; hence
the moral darkness which spread over the world during the
prophetic period of twelve hundred and sixty years was due to
wrong methods of education. People do not sink into degradation
and sin when properly educated. Truth elevates, and, when
embodied in man, brings him nearer to his Maker. Faith is the ladder
by which he climbs, and when that element has been lacking in an
educational system, the masses have sunk lower and lower.
Mind is a wonderful thing, the most profound Papacy’s
study of the universe. It was designed to be free, tyranny of
to grasp the mighty laws of its own Creator, and a theology
thought
over
ebookgate.com