Intro To Java Textbook
Intro To Java Textbook
©
! '5)$% 4/
02/'2!--).' ).
3%#/.$ %$)4)/.
FOR *AVA© 3% AND *AVA© 3%
"ETH "ROWN
A Guide to
Programming in Java™
Second Edition
for Java™ SE 5 and Java™ SE 6
Beth Brown
Preface
W e have strived to make this edition the clearest and most compre-
hensive Java text available. Our primary objective in this text is to present
material in clear language with easy to follow examples. To meet this
objective, we use our teaching experiences as well as the feedback, com-
ments, and suggestions from other experienced instructors to determine
how best to present programming concepts.
For the best classroom experience for both the student and the instructor,
our comprehensive text book includes hands-on reviews, critical-thinking
questions, and exercises of varying difficulty levels. Additionally, our
Teacher Resource Materials correlate directly to the text book and offer
teaching hints for explaining difficult concepts, additional lessons and
exercises, and a comprehensive question bank for creating tests, quizzes,
and reviews. The Teacher Resource Materials include the applications,
Case Studies, and vocabulary from the text book, as well as answers to
all the reviews and exercises.
It is our belief that learning to program offers the student an invaluable
opportunity to develop problem-solving skills. The process of defining a
problem, breaking it down into a series of smaller problems, and finally
writing an application to solve it exercises a student’s logical abilities.
Additionally, the student is made aware of the capabilities and limita-
tions of a computer and soon realizes that the programmer—the human
element—is more important than the machine.
A Guide to Programming in Java, Second Edition, is written for a one-term
or two-term course. No previous programming experience is required or
assumed. It is our goal that this text provide students the best possible
introduction to programming using Java and to prepare them for further
study in the IT/programming/computer science field.
Preface iii
Design and Features
Programming Concepts This text emphasizes the fundamental concepts
of programming so that this knowledge can be applied to other program-
ming languages.
Problem Solving From the very beginning, students are taught to imple-
ment programming solutions with proper algorithm design and code
conventions.
Programming Style Throughout the text, proper programming style
is emphasized so that students can make their applications easy to read,
modify, and debug.
Demonstration Applications and Runs Many demonstration applica-
tions are included, complete with sample runs, so that students are shown
both proper programming techniques and the output actually produced
by an application.
Reviews Numerous reviews are presented throughout each chapter to
provide immediate reinforcement of newly learned concepts. Solutions to
the reviews are included on the Teacher Resource Materials CD.
Case Studies Most chapters end by stating a problem, developing an
appropriate algorithm, and then implementing the solution. The process
of specification, design, implementation, and debugging and testing is
clearly outlined.
Chapter Summaries Each chapter ends by summarizing the concepts
and statements covered in the chapter.
Vocabulary Sections Each chapter contains a vocabulary section that
defines new terms. A separate section lists Java keywords, statements,
and classes.
Critical Thinking Written response questions that require critical think-
ing from the student are included at the end of each chapter.
Exercises Each chapter includes a large set of exercises of varying diffi-
culty, making them appropriate for students with a range of abilities. Most
exercises include a demonstration run to help make clear what output is
expected from the student’s application. Exercises based on previous work
are marked with a ö symbol. Answers to the exercises are included on
the Teacher Resource Materials CD.
Indexes In addition to a standard index, an index of the applications
presented in the text is also included.
Appendices A chart of Unicode symbols is included. Also included is
instruction for using JCreator, the Java compiler included with this text.
Student CD A CD with everything students need to do their assign-
ments from home, including JCreator Pro, programs from the text, and
data files.
Online Resources Materials that complement and extend this text are
free for download and distribution in your class. Supplements also cover
operating systems, personal finances, the Web, and keyboarding skills.
Students can download all the files needed to complete the reviews and
exercises from www.Lpdatafiles.com.
Acknowledgments
Special thanks to the many instructors who used this text in their
classroom as it was being written. I would especially like to thank the
following instructors for their many comments and suggestions:
Paul Massey Hanna-Westside Extension Campus
Edward Sapienza Peabody Veterans Memorial High School
Timothy Strohm Churchville-Chili Senior High School
Jackie Kyger Marine Military Academy
Jan Marrelli, a Lawrenceville Press author and editor, has contributed
much to this text. She has used this text as it was being written in her
classroom. The many comments and suggestions from her and her stu-
dents have helped to make this text so clearly written. Jan, an experienced
instructor, has also written many of the critical thinking questions, exer-
cises, and reviews.
Preface v
Elaine Malfas, senior technical editor at Lawrenceville Press, has pro-
duced the format and layout for this text. The many illustrations have been
created by Elaine as well.
Thanks also to Joseph Dupree in our Customer Relations Department
for some of the original drawings included in this text.
The success of this and all of our texts is due to the efforts of Heidi
Crane, Vice President of Marketing at Lawrenceville Press. Joseph Dupree
runs our Customer Relations Department and handles the thousands
of orders we receive in a friendly and efficient manner. Michael Porter
is responsible for the excellent service Lawrenceville Press offers in the
shipping of orders.
Preface vii
Chapter 5 – Conditional Control Chapter 8 – Classes and Object-
Structures Oriented Development
After completing Chapter 5, students After completing Chapter 8, students
will be able to: will be able to:
1. Demonstrate the use of decision structures to 1. Understand and instantiate objects.
control the flow of a program. 2. Design and implement a class.
2. Describe how a roundoff error can occur. 3. Apply functional decomposition.
3. Generate random numbers. 4. Apply appropriate naming conventions to a
4. Write compound Boolean expressions. class.
5. Access methods in the Math class. 5. Explain the difference between accessor,
6. Modify existing code. modifier, and helper methods.
7. Develop code with correct and efficient use of 6. Write constructors.
conditional control structures. 7. Compare and contrast instance and class
8. Select appropriate test data. members.
9. Create and modify solutions to problems. 8. Understand class specifications and the
relationships among the classes.
Chapter 6 – Loop Structures and 9. Understand and implement a given class
hierarchy.
Strings 10. Apply encapsulation.
After completing Chapter 6, students
11. Identify reusable code from existing code.
will be able to:
1. Demonstrate the use of repetition control
structures. Chapter 9 – Inheritance and
2. Explain how infinite loops can occur. Polymorphism
3. Differentiate between counters and After completing Chapter 9, students
accumulators. will be able to:
4. Use various tools and techniques to debug an 1. Extend a class using inheritance.
application. 2. Explain an is-a relationship.
5. Manipulate and compare strings using the 3. Implement a subclass.
String class and its methods. 4. Define and demonstrate polymorphism.
6. Develop code with correct and efficient use of 5. Understand abstract classes.
repetitive control structures. 6. Declare and implement an interface.
7. Apply problem solving strategies. 7. Extend existing code using inheritance.
Preface ix
x A Guide to Programming in Java
Table of Contents
Table of Contents xi
Chapter 3 – Introducing Java Chapter 5 – Conditional Control
Why Program in Java? ............................................ 59 Structures
Objects, Classes, and Packages ............................. 59
The if Statement..................................................... 105
A Java Application .................................................. 61
Roundoff Error ...................................................... 106
Executing a Java Application ................................. 62
Review: SurfsUp – part 1 of 3 ......................... 106
Review: Greeting................................................ 62
The if-else Statement............................................. 106
Displaying Output ..................................................63
Review: SurfsUp – part 2 of 3 ......................... 107
Review: AboutMe – part 1 of 2 .........................64
Review: CircleCircumference – part 2 of 2... 107
Formatting Output..................................................64
Nested Statements ................................................. 107
Review: AboutMe – part 2 of 2 .........................65
Review: Stages .................................................. 107
Code Conventions ...................................................65
The if-else if Statement ......................................... 108
Algorithm Design ................................................... 66
Review: SurfsUp – part 3 of 3 ......................... 108
Chapter Summary .................................................. 67
Review: Discriminant...................................... 108
Vocabulary ............................................................... 69
The switch Statement............................................ 109
Java ............................................................................ 70
Review: Hurricane ........................................... 110
Critical Thinking ..................................................... 71
Generating Random Numbers ............................ 110
Exercises ................................................................... 72
Review: RandomNum ..................................... 111
Compound Boolean Expressions ........................ 112
Review: Delivery .............................................. 113
Chapter 4 – Variables and The Math Class ...................................................... 113
Review: PerfectSquare ..................................... 114
Constants Chapter 5 Case Study ........................................... 114
Declaring Variables.................................................77 Review: RPS – part 1 of 2 ................................ 118
Using Variables ........................................................ 78 Review: RPS – part 2 of 2 ................................ 118
Review: RectanglePerimeter............................. 79 Chapter Summary ................................................ 119
Primitive Data Types .............................................. 79 Vocabulary ............................................................. 120
Review: Distance – part 1 of 2 .......................... 79 Java .......................................................................... 121
Abstract Data Types ................................................80 Critical Thinking ................................................... 122
Java Packages ...........................................................80 Exercises ................................................................. 123
Obtaining a Value from the User .......................... 81
Review: Distance – part 2 of 2 .......................... 82
Numeric Expressions..............................................83
Review: Digits.....................................................84
Chapter 6 – Loop Structures and
Type Casting ............................................................84 Strings
Review: GradeAvg – part 1 of 2 .......................85
The while Statement ............................................. 131
Review: TempConverter ....................................85
The do-while Statement ....................................... 131
Formatting Numeric Output ................................. 86
Infinite Loops ........................................................ 132
Assignment Operators ........................................... 86
Review: Prompter ............................................ 133
Review: GradeAvg – part 2 of 2 ....................... 87
Counters and Accumulators................................ 133
Using Named Constants ........................................ 87
Review: Evens ................................................... 134
Identifiers and Keywords ......................................88
Review: NumbersSum .................................... 134
Review: CircleCircumference – part 1 of 2..... 88
Review: PercentPassing ................................... 134
Programming Errors .............................................. 88
The for Statement .................................................. 135
Chapter 4 Case Study .............................................90
Review: Factorial .............................................. 136
Chapter Summary .................................................. 93
Review: OddSum ............................................. 136
Vocabulary ............................................................... 95
Debugging Techniques ........................................ 136
Java ............................................................................ 96
Review: Variable Trace .................................... 137
Critical Thinking ..................................................... 97
The String Class .................................................... 138
Exercises ................................................................... 99
Review: AccountSetup .................................... 139
Comparing Strings................................................ 140
Review: FormalGreeting ................................. 141
Chapter 7 – Methods
Program Development Using Methods ............. 157
Chapter 9 – Inheritance and
Writing Methods ................................................... 159 Polymorphism
Review: TimeConverter................................... 160
Extending a Class .................................................. 213
Method Parameters............................................... 160
Implementing a Subclass ..................................... 214
Review: SpanishNumbers .............................. 161
Review: Puck – part 1 of 2 ............................... 216
Review: DisplayBox – part 1 of 2 ................... 162
Polymorphism ....................................................... 217
Method Overloading ............................................ 162
Review: Music – part 1 of 2 ............................. 221
Review: DisplayBox – part 2 of 2 ................... 163
Abstract Classes ....................................................222
The return Statement ............................................ 163
Review: Music – part 2 of 2 .............................225
Review: Exponentiation .................................. 164
Interfaces ................................................................225
Documenting Methods ........................................ 164
Review: Disk ..................................................... 227
Review ............................................................... 165
Review: Puck – part 2 of 2 ............................... 227
Chapter 7 Case Study ........................................... 165
Review: Rectangle – part 4 of 4 ...................... 227
Review: GradeConverter ................................. 171
Review: Rectangle – part 4 of 5 ...................... 227
Chapter Summary ................................................ 171
Chapter 9 Case Study ........................................... 227
Vocabulary ............................................................. 173
Review: SalesCenter.........................................234
Java .......................................................................... 173
Chapter Summary ................................................234
Critical Thinking ................................................... 174
Vocabulary ............................................................. 236
Exercises ................................................................. 175
Java .......................................................................... 236
Critical Thinking ................................................... 237
Exercises ................................................................. 238
Chapter 8 – Classes and Object-
Oriented Development
What is an Object? ................................................ 179
Chapter 10 – Arrays
Designing and Writing a Class ........................... 180 Declaring Arrays ................................................... 239
Review: Circle – part 1 of 4 ............................. 182 Using Arrays .......................................................... 240
Review: Coin – part 1 of 2 ............................... 182 Review: StudentRoster .................................... 241
Writing Constructors ............................................ 183 Review: Squares ............................................... 241
Review: Circle – part 2 of 4 ............................. 184 Review: Reverse ............................................... 241
Review: Rectangle – part 1 of 5 ...................... 184 Array Parameters .................................................. 241
Instance and Class Members............................... 184 Arrays with Meaningful Indexes ....................... 242
Review: Circle – part 3 of 4 ............................. 185 Review: DiceRolls – part 1 of 2 ....................... 243
Review: Rectangle – part 2 of 5 ...................... 185 Review: DiceRolls – part 2 of 2 ....................... 243
The Object Class .................................................... 185 Review: NumberCounts.................................. 243
Review: Circle – part 4 of 4 ............................. 187 Characters and Arrays ......................................... 244
Review: Rectangle – part 3 of 5 ...................... 187 Review: CountLetters ...................................... 246
Review: Coin – part 2 of 2 ............................... 187 Review: NameBackwards ............................... 246
Classes Using Classes ........................................... 187 Searching an Array ............................................... 246
Review: Bank .................................................... 191 Review: FindName .......................................... 247
Object-Oriented Development ............................ 191 Two-Dimensional Arrays ..................................... 247
Review: Carnival .............................................. 195 The ArrayList Class .............................................. 252
Appendix A – Unicode
Unicode ................................................................... 381
Index
Index ....................................................................... 393
Table of Contents xv
xvi Table of Contents
Chapter 1
An Introduction to Computers
Desktop Computing
A desktop computer and its components are designed to fit on or under
a desk:
TIP Desktop computers are
referred to as either PCs or
Macs.
BASE UNIT
#$ 27$6$ DRIVE
MONITOR DISK DRIVE
SCANNER
KEYBOARD
MOUSE
Windows XP Utilities
Mobile Computing
Improved technology has brought about the miniaturization of computer
components and the development of long-lasting batteries. Computers now
come in many shapes, sizes, and with many levels of features. Among
Bluetooth these computers are notebooks, tablets, handhelds, smart phones, and
Blueto oth is a wireless wearables. Because of their portability, these types of computers are
technology used to allow classified as mobile computing devices:
mobile computing devices to
communicate. • A notebook computer is a portable, lightweight computer with a
CPU, memory, and hard disk space comparable to that of a typical
desktop computer.
• A tablet PC is a computer designed similar to a pad of paper and
a pencil. Users simply “write” on a screen with a device called a
stylus that is shaped like a thin pencil. Handwriting recognition
software is used to interpret a user’s handwriting. A keyboard can
also be attached.
cross-platform connectivity One issue involved with using so many types of PCs is cross-platform
connectivity, which is the ability for one type of PC to link to and share
data with a different type of PC. Notebook and desktop PCs typically have
good cross-platform connectivity because their file formats can be used on
either computer. Tablets and handhelds use a different OS and generate
different file formats, requiring special hardware and software to use their
files on a desktop or notebook PC. Wearable computers typically have a
cable that allow a connection to other types of PCs, but special software
must be used to communicate between the devices.
Programming Languages
A programming language is a set of words, codes, and symbols that allow
a programmer to give instructions to the computer. Many programming
languages exist, each with their own rules, or syntax, for writing these
instructions.
Programming languages can be classified as low-level and high-level
languages. Low-level programming languages include machine language
and assembly language. Machine language, which is referred to as a first
generation programming language, can be used to communicate directly
with the computer. However, it is difficult to program in machine language
because the language consists of 0s and 1s to represent the status of a
switch (0 for off and 1 for on). Assembly language uses the same instruc-
tions and structure as machine language but the programmer is able to
Fourth and Fifth use meaningful names or abbreviations instead of numbers. Assembly
Generation Languages language is referred to as a second generation programming language.
Fourth generation languages
( 4GL), such as SQL, have High-level programming languages, which are often referred to as third
higher English-like instructions generation programming languages (3GL), were first developed in the late
than most high-level languages 1950s. High-level programming languages have English-like instructions
and are typically used to access and are easier to use than machine language. High-level programming
databases. Fifth generation languages include Fortran, C, Basic, COBOL, and Pascal. In order for the
languages are used for artificial
computer to understand a program written in a high-level language, pro-
intelligence.
grammers convert the source code into machine language using a compiler
or an interpreter. A compiler is a program that converts an entire program
Networks
A network is a combination of hardware and software that allows
computers to exchange data and share software and devices, such as
printers. Networks are widely used by businesses, universities, and other
organizations because a network:
• allows users to reliably share and exchange data
• can reduce costs by sharing devices such as printers
• offers security options including password protection to restrict
access to certain files
• simplifies file management through centralized software updates
and file backups
• provides e-mail for network users
Baseband and
Broadband Technology
Most L ANs use baseband
technology which means the
transmission media carries one LAN using a star topology
signal at a time. Broadband
technology allows for data • In a ring topology, each node is connected to form a closed loop.
transmission of more than one A LAN with a ring topology can usually cover a greater distance
signal at a time and is found in
than a bus or star topology:
cable television transmission.
Wi-Fi
Wi-Fi ( Wireless Fidelity) is
a term used to describe an
802.11 network, which is a LAN using a ring topology
specification or protocol for
wireless networks. • Wireless networks use high frequency radio waves or infrared sig-
nals instead of cables to transmit data. A router/wireless access
point device is used to allow nodes to transfer data through the
air.
logical topology Another type of topology is logical topology, which refers to the way data
is passed between the nodes on a network. A LAN’s logical topology is
not always the same as its physical topology.
Number Systems
The electrical circuits on an IC have one of two states, off or on. Therefore,
binary number system the binary number system (base 2), which uses only two digits (0 and 1), was
adopted for use in computers. To represent numbers and letters, a code
was developed with eight binary digits grouped together to represent a
bit single number or letter. Each 0 or 1 in the binary code is called a bit (BInary
byte digiT) and an 8-bit unit is called a byte.
base 10 Our most familiar number system is the decimal, or base 10, system. It
uses ten digits: 0 through 9. Each place represents a power of ten, with
the first place to the left of the decimal point representing 100, the next
place representing 101, the next 102, and so on (remember that any number
raised to the zero power is 1). In the decimal number 485, the 4 represents
4×102, the 8 represents 8×101, and the 5 represents 5×100. The number 485
represents the sum 4×100 + 8×10 + 5×1 (400 + 80 + 5):
Decimal Base 10 Equivalent
485 4×102 + 8×101 + 5×100 = 400 + 80 + 5
base 2 The binary, or base 2, system works identically except that each place
represents a power of two instead of a power of ten. For example, the
binary number 101 represents the sum 1×22 + 0×21 + 1×20 or 5 in base ten.
Some decimal numbers and their binary equivalents are:
Decimal Binary Base 2 Equivalent
0 0 = 0×21 + 0×20 = 0×2 + 0×1 =0+0
1 1 = 0×21 + 1×20 = 0×2 + 1×1 =0+1
2 10 = 1×21 + 0×20 = 1×2 + 0×1 =2+0
3 11 = 1×21 + 1×20 = 1×2 + 1×1 =2+1
4 100 = 1×22 + 0×21 + 0×20 = 1×4 + 0×2 + 0×1 =4+0+0
The overflow problem discussed for integers can also occur in real
roundoff error numbers if there are not enough bits to store the exponent. A roundoff error
occurs when there are not enough bits to store the significand.
What is a File?
A file is related data stored on a persistent media. A file can be an appli-
cation (program) or the product of an application. For example, a word
File Size Limitations processor application is used to create document files. As another example,
a digital camera is used to create photo files. A file is stored on a persistent
File size can be decreased
or compressed using a
media so that it is retained even after the computer or computerized device
compression program, such is turned off. A file can be used over and over again whenever the data it
as WinZip. This technique is stores is needed.
often used to accommodate
storage device and e-mail A file is really just 1s and 0s because it is stored in binary code. Computers
account limitations. are programmed to translate bytes and words into symbols. Depending
on the file type, these symbols are either human-readable or computer-
readable after translation. Human-readable files are called text files, and
computer-readable files are called binary files. Simple files, such as a text
document, can be measured kilobytes, for example 64K. The K comes from
the word kilo and represents 210 or 1,024. Therefore, a 64K file uses 65,536
bytes (64×210) of storage.
File types are distinguished by the extension that comes after the file
name. An application adds a unique extension to the files it creates. For
Extensions example, MyResume.docx is a document file type. A .docx file is a binary
file created using Microsoft Word. Executable files are .exe files and are
Common extensions include:
also binary files. A file named TestData.txt is a plain text file. A .txt file
.xlsx - Excel file contains only letters, numbers, and common symbols readable by humans.
.class - Compiled Java file Folders are used to organize commonly related files.
.java - Java file
.zip - compressed file Binary files are more complex than text files and often contain data for
.gif - GIF image file photos, formatted text, spreadsheets, sound, and so on. The disadvantage
.bmp - Bitmap graphic of binary files is that they require another application to interpret the
contents. A binary file may have content similar to:
ÿÿñU_ÿÿþ}9UTýÿ–÷}]Ï_ñÿÑßÿÿý ÿ×_ÿ÷Äõÿ
TIP The format an application
ÿ ÿ ð – U _ÿ ÿ w u s U U ü w] U/ U _ ñ ÿ U Ww w t w wU Ww wD õ ÿ
normally uses for saving a file
is called native format. þ»ÿÿúªî¿þÿþûïûüÿ¾þïìÿ
þÿÿï¿¿ÿïìôÿ UÿÿüET_ÿÿ÷wìÿ–þ»ÿÞþïýÿþøÿ¯ÿëÿúþÿ«ºòÿþýÿûÿûèôÿ
ÿÝþ_ÿÿ ÿwþuUuWýw÷÷ÿ{þÿß¿ß÷ÿuWwwu÷uuUUwwDõÿþ»ÿÌ®è lïÿþ
>«~﮿þÿ
ýUÝUUÕ]UU]UÕ]Õ]æÝDôÿ¿Îÿàôÿøÿ
ßýÕW_ý_õW_ÕÕ]uåÿDõÿþ¿óÿïþÿÿþáÿèôÿøwÿuþWuWUUwWþUåwDõ
ÿþ
A binary file is computer-readable
Internal devices are drives mounted inside the PC case. These devices
can include hard disk, CD/DVD, disk, tape, Zip, and Jaz drives. Except for
the Iomega® RRD (Removable Rigid Disk) system, which uses a removable
media, hard drives typically have permanently installed disks that are not
accessible from outside the PC case. Other devices have an external slot
for removable storage media.
External devices have a stand-alone drive housing and connect to a
computer’s USB port with a cable. USB (Universal Serial Bus) is a standard-
ized technology with data transfer rates up to 480 Mbps. As many as 127
devices can be connected to a single port with USB hubs.
External drives offer the advantage of portability because they can be
easily moved to other computers that support the technology. External
devices include hard disk, RRD, CD/DVD, diskette, tape, Zip, and Jaz
drives. Except for the hard disk drive, these drives have removable
media.
Ultra-portable devices include keychain, watch, mini drive, and mouse
storage to name just a few. These external devices are small and easy-to-
use, but currently more expensive than comparable storage devices that
are larger in size. Most ultra-portable devices, including the keychain and
mini drive, have storage media attached directly to a USB plug that is con-
nected to a USB port. The watch and mouse storage devices use a cable
with a USB plug to connect to a USB port. The watch has a short cable and
USB plug hidden in the band. The mouse storage device requires a longer
cable so that it can also function as a pointing device.
Firewire Storage device technologies determine the media, size, and portabil-
Using the IEEE 1394 standard, ity of a device. Magnetic technology uses a mechanical drive with tiny
a FireWire port allows devices electromagnetic heads for reading and writing data to media. The media
to quickly t rans fe r lar ge required with magnetic technology is a disk, usually made of aluminum or
amounts of data (greater than
Mylar®, coated with iron oxide. The disk is either encased in hard plastic
400Mbps). FireWire is often
used for digital video cameras
(floppy diskette and Zip) or several disks, called platters, are sealed in a
and sometimes external hard case (Jaz, RRD, and hard disk). A data signal sent through the heads in
drives because of the amount the drive magnetize a bit of the media in one direction to store a 1 and in
of data associated with these the other direction to store a 0.
devices. FireWire devices can
be daisy-chained together, Optical technology uses a drive with a laser and an optoelectronic sen-
which means one device sor. The media required with optical technology is a compact disc made
is connected to another’s of polycarbonate plastic. A CD-R (CD-Recordable) disc is used for stor-
FireWire port and that device ing files. CD-Rs are coated with a reflective organic compound and then
is connected to another and so sealed with a plastic layer to protect the reflective layer from scratches.
on. FireWire also supports iso-
The laser in the drive is focused on a bit of the CD-R to darken, or “burn,”
chronous mode for real-time
data transfer. the organic compound to store a 1. The areas of the CD-R left unburned
are read as bits storing a 0.
Telecommunications
Telecommunications is the transmitting and receiving of data. Data can be
in various forms including voice and video. Telecommunications requires
TIP Access to the Internet a modem or adapter and a line or cable. The speed of data transmission
re quire s tele communica-
tions and an Internet Service
(sending) and receipt (receiving) is measured in Kbps (thousands of bits
Provider (ISP). per second) or Mbps (millions of bits per second). Numerous telecommu-
nications options are available, which vary in speed and cost:
• A conventional modem uses standard telephone lines to convert
analog signals to digital data. A conventional modem is a 56 Kbps
modem, which transmits data at 28.8 Kbps and 36.6 Kbps, and
receives data at 56 Kbps. Home computers sometimes use a con-
ventional modem.
• A DSL (Digital Subscriber Line) modem uses standard telephone
TIP In a wireless network, a
router/wireless access point is lines with data transmission up to 640 Kbps. Data receipt is from
typically connected by a cable 1.5 Mbps to 9 Mbps. A DSL (Asymmetric DSL) is the most common
to a cable or DSL modem. form used.
• A cable modem transmits data through a coaxial cable television
network. Data transmission is from 2 Mbps to 10 Mbps and data
receipt is from 10 Mbps to 36 Mbps.
• Leased/Dedicated lines are used by many businesses and schools
for Internet access. They allow for a permanent connection to the
Internet that is always active. The cost of a leased line is usually a
fixed monthly fee. A T-1 carrier is a type of leased line that trans-
mits data at 1.544 Mbps.
• ISDN (Integrated Services Digital Network) is a digital telephone
network provided by a local phone company. ISDN is capable of
transmitting and receiving data at up to 64 Kbps. ISDN requires
the use of an ISDN terminal adapter instead of a modem.
Blog
Blog is short for weblog and is
a type of Web site where users
can post entries in a journal
format.
TIP Just because a file is Information on a Web site is sometimes in the form of a downloadable
available on a Web site for file. Downloading is the process of copying a file from a Web site to the
download does not mean that user’s computer. For example, virus definitions can be downloaded from a
it is legal to download the file. antivirus software company’s Web site and software updates can be down-
Downloading copyrighted loaded from the software company’s Web site. When a file is downloaded,
files that have not been made the user specifies where the file should be saved on the local computer.
freely available is a violation of
Files should only be downloaded from known, authentic Web sites since
copyright law.
downloadable files are often associated with viruses.
If information from a Web site is to be referenced or quoted in a report,
essay, or other document, a citation must be used to give credit to the
original author and allow the reader to locate the cited information. A
widely accepted form for citation is published by the Modern Language
MLA Association (MLA) in its publication MLA Handbook for Writers of Research
Papers, Sixth Edition.
A citation of a personal Web site does not have many details and may
look similar to:
Rawlings, Julie. Home page. 23 Dec. 2007. 15 May 2009
<http://www.Lpdatafiles.com/jrawlings/index.htm>.
crackers, hackers Newspapers have carried numerous reports of crackers, or hackers, gain-
ing access to large computer systems to perform acts of vandalism. This
malicious act is illegal and can cause expensive damage. The Electronic
Address A unique binary representation of a location Cookie Text file created by the server computer
in memory. when a user enters information into a Web site.
Address bus Carries memory addresses that indi- Copyright Protects a piece of work from reproduc-
cate data storage locations. tion without permission from the work’s author.
ALU (Arithmetic Logic Unit) The part of the CPU CPU (Central Processing Unit) Processes data and
that handles arithmetic and logic operations. controls the flow of data between the computer’s
other units. Also contains the ALU. Located on the
Antivirus program Software used to detect and
motherboard.
remove viruses.
Cracker Person who accesses a computer system
Applications software Program written to perform
without authorization.
a specific task.
Cross-platform connectivity The ability of one
Base unit Housing that contains the mother-
type of PC to link to and share data with a different
board, CD-RW/DVD drive, disk drive, and hard
type of PC.
disk drive.
Dedicated line See Leased line.
Binary number system Number system used by
computers that uses only digits 0 and 1. Also called Device driver One type of utility program.
base 2.
Downloading The process of copying a file from
Bit (BInary digiT) A single 0 or 1 in binary code. a Web site to the user’s computer.
Bus A central network cable. Also a set of circuits DSL (Digital Subscriber Line) modem A modem
that connect the CPU to other components. that uses standard telephone phone lines. ADSL is
the most common form used.
Bus topology A physical LAN topology that uses a
single central cable to attach each node directly. E-mail (electronic mail) The sending and receiving
of messages and electronic files over a communica-
Byte A group of 8 bits.
tions network such as a LAN or the Internet.
Cable modem A modem that transmits data through
E-mail client Software used to create, send, receive,
a coaxial cable television network.
and organize e-mail messages.
Cache High-speed memory used to store frequently
Environment A computer’s hardware and soft-
used data so that it can be quickly retrieved by an
ware configuration. Also referred to as platform.
application.
Environment types include desktop, multiuser, net-
Client A computer that is sent information from a work, handheld, distributed, multiprocessing, and
server computer. multitasking.
Client/server network A type of network that Ergonomics The science that studies safe work
consists of a group of computers, called clients con- environments.
nected to a server computer.
Expansion boards Circuit boards that connect to the
Clock rate The speed at which a CPU can execute motherboard to add functionality to the computer.
instructions, measured in megahertz or gigahertz.
Exponent The bits that represent the exponent of
Compiler A program that converts an entire pro- a floating point number.
gram into machine code before the program is
Extension Added after a file name to distinguish
executed.
file types.
Control bus Carries control signals.
Extranet An extended intranet that provides vari-
Conventional modem A modem that uses stan- ous levels of access to authorized members of the
dard telephone lines to convert analog signals to public.
digital data.
Hexadecimal system Number system based on 16 Mailing list server A server that manages mailing
digits. Also called base 16. lists for groups of users.
High-level programming languages Third Magnetic technology Storage device technology that
generation programming languages that have uses a mechanical drive with tiny electro-magnetic
English-like instructions. heads for reading and writing data to media.
Hub A communication device that joins communica- Mbps Millions of bits per second.
tion lines at a central location on the network.
Megabytes (MB) Approximately one million
Information age Present time characterized bytes.
by increasing dependence on the computer’s
Megahertz (MHz) Million of cycles per second.
ability to store and manipulate large amounts of
information. Memory-resident A program that is always in
memory.
Input device Device used to enter data and instruc-
tions into the computer. Minus sign (–) Used in search criteria to exclude
unwanted Web pages.
Integrated circuits (ICs) A silicon wafer with intri-
cate circuits etched into its surface and then coated Modern Language Association (MLA) Organization
with a metallic oxide that fills in the etched circuit that publishes standards used for citations.
patterns. Also called a chip.
Motherboard The main circuit board inside the
Interactive Information accessed as a result of base unit.
selections made by the user.
Netiquette The etiquette that should be followed
Internet The largest and most widely accessed when using a network.
network.
Network A combination of software and hardware
Interpreter A program that translates and that allows computers to exchange data and to share
executes an instruction before moving on to the software and devices, such as printers.
next instruction in the program.
Net work architect ure The st ruct ure of a
Intranet A network that is used by a single organi- network.
zation and only accessible by authorized users.
Network interface card A circuit board that goes
ISDN (Integrated Services Digital Network) A into a computer or other device in a LAN.
digital telephone network provided by a local tele-
Network operating system Software that allows
phone company.
users and devices to communicate over a network.
IT (Information Technology) A term that
Node A location on the network capable of processing
encompasses all aspects of computer-related
information, such as a computer or a printer.
technology.
Real numbers Numbers that contain decimal Topology The physical or logical arrangement of
points. the nodes on a network.
3. Describe the flow of data between the compo- 16. List three netiquette rules.
nents of a computer, starting with input.
17. Explain why the binary number system was
4. a) Describe one difference between operating adopted for use in computers.
system software and applications software.
b) Describe three different types of operating 18. a) What is the decimal equivalent of 1112?
systems. b) What is the decimal equivalent of 2C16?
c) What does environment refer to?
19. What is Unicode?
5. What is a utility program? Give an example.
20. a) How many bytes of data can 512 MB of RAM
6. List four types of mobile computing devices. store?
b) How many bytes of data can a 40 GB hard
7. What is a stylus used for? drive store?
8. Describe one type of wearable computer. 21. What are bits grouped in units of 16 to 64
called?
9. Why is cross-platform connectivity important
to many computer users? 22. When would an overflow error occur?
10. a) What is the difference between low and high 23. a) What are real numbers?
level programming languages? b) When would a roundoff error occur?
b) L i st t h r e e h ig h -le ve l pr o g ra m m i ng
languages. 24. a) What is the difference between a text file and
c) What is the difference between a compiler a binary file?
and an interpreter? b) Explain how an extension distinguishes file
d) List an advantage of using an object-oriented types.
programming language. c) Why would organizing files into folders be
considered a good practice?
11. List four benefits of using a network.
25. List three ways storage devices can be classified
12. a) What are the two common size classifica- and give an example of a storage device in each
tions for networks? category.
b) What size classification is used to connect
devices over large geographical distances? 26. Describe three storage device technologies.
13. a) What is a network operating system? 27. List four rules that should be followed to avoid
b) What does a network environment refer damaging files stored on disks or CD/DVDs.
to?
28. a) What is the difference between an intranet
14. Describe two common network architecture and an extranet?
models. b) Who controls the Internet?
Exercise 1 ——————————————————————————
In this exercise you will research your classroom computer network by answering a series of
questions:
Exercise 2 ——————————————————————————
In this exercise you will assess the input and output devices you have access to.
Exercise 3 ——————————————————————————
In this exercise you will organize your existing files. You may need to refer to the appropriate operating
system chapter on www.Lpdatafiles.com to complete this exercise.
a) Examine the files you currently have saved on your computer. Use the appropriate
operating system command to rename any files that do not have descriptive names.
b) Use the appropriate operating system commands to organize your existing files into
appropriate folders.
a) Conduct a search on the Internet using at least two search engines to find three Web
pages that have information about Carpal Tunnel Syndrome.
b) Write a brief description of the injury.
c) In a second paragraph, write about possible treatments for the injury.
d) Write a citation for each source.
Exercise 5 ——————————————————————————
Expand on the information presented in this chapter by researching one of the following topics:
• Network Protocols
• Operating Systems
• The History of the Internet
• Evolution of Programming Languages
• Identity Theft
a) Use the Internet, magazines, and books to find at least three sources of information.
b) Write a two page report that summarizes your research.
c) Write a citation for each source.
Exercise 6 ——————————————————————————
In this exercise you will research and compare the advantages and cost of obtaining Internet access
through three different telecommunication options.
a) Use the Internet and newspapers to find information about Internet service providers
(ISPs).
b) Compare the costs and the advantages of at least three different telecommunication
options.
c) Write a one paragraph conclusion that explains what telecommunication option would
be the best choice.
d) Write a citation for each source.
a) Use the Internet, magazines, and books to learn more about at least three emerging
technologies. Look specifically for information on how these emerging technologies
impact individuals and businesses. For example, speech recognition technology greatly
impacts those individuals who must rely on voice input rather than keyboard input
for a PC.
b) Write a two-page report that summarizes the impact of and lists several functions of
the emerging technologies you have researched.
c) Write a citation for each source.
Exercise 8 ——————————————————————————
Many computer viruses have been associated with e-mail attachments.
a) Conduct a search on the Internet to find information about a virus associated with an
e-mail attachments.
b) Write a one-paragraph description of the virus. Include details, such as the damage
caused by the virus and steps necessary to remove the virus.
c) Write a citation for each source.
Exercise 9 ——————————————————————————
You have decided to investigate computer programming as a possible career path.
a) Conduct a search on the Internet using at least two search engines to find three appro-
priate bachelor degree programs.
b) List each program location (college name), the number of credits required to finish the
degree, and the tuition cost per credit or per course.
Exercise 10 ——————————————————————————
In this exercise you will investigate list serves.
Browsers
Commonly used Web browser
applications include Internet
Explorer, Firefox, Netscape,
Opera, Amaya, and Safari.
Viewing HTML
Documents
An HTML document stored
on a local computer can also
be viewed in a browser. In A Web browser is used to access and view HTML documents that have
Internet Explorer, click been published to a Web server. The Web browser first interprets the URL
j Menu Bar. Next, select File to identify the location of the page on the Web and then interprets the
j Open and then Browse to HTML document to display a Web page in the browser window. HTML
navigate to the location of the documents saved on a local computer can also be viewed in a browser.
HTML document.
Validating HTML
HTML document s can be
validated to ensure they are
meeting W3C standards at the
http ://v a lid ator.w3.or g
Web site.
An HTML document contains pairs of tags
In order to validate an HTML
document, a DTD (docu- The html, head, title, and body tags are called document tags:
ment definition tag) must be
included as the first line of an • The <html> tag tells the browser that the file contains HyperText
HTML document. For exam- Markup Language.
ple, to check to see if an HTML
document meets HTML 4.01 • The <head> tag defines the section that contains information about
standards, include the tag: the document, including its title. This section will not be displayed
as part of the document content.
<!DOCTYPE HTML PUBLIC "-
//W3C//DTD HTML 4.01// EN" • The <title> tag marks the document title. The title section
"http://www.w3.org/TR/ must be within the head section. The document title should be
hmtl4/stict.dtd"> descriptive and meaningful because it is displayed in the title bar
of the browser’s window and is also used when the user adds the
document to the browser’s Favorites list.
• The <body> tag defines the body section, which contains the doc-
ument’s content. All content must be enclosed in the appropriate
tags. For example, on the previous page, the content is marked as
a paragraph.
HTML documents are free-form, which means that spaces and blank lines
generally have no effect on how the document is interpreted. Therefore,
the document:
TIP To help make an HTML <html><head><title>An example HTML document</title>
document easier to under- </head>
stand, place document tags <body> <p>Hello world!</p></body></html>
on separate lines, except the
title tags, and use blank lines to Poorly structured HTML document
separate sections of HTML.
displays exactly the same as the HTML document on the previous page.
However, editing a poorly structured document can be time-consuming
and error-prone.
saving an HTML document An HTML document is saved with a lowercase, descriptive file name.
The file name should not contain any spaces and the .htm extension needs
to be added. If using a word processor to save the file, be sure to save the
file in text format.
JavaScript
Scripts are used to add dynamic content to an HTML document and
consist of a list of commands that execute without user interaction. Scripts
Java vs JavaScript are written in a scripting language, such as JavaScript. JavaScript is a
JavaScript is similar to the Java scripting language that is interpreted by a browser’s built-in JavaScript
programming language, but it engine.
is a separate language.
In an HTML document, JavaScript code is written as a script block
between <script> and </script> tags. Scripts are typically found in
the head section, but can be placed anywhere in an HTML document.
Displaying a message in an alert dialog box is one form of dynamic content
that can be added to an HTML document using a script:
T I P Java S cript is c a s e
sensitive. <head>
<title>JavaScript Greeting</title>
<script type="text/javascript">
// Display a greeting
alert("Hello World!");
</script>
</head>
JavaScript Files • The type attribute in the script tag specifies which scripting
Scripts can also be written as a language is used to define the script.
separate JavaScript file, which
is saved with a .js extension,
• // is used to add a single line comment that explains the script.
and then referenced in the • a ler t() displays an alert dialog box with the specified text
script tag. message.
• A semicolon is used to end each JavaScript statement.
Review: welcome.htm
Create an HTML document that contains a script block that prompts the user for their full name and then
displays the message “Welcome to our site Full Name”, replacing Full Name with the user’s name, in an alert
dialog box.
The script above is interpreted when the HTML document is loaded, and
displays a message in the status bar of the browser window:
Java Applets
A Java applet is a small Java application that is embedded in an HTML
TIP This section provides document and run in a browser window. When a browser interprets a
a brief overview on writing document that contains a Java applet, the program files are downloaded
Java applets. You may want onto the user’s machine and then the browser’s Java interpreter runs the
to revisit this section after
becoming familiar with the
applet. Java applets are well suited for the Web because they are able to
Java programming language. run on different hardware and across different platforms. Applets are
secure because they do not have the ability to read or write to files on a
user’s computer.
Numerous applets can be downloaded from the Web and embedded in
an HTML document to add dynamic content. Applets take various forms,
such as animated banners, stock ticker tapes, photo cubes, and animated
video clips. Original applets can also be created.
import java.awt.*;
import java.applet.*;
String message;
<body>
<applet code = "FirstApplet.class" width = "300" height = "60">
You are unable to view the applet.
</applet>
</body>
<object> Tag
The <applet> tag has three required attributes:
The <object> tag allows for
multimedia resources, such as • code=“name” specifies the name of the applets to run
video and audio, to be embed-
ded in an HTML document.
• width=“value” specifies the width for the applet display in pixels
When interpreting an <object> • height=“value” specifies the height for the applet display in
tag, the browser determines if pixels
another application, such as
the Windows media player, is
needed to display the object.
Save the modified System Check HTML document in the classes folder in the CLOCK folder, which is included
as a data file for this text.
HTML Tags
In addition to applets and scripts, a Web page can contain text. For
HTML 4 example, consider the following Web page:
The HTML for the Web page is shown below. The body section of the
HTML document includes the content and tags that format the content:
<body>
<h1>Computer Viruses</h1>
<hr>
comments Comments are text used to explain and clarify HTML to the reader of an
HTML document. They do not appear in a browser window. Comments
start with an angle bracket, followed by an exclamation mark and two
hyphens. At the end of the comment are two more hyphens and an ending
bracket, <!--comment-->.
lists Lists are used to organize information. Bulleted and numbered are
two types of lists that can be created in an HTML document. A bulleted
list, also called an unordered list, is used when each item is equally impor-
tant. A numbered list, also called an ordered list, is used to show priority of
importance.
Bulleted list tags include:
• <ul> </ul> defines the start and end of a bulleted list
• <li> </li> defines the start and end of an item
The anchor tag (<a>) is used in an HTML document to mark text that is
a link. The href attribute is set in the tag to the name of the linked docu-
ment. For example, <a href="digicam.htm">digital cameras</a>.
A hyperlink, also called a link, is text displayed in a browser window
that can be clicked to display a different HTML document in the browser
window. Hyperlinks are what make a hypertext system, such as the Web
TIP Visited hyperlinks are work. Hyperlinks are typically displayed as blue, underlined text in the
typically displayed as purple,
underlined text in the browser browser window. Countless documents can all be linked, allowing the
window. user to go from topic to topic, or browse HTML documents.
A table requires several tags for formatting:
• <table> </table> creates a table.
TIP Tables can also be used to • <th> </th> creates a table header, which is a cell with bold, centered
control the layout of an HTML text.
document by placing content
in table cells and setting the • <tr> </tr> defines the start and end of a table row.
border attribute to 0. • <td> </td> defines the start and end of a table data cell.
Style Sheets
A style sheet is used to define the type, paragraph, and page formats
for an HTML document. Style sheets give HTML documents a consistent
appearance because they override the browser settings that interpret how
tags are displayed:
embedded style sheet A style sheet can be embedded or linked. An embedded style sheet is
defined within <style type="text/css"> and </style> tags in the head
section of the HTML document. The embedded style sheet for the Web
page above appears as:
<html>
<head>
<title>Computer Viruses</title>
<!--apply style sheet rules to the document-->
<style type="text/css">
h1 {color: #FF0000; text-align: center}
p {font-family: Georgia, "Times New Roman", Times, serif;
font-size: 16 px; line-height: 18 px}
ul {font-family: Georgia, "Times New Roman", Times, serif;
font-size: 14 px; line-height: 18 px}
ol {font-family: Georgia, "Times New Roman", Times, serif;
font-size: 14 px; line-height: 18 px}
h4 {text-align : right}
</style>
</head> …rest of HTML document
class A class is a set of declarations that can be applied to different tags. Class
names begin with a dot (.). For example:
.para _ with _ space {
font-family: Georgia, "Times New Roman", Times, serif;
font-size: 14px;
line-height: 28px;
}
Style Sheet Class
The class above can be applied to individual paragraphs to format the
paragraph in 14px Georgia with a line-height of 28 px. For example:
<p class="para _ with _ space">Spyware is software that collects
information without the user's knowledge. The information is
usually for advertising purposes.</p>
text and background color To change the background and text color of an HTML document, the
HTML body element is modified in a style sheet rule:
body { background-color : #000000; color : #FFFFFF }
text alignment HTML content is left aligned by default. To change the alignment of an
entire HTML document, the HTML body element is modified in a style
sheet rule:
body { text-align : center }
Chapter Summary
Most Web pages are created using HTML (HyperText Markup Language)
and other code. HTML is a markup language that is well suited for the Web
because it supports hypertext and multimedia. HTML uses a set of codes,
called tags, to “mark up” plain text so that a browser application, such as
Internet Explorer, knows how to display the text in a browser window.
Scripts are used to add dynamic content to an HTML document.
JavaScript is a scripting language that is interpreted by a browser’s built-
in JavaScript engine. In an HTML document, JavaScript code is written as
a script block between <script> and </script> tags.
A Java applet is a small Java application that is embedded in an HTML
document within the <applet> and </applet> tags and run in a browser
window. Applets can be downloaded from the Web and embedded in an
HTML document to add dynamic content. Original applets can also be
created. Parameters allow users to specify custom values to use in a Java
applet. In an HTML document, parameter information is specified in a
<param> tag.
Attribute Used to modify the features of an element Multimedia Images, video, audio, and Java applets
in an HTML tag. embedded in an HTML document.
Bulleted list A list that is used when each item is Numbered list A list that is used to show a priority
equally important. of importance.
Class A set of declarations that can be applied to Ordered list see Numbered list.
different tags.
Parameters Used to specify custom values to use
Comment Text used to explain and clarify HTML in a Java applet.
for a reader.
Rule A line in a browser window for dividing
Declarations The formats to be applied in a style content.
sheet rule.
Scripts Used to add dynamic content to an HTML
Document tags The html, head, title, and body document. Scripts are written in a scripting language,
tags. such as JavaScript.
Element The part of an HTML tag placed inside Selector The HTML element being redefined in a
angle brackets (<>). For example, <title> is called style sheet rule.
the title tag, where title is the element.
Style sheet Used to define the type, paragraph, and
Embedded style sheet A style sheet defined with page formats for an HTML document.
<style> and </style> tags in the head section of an
Tables Used to arrange data in an HTML
HTML document.
document.
Free-form Spaces and blank lines generally have
Tag Comprised of an element inside angle brackets
no effect on how the document is interpreted. The
that is used to “mark up” plain text so that a browser
format of an HTML document.
application knows how to display the text.
Hexadecimal A base-16 numbering system that
Unordered list see Bulleted list.
consists of the numbers 0 through 9 and the letters
A through F. Web Tool used to search and access information
available on the Internet.
HTML (HyperText Markup Language) A set of tags
that are used to “mark up” plain text so that a browser Web browser application Provides a graphic inter-
application knows how to display the text. face to present information in the form of a Web
site.
Hyperlink Text that can be clicked to display another
HTML document. Also called a link. Website Series of related Web pages.
Hypertext A database system where objects, such
as text and images, can be linked.
Java applet A small Java application that is
embedded in an HTML document and run in a
browser window.
JavaScript A scripting language that is interpreted
by a browser’s built-in JavaScript engine.
Link see hyperlink.
Linked style sheet A style sheet saved as a sepa-
rate file with a .css extension and applied using a
<link> tag.
1. a) What is the most widely used Internet 8. a) What does a style sheet define?
service? b) Why are style sheets used?
b) List two examples of Web browsers. c) What is the difference between an embedded
and a linked style sheet?
2. a) What is used to create most Web pages?
b) Why is HTML well suited for the Web? 9. What element is modified to change the back-
c) Why is it important for the W3C to develop ground color or alignment of a Web page?
Web standards?
True/False
3. Why is the order of HTML tags and content
important in an HTML document? 10. Determine if each of the following are true or
false. If false, explain why.
4. a) List the four document tags. a) A Web site consists of a series of Web
b) Why is it important to properly structure an pages.
HTML document when HTML is a free-form b) Hypertext is a database system.
language? c) An HTML document must be published to
c) What rules are followed when saving an a Web server in order to be viewed in a Web
HTML document? browser.
d) Spaces and blank lines generally have no
5. a) Where are scripts placed in an HTML docu- effect on how an HTML document is inter-
ment? preted.
b) How can scripts enhance a Web site? e) HTML documents are saved with a TXT
c) Write a script to display “Good-bye” in an extension.
alert dialog box. f) Scripts must be placed in the head section of
d) Write a script to display “Today’s News” in an HTML document.
the status bar of the browser window. g) JavaScript is used to add dynamic content to
an HTML document.
6. a) What is a Java applet? h) Java applets are i nter preted on Web
b) How is a Java applet interpreted by a Web servers.
browser? i) Java applets can only run on a Windows
c) List two reasons why Java applets are well platform.
suited for the Web? j) Java applets have the ability to write files on
a user’s computer.
7. The following HTML document has seven k) Java applets have to be compiled.
errors. What are they? l) T he a nc hor t ag i s u s e d to c r e at e a
hyperlink.
<html> m) A rule modifies an HTML element.
<body>
<title>Operating Systems</title>
</body>
<head>
<!--adds a horizontal rule>>
<hr width is 50%>
<p>Every computer must have an operat-
ing system. Types of operating systems
include:</p>
<ul>
<li>Windows<li>
<li>UNIX</li>
<li>Linux</li>
<li>OS/2</li>
</ul>
</head>
</html>
TIP Applications use, or An application is a type of package. It contains a controlling class and
import, packages to define can contain other classes as well:
objects.
TIP Virtual means not real. Compiled Java source code is called bytecode. Executing a Java applica-
A virtual machine is there- tion means that its bytecode is interpreted with the Java Virtual Machine
fore conceptual, not made of (Java VM), part of the Java 2 platform. The interpreter runs each bytecode
hardware and other physical instruction as it is read. The Java VM can reside on any computer, regard-
components.
less of operating system environment, making Java applications extremely
portable, reliable, and platform-independent.
Although bytecode is versatile for porting applications to several dif-
Platform-Dependent ferent environments, programs compiled to machine code run faster.
Programming languages such Machine code is comprised of just 1s and 0s and is different depending on
as C++ and Visual Basic are the computer platform. A just-in-time compiler (JIT) converts bytecode to
compiled directly to machine machine code before it is executed with the Java VM.
language. Although faster,
t h e s e p r o gram s mu s t b e A program containing syntax errors will not compile. A syntax error
recompiled for every platform occurs in a statement that violates the rules of Java. For example, all Java
that will run the application.
statements must end with a semicolon. A statement without a semicolon
generates a syntax error when the program is compiled, preventing the
compiler from generating bytecode for the application.
Review: Greeting
Create a Greeting application similar to the one shown in the “A Java Application” section. Refer to Appendix
B for guidance with JCreator Pro. Your instructor may also have specific information regarding your com-
piler. The goal of this review is to write the source code for a simple application and then compile and run
the code.
argument The print() and println() methods require arguments. An argument is data
passed to a method for processing. In this case, the print() and println()
string arguments are strings. A string is a set of characters, which are enclosed
by quotation marks.
MulticulturalGreeting produces output similar to:
escape sequence An escape sequence is a backslash (\) followed by a symbol that together
represent a character. Escape sequences are used to display special char-
acters. Common escape sequences include:
\n newline
\t tab (8 spaces)
\\ backslash
\" double quotation mark
The modified MulticulturalGreeting illustrates the use of escape
sequences:
/**
* Displays a welcome message.
*/
public class MulticulturalGreeting {
Formatting Output
The format() method can be used in place of the print() or println()
methods to control the way output is displayed. The format() method
arguments include a format string and an argument list. The format
NumberFormat Class string contains specifiers that indicate how the corresponding strings in
The NumberFormat class, the argument list should be displayed. The following code demonstrates
discussed in Chapter 4, can the format() method:
also be used to format numeric
data. System.out.format("%-10s %8s %8s", "Team", "Wins", "Losses\n");
System.out.format("%-10s %8s %8s", "Jaguars", "10", "5\n");
System.out.format("%-10s %8s %8s", "Cheetahs", "14", "1\n");
System.out.format("%-10s %8s %8s", "Panthers", "8", "7\n");
System.out.format("%-10s %8s %8s", "Penguins", "4", "11\n");
displays:
Code Conventions
Code conventions are a set of guidelines for writing an application. These
guidelines provide details about commenting, rules for naming methods,
classes, and packages, and statement formatting. Just as comments inform
a reader about a segment of code, a program that follows specific code
conventions is easier to read and understand.
A company or organization that employs programmers will typically
adhere to specific code conventions. A programmer familiar with the
code conventions will more quickly become familiar with code written
by another programmer in the company. Code conventions can make
modifying and maintaining code faster, easier, and less expensive. Because
of these benefits, organizations often not only encourage the use of code
conventions, but require it.
The code conventions introduced in this chapter are:
TIP Code conventions are
important. About 80% of the • An introductory comment should begin a program. This comment
lifetime cost of a piece of soft- should include information such as your name, class name, the
ware goes to maintenance.
date, and a brief statement about the program.
Rarely is software maintained
for its whole life by the original • Package names should begin with a lowercase letter and then an
author. uppercase letter should begin each word within the name. Package
names may not contain spaces.
• Class names should be nouns and begin with an uppercase letter
and an uppercase letter should begin each word within the name.
Class names may not contain spaces.
• A comment block should be included before each class and
method. A comment block is not typically placed before the main()
method.
• Comments should not reiterate what is clear from the code.
• Statements in a method should be indented.
• An open curly brace ({) should be placed on the same line as
the class or method declaration, and the closing curly brace (})
should be on a separate line and aligned with the class or method
declaration.
Chapter Summary
This chapter introduced Java, which is an object-oriented program-
ming language. OOP languages evolved out of the need to better develop
complex programs. In addition to being object-oriented, Java applications
are platform independent and can run on any computer, regardless of the
operating system or hardware configuration.
Object-oriented languages use classes to define objects. A class defines
the type of data and actions associated with an object, but not the actual
data for an object. A package groups related classes.
A Java application is a package with at least one class. Statements in an
application provide instructions. Methods are a named set of statements
that perform a single, well-defined task. Comments in an application
provide details about the code to the reader. Comments can be single or
multiline and can also be extracted for documentation.
The code typed by a programmer is called source code. The source code
is translated to bytecode with a compiler. Program execution occurs when
the bytecode is interpreted with a Java Virtual Machine (Java VM). The
Java VM can reside on any computer. A just-in-time (JIT) compiler converts
bytecode to machine code before execution by the Java VM. Although
less portable, machine code is faster. If a program contains errors, it will
not compile. One type of error is the syntax error, which results when a
statement violates the rules of Java.
Program output is through the output stream. The standard output
stream is typically the computer screen and requires the System.out meth-
ods print() and println(). These methods require a string argument.
Escape sequences are used to display special characters. Output can be
formatted with the format() method.
Code conventions are a set of guidelines for writing an application. The
code conventions introduced in this chapter are:
• An introductory comment should begin a program. This comment
should include information such as your name, class name, the
date, and a brief statement about the program.
• Package names should begin with a lowercase letter and then an
uppercase letter should begin each word within the name. Package
names may not contain spaces.
• Class names should be nouns and begin with an uppercase letter
and then an uppercase letter should begin each word within the
name. Class names may not contain spaces.
• A comment block should be included before each class and
method. A comment block is not typically placed before the main()
method.
Algorithm A set of steps that outline how to solve Method A named set of statements that perform
a problem. a single, well-defined task. A method is always a
member of a class.
A r g u ment Dat a passed to a met hod for
processing. Object A named entity that consists of related
data and instructions for performing actions on
Bytecode Compiled Java source code.
that data.
Class The description of an object.
Objec t- or iented pr og ra m m i ng ( OOP ) A
Code conventions A set of guidelines for writing systematic, modular approach to developing complex
an application. programs.
Comment Text that provides information to the OOP see Object-oriented programming.
reader of program code.
Output Stream Sends data to an output device,
Comment block Multiline comments that describe typically the computer screen.
a program, class, or method.
Package A group of related classes. Also called a
Compiling The process where source code is con- library.
verted to code the computer understands.
Platform-independent application A program that
Controlling class The class in an application that can be run on any computer regardless of operating
contains the main() method. system or hardware configuration.
F lowcha r t A visual representat ion of a n Source code The code typed by a programmer.
algorithm.
Statement An instruction in a program.
Importable Package code that can be used by an
String A set of characters.
application.
Syntax error A statement that violates the rules
Inheritance An object-oriented language feature.
of Java.
Interpreter Software that runs each bytecode
instruction of a compiled Java program.
Java application A package with a controlling class
and possibly other classes.
Java Virtual Machine (Java VM) The Java bytecode
interpreter.
Just-in-time compiler (JIT) Software that converts
bytecode to specific machine code.
Library see Package.
Machine code The most basic computer language,
which is comprised of just 1s and 0s.
1. a) List three features of every object-oriented 12. Explain the difference between the print() and
programming language. println() methods.
b) Explain, in your own words, what you think
the meaning is of each of the three features 13. Explain the advantages of using the format()
listed in part (a). method in place of the print()and println()
methods.
2. Draw a sketch that shows the relationship, and/
or hierarchy, of object, class, and package for the 14. There are five places in which the application
package File, class FileReader, and the object below does not follow the code conventions
fileInput. outlined in this chapter. Where are they?
/*
3. Write an appropriate comment block for the * getGreeting.java
beginning of a program to describe an applica- * What's wrong application.
tion that is intended to calculate test averages. * Student Name
*/
4. Write an appropriate comment for describ-
package notSoGood;
ing a class that displays the average of a set of
scores. /**
* Good Morning is displayed.
5. Write a statement that declares a package with */
the name gradeCalculator. public class getGreeting {
Exercise 2 —————————————————————BingoRules
Create a BingoRules application that displays the rules for playing bingo. Place each rule on a separate
line and place a blank line between rules. The application output should look similar to:
a) Add the compiler name to the right of “Compiler” and then explain how to create a new
project, enter source code, compile, and run a Java application using a format similar
to:
b) Explore the compiler’s help features. Add documentation that explains how to use
the compiler’s Help features.
b) The hexadecimal, or base 16, system is based on 16 digits: 0 through 9, and the letters
A through F representing 10 through 15 respectively. Modify the BinaryNumbers
application to include a Hexadecimal column that contains the corresponding
hexadecimal numbers.
b) Use books and the Internet to research other object-oriented programming languages
and add three additional object-oriented programming languages to the list.
Declaring Variables
A variable is a name for a value stored in memory. Variables are used in
programs so that values can be represented with meaningful names. For
example, when a variable named length is used in a program, it is clear
that its value is a distance. Variables should be used to represent values
because they make code easier to read, understand, and modify.
data type The declaration includes two parts. The first is the data type, which
determines the type of data the variable will store. The second part of a
identifier declaration is the variable name, called the identifier. For example, in the
declaration
int length;
int is the data type and length is the identifier. An int stores an integer
value, which is a positive or negative whole number. When an integer
variable is declared it stores the value 0.
An identifier must begin with a letter and contain only letters, numbers,
and some special characters. Typically variable identifiers begin with a
lowercase letter. Any word after the first in a variable identifier should
begin with an uppercase letter. For example, rectangleLength. This code
convention allows variables to be easily recognized.
Multiple variables with the same data type can be declared in a single
statement, similar to:
int length, width;
An int variable uses 4 bytes of memory to store its value and is used
for representing whole numbers.
Values that are represented by the double data type are sometimes
floating point referred to as floating point, meaning that the values contain numbers after
the decimal point. Because of the many digits that are possible in a double,
a variable of this type uses 8 bytes of memory.
A char variable requires 2 bytes of memory because Java uses the 16-
TIP Java also supports the bit Unicode character encoding. Assignment to a char variable requires
byte, short, long, and float
primitive data types.
enclosing a single character in single quotation marks, as in 'a'.
Variables that are type boolean can have only one of two values—true
or false. Boolean variables are particularly useful for representing yes/no
or on/off values.
choosing data types When choosing a data type, it is important to choose the most appropri-
ate type for the quantity being represented. If a value could possibly have
a decimal portion, then double is the best choice. If a variable will represent
TIP Primitive data types are only whole numbers, then int is the best choice even though double will
also called built-in data types. work. Using the most appropriate data types for variables has two benefits.
First, both the compiler and the reader will understand the possible values
for a variable. Second, the compiler allocates the appropriate memory for
the variable.
object A variable declared with a class is called an object. The variable itself
actually stores a reference to the area in memory where the object’s data
and methods are stored:
The new operator allocates memory for the object and returns a reference
to the object. <arguments> are used to initialize the data for the object.
The code below creates a new object using a class named Circle:
Circle spot = new Circle(4); //spot with radius 4
In this statement, the variable spot refers to a Circle object that has been
initialized with a radius of 4.
To access a member of a class, such as a method, use the object name
followed by a dot (.) and then the member name. For example, the code
below executes method members getRadius() and area():
Circle spot = new Circle(4);
System.out.println("Radius of spot is " + spot.getRadius());
System.out.println("Area of spot is " + spot.area());
The class name starts with an uppercase letter, following the appropriate
naming convention for class names. If several classes in a package are to
be accessible, then a statement that imports the entire package may be
used:
import java.util.*;
The asterisk (*) indicates that all members of the util package are to be
accessible. import statements must appear after a package statement and
before any class definitions. Java applications automatically import the
java.lang entire java.lang package.
The next() method is used for reading a string that does not contain
spaces. For example, “apple”. Attempting to read the string “apple pie”
generates a run-time exception called InputMismatchException. An
exception exception is an error affecting program execution. Exceptions are discussed
later in this chapter.
/**
* Calculates and displays the area of a rectangle
* based on the width and length entered by the user.
*/
public class RectangleArea2 {
Note that the import statement appears above the class. RectangleArea2
produces output similar to the following when values 6 and 2 are typed
by the user:
Real division returns the entire quotient, including the decimal portion,
and is performed when one or both operators are type double.
modulus division Modulus division returns the remainder resulting from division. The %
operator truncates the operands, if necessary, to return an integer:
Review: Digits
Create a Digits application that prompts the user for a two-digit number and then displays the ones-place
and tens-place digits.
Type Casting
Type casting converts a number of one type to a number of a different,
but compatible type. For example, a double can be cast as an int, as in the
statements:
int i = 2;
double d = 3.7;
int x;
x = i * (int)d //d is explicitly cast; x is assigned 2x3
Type casting is necessary in this case because one of the operands in the
expression has less precision than the variable that will store the result.
Explicit casting also makes it clear that the programmer intended for the
calculation result to be an int.
Review: TempConverter
Create a TempConverter application that converts a Fahrenheit temperature to the corresponding Celsius
temperature. The formula for converting Fahrenheit to Celsius is C = 5/9(F – 32). The application should
prompt the user for the Fahrenheit temperature. Be sure to carefully form the expression. Parentheses will
be needed to specify the order of operations.
Assignment Operators
In an assignment statement, the expression on the right side of the equal
sign (=) is evaluated first and then that value is given to the variable on
the left. Because the expression on the right is evaluated before an assign-
ment is made, it is possible to use the current value of the variable in the
expression itself. For example:
numPlayers = 12; //numPlayers is assigned 12
numPlayers = numPlayers + 2; //numPlayers is now 14
Changing the value of a variable based on its current value is often done
in programming. Therefore, in addition to the = assignment operator, Java
recognizes the +=, -=, *=, /=, and %= assignment operators. These operators
perform an operation before making an assignment. For example, the
previous assignment statement can be rewritten as:
numPlayers += 2; //numPlayers is now 14
The -=, *=, /=, and %= operators work similarly, as in the statements:
numPlayers -= 3; //same as: numPlayers = numPlayers - 3
numCopies *= 5; //same as: numCopies = numCopies * 5
total /= 2; //same as: total = total / 2
remainder %= 6; //same as: remainder = remainder % 6
Although not keywords, true, false, and null are reserved and not for
use as identifiers.
Programming Errors
There are many types of errors that can occur in a program. Some errors
are found by the compiler. Others occur at run time. A program that has
been carefully designed will have fewer errors. Code reuse can also lead to
fewer errors because packages that have been carefully tested and properly
documented produce cleaner and more robust code.
syntax error Errors that violate the rules of Java are called syntax errors. For example,
forgetting a semicolon at the end of a statement generates a syntax error.
Syntax errors are found by the compiler. An application with syntax errors
will not run because it will not compile.
The statements assign the value 9 to area rather than the expected 10.24.
Although, it is possible that the programmer intended for the value to be
truncated, it is more likely that variables length and area were supposed
to be declared as double.
Logic errors must be found by the programmer through testing and by
carefully examining the source code. Accurate and careful commenting,
proper indentation, and descriptive identifiers can help in finding and
preventing logic errors.
run-time error, exception Errors that are not detected by the compiler may generate a run-time
error. A run-time error, also called an exception, halts program execution
at the statement that cannot be executed. For example, although the state-
ments below are syntactically correct, they will generate a run-time error
because division by 0 is undefined:
int totalScores = 40;
int totalTests = 0;
double avgScore;
avgScores = totalScores / totalTests;
The program only had code to handle numeric user input. When a letter,
rather than a number was typed, an exception was “thrown.” Writing code
to handle exceptions is discussed in Chapter 12.
BirthdayGame Implementation
Based on the code design, the BirthdayGame implementation follows:
/*
* BirthdayGame.java
*/
import java.util.Scanner;
/**
* Plays a birthday guessing game with one player.
*/
public class BirthdayGame {
Chapter Summary
Variables and constants are used in programs so that values can be
represented with meaningful names. Variables and constants should be
used because they make code easier to read, understand, and modify.
Both variables and constants are created with a declaration statement.
A variable declaration includes the data type and identifier. A constant
declaration also includes the keyword final. Identifiers are case sensitive
and cannot be the same as a Java keyword. The value of a variable can be
changed throughout program execution with assignment statements. The
value of a constant cannot be changed from its initial assignment.
A primitive data type stores a single piece of data and can include int,
double, char, and boolean. Abstract data types include classes. Each class
defines not just a single piece of data like a primitive data type, but a set
of data along with methods for performing actions on that data. Variables
declared with an abstract data type are called objects. An object declara-
tion is called instantiation. An object is instantiated with the keyword
new.
Data can be read from the user at run time by using the Scanner class.
This class processes data from the input stream. Objects that read data
from the keyboard are initialized with System.in. When obtaining data
from the user, a prompt should be included so that the user knows what
information is expected.
Abstract data type A class. A data type that can Keyword A word that has special meaning to the
store data and methods. Java compiler and therefore cannot be used as a
variable or constant identifier.
ArithmeticException exception An exception
thrown when division by 0 occurs. Literal An actual value.
Assignment statement A statement that gives the Logic error An error caused by a statement that is
variable or constant on the left of an assignment syntactically correct, but produces unexpected or
operator the value of the expression on the right undesired results. Also called a semantic error.
side of the assignment operator.
Modulus division Division that returns the
Case sensitive An uppercase letter is different remainder.
from the same letter in lowercase.
Numeric expression At least one operand and
Class see Abstract data type. possibly one or more operators that evaluate to a
single value.
Concatenate To join two or more strings to form
one larger string. Object A variable declared with a class.
Constant A name for a memory location that stores Operator precedence The level assigned to an
a value than cannot be changed from its initial operator so that a specific order of operations is
assignment. maintained.
Data type The kind of information a variable Primitive data type A data type that can store only
stores. a single piece of data. Primitive data types are also
called built-in data types.
Declaration A statement that creates a variable or
constant. Prompt A string that informs the user of the kind
of data expected to be typed.
Equal sign (=) An assignment operator that indicates
the variable or constant on the left is to receive the Run-time error An error affecting program execu-
value of the expression on the right. tion. Also called an exception.
Floating point Values that are represented by the Syntax error An error caused by a statement that
double data type. Values that contain numbers after violates the rules of Java.
the decimal point.
Truncate Removing the decimal portion of a number
Identifier A name for a variable or constant. An when casting a double to an int.
identifier must begin with a letter and can include
Type casting Converting a number from one type
any number of letters, numbers, and some special
to a different type.
characters.
Variable A name for a memory location that stores
Initialize To assign a variable a value in a declara-
a value.
tion statement.
InputMismatchException exception An exception
thrown when user input is not as expected.
Input stream The sequence of characters received
from an input device.
Instantiation To create a new object.
Integer division Division that truncates the decimal
portion.
+ Operator used for concatenating strings. java.lang The most fundamental Java package. It
contains classes that define the Java language.
+ The arithmetic addition operator.
java.text A Java package with the NumberFormat
- The arithmetic subtraction operator.
class for formatting numbers.
* The arithmetic multiplication operator.
java.util A Java package with the Scanner class for
/ The arithmetic division operator. reading input.
% The arithmetic modulus division operator. new An operator that allocates memory for an
object.
() Used to change the order of operations in an
expression. Also used for type casting. NumberFormat A java.text class with methods for
formatting numbers.
= An assignment operator that gives the variable
on the left the value on the right. Scanner A java.util class with methods for reading
input from the user.
+= An assignment operator that adds the value on
the right to the variable on the left and then assigns System.in The input stream for reading from the
that value to the variable on the left. keyboard.
1. a) List four legal identifier names. 7. The java.util package contains a class named
b) List four illegal identifier names and explain ArrayList. Write a statement that makes the
why each is illegal. ArrayList class accessible to an application.
2. a) In two statements, declare a variable named 8. What is the value of each of the following
numBeads and assign it the value 5. expressions?
b) In one statement, declare a variable named a) 5 + 7 – 3
numBeads and assign it the value 5. b) 10 * 2 – 3
c) 10 * (2 – 3)
3. a) What is the final value of yourNumber after d) 8 – 3 * 2
the last statement executes? e) 10 / 5 * 4
int myNumber = 5; f) 10 / 2 + 3
int yourNumber = 4; g) 6 % 3 + 4
myNumber = yourNumber * 2;
h) 12 % 5 * 3
yourNumber = myNumber + 5;
i) 12 % (5 * 3)
b) What is the final value of yourNumber after
the last statement executes? 9. What is the result of the following expression
int myNumber; when x is 2005? When x is 1776? When x is 39?
int yourNumber = 4;
myNumber = yourNumber + 7; (x/10)%10
yourNumber = myNumber;
10. Write each equation as a valid Java expression:
4. Determine the appropriate data type for each
of the following values: a) (geometry)
a) the number of basketballs in a department
store.
b) the price of a basketball. b) (business)
c) the number of players on a basketball
team.
d) the average age of the players on a basketball c) (geometry)
team.
e) whether a basketball player has received a
jersey or not. d) (geometry)
f) the first initial of a basketball player’s first
name.
e) (algebra)
5. a) What is the difference between a primitive
data type and an abstract data type?
b) What is the difference between a class and f) (physics)
an object?
g) (business)
6. Assume a class named Team defines a sports
team.
11. Using the following declarations, rewrite the
a) Methods define the actions in a class and
statements to include the appropriate type cast-
typically include action words in their name.
ing, rounding where necessary. If type casting
For example, getTeamName is a method
is not necessary, explain why:
name that returns the name of the team. List
three more possible method names for the int j = 5;
Team class. double k = 1.6;
int y;
b) List three possible object names of type
double z;
Team.
a) y = j * k;
b) z = j * k;
True/False
16. Determine if each of the following are true or
false. If false, explain why.
a) An identifier can contain spaces.
b) Data of type double is sometimes referred to
as floating point.
c) An abstract data type is also called a primi-
tive data type.
Exercise 1 ————————————————————ObjectHeight
The height of an object at any given time dropped from a starting height of 100 meters is given by the
equation h=100–4.9*t2 where t is the time in seconds. Create an ObjectHeight application that prompts
the user for a time less than 4.5 seconds and then displays the height of the object at that time. The
application output should look similar to:
a) Create an Order application that prompts the employee for the number of burgers, fries,
and sodas and then displays the total, the tax (6.5%), and the final cost. The application
output should look similar to:
b) Modify Order to prompt the employee for the amount tendered and then display the
change due. Application output should look similar to:
a) The value of the amount after the term is calculated using the formula:
Amount = Principal * (1 + years * interest rate)
Create a SimpleInterest application that prompts the user for the principal, number of
years, and the interest rate (as a fraction) and then calculates the amount of interest.
The application should display output similar to:
b) The formula in part (a) can be adjusted to calculate what principal will need to be
invested in order to have a certain amount of money after a specified term and interest
rate:
Principal = Amount / (1 + years * interest rate).
Modify SimpleInterest to prompt the user for the desired amount, number of years,
and interest rate and then calculate the principal that will need to be invested.
Write a program that prompts the user for the election results, and then displays output similar to:
The if Statement
conditional control structure The if statement is a conditional control structure, also called a decision
structure, which executes a set of statements when a condition is true.
Conditional control structures are used to change program flow. The if
statement takes the form:
TIP The condition of an
i f statement should never if (<condition>) {
make an equality comparison <statements>
between floating point num- }
bers because of the possibility
For example, in the following if statement, guess == SECRET _ NUM is the
of roundoff error.
condition, and there is one statement that will be executed when this
condition is true:
if (guess == SECRET _ NUM) {
TIP Using = instead of == in System.out.println("You guessed it!");
an if statement condition gen- }
erates an error.
The == relational operator determines if the value of guess is equal to the
value of SECRET _ NUM. If equal, the println() statement executes. If not, then
program flow continues to the next statement after the closing brace of
the if statement.
Review: Stages
Create a Stages application that prompts the user for an age. For an age over 18, adult is displayed. For an age
less than or equal to 18, toddler is displayed when the age is less than or equal to 5, child when the age is less
than or equal to 10, preteen when the age is less than or equal to 12, and teen when the age is over 12.
There can be multiple else if clauses, and the last else clause is optional.
For example, there are three possible decisions in the if-else if statement
below:
Commenting Complex
Decision Structures if (guess == SECRET _ NUM) { //correct
System.out.println("You guessed it!");
Decision structures with many
} else if (guess < SECRET _ NUM) { //too low
branches can quickly become System.out.println("Too low.");
difficult to understand. Brief } else { //too high
inline comments can make System.out.println("Too high.");
code much more readable. }
This is especially important
for the last branch of a deci- The logic used in developing an if-else if statement is important. For
sion structure, which usually example, when testing a range of numbers, if conditions must be properly
does not include an explicit ordered because statements are executed for the first true condition only
condition. and then program flow continues to the next statement after the if-else
if.
Review: Discriminant
In mathematics, the quantity b2 – 4ac is called the “discriminant.” Create a Discriminant application that
prompts the user for the values of a, b, and c an then displays “No roots” if the discriminant is negative,
“One root” is the discriminant is zero, and “Two roots” if the discriminant is positive. Application output
should look similar to:
case The expression must evaluate to an integer. There can be multiple case
break clauses. The break statement is necessary to move program control to the
next statement after the switch statement. The default code is optional and
is executed when none of the previous cases are met. For example, when
score is 5, the case 5 statement executes and then program control moves
to the next statement after the switch (skipping the case 10 statement):
switch (score) {
case 0: System.out.println("Better luck next time."); break;
case 5: System.out.println("Pretty good."); break;
case 10: System.out.println("Great!"); break;
}
Review: Hurricane
The Saffir-Simpson Hurricane Scale provides a rating (a category) depending on the current intensity of a
hurricane. Create a Hurricane application that displays the wind speed for the hurricane category entered
by the user. Display the speed in miles per hour (mph), knots (kts), and kilometers per hour (km/hr). Refer
to the Saffir-Simpson Hurricane Scale below for wind speeds:
Category 1: 74-95 mph or 64-82 kt or 119-153 km/hr
Category 2: 96-110 mph or 83-95 kt or 154-177 km/hr
Category 3: 111-130 mph or 96-113 kt or 178-209 km/hr
Category 4: 131-155 mph or 114-135 kt or 210-249 km/hr
Category 5: greater than 155 mph or 135 kt or 249 km/hr
random numbers in a range To generate a random number in a range the following formula is
used:
(highNum - lowNum + 1) * Math.random() + lowNum
Review: RandomNum
Create a RandomNum application that prompts the user for two numbers. The first number is a minimum
value and the second is a maximum value. RandomNum then displays an integer between the min and max
values entered by the user.
When a guess is either less than 1 or greater than 50, “Invalid guess.” is
displayed. The condition in the if statement is called a compound Boolean
expression because more than one Boolean expression determines whether
the condition is true or false.
truth table How a compound Boolean expression evaluates with && and || operators
can be shown with truth tables. A truth table shows the possible outcomes
of compound Boolean expressions:
And Or
Exp1 Exp2 Result Exp1 Exp2 Result
True True True True True True
True False False True False True
False True False False True True
False False False False False False
short circuit evaluation Java uses short-circuit evaluation for determining the result of a com-
pound Boolean expression that includes && or ||. In short-circuit evaluation,
the left operand is evaluated first. If the result of the entire expression can
be determined by the value of the left operand, then no other operands will
be evaluated. For example, the expression x < 0 || x > 5 evaluates to true
if x is less than 0 regardless of the value of x > 5. Therefore, when x is less
then 0, the second operand will not be evaluated. As another example, the
expression x > 5 && x < 20 evaluates to false if x is less than or equal to
5 regardless of the value of x < 20. Therefore, when x is less than or equal
to 5, the second operand will not be evaluated.
order of operations In the order of operations, ! is evaluated before &&. || is evaluated last.
For example, the expression !5 < 6 || 2 > 4 && 3 < 6 evaluates to false
because !5 < 6 is performed first, then 2 > 4 && 3 < 6, and then False ||
False. Use parentheses to change operator precedence and to make code
more readable.
Review: Delivery
Create a Delivery application that prompts the user for the length, width, and height of a package, and then
displays “Reject” if any dimension is greater than 10, and “Accept” if all dimensions are less than or equal
to 10.
Calling a Math method requires using the class name. For example,
Math.abs(-3) returns 3. The application on the next page demonstrates the
Math methods:
import java.lang.Math;
Review: PerfectSquare
Create a PerfectSquare application that prompts the user for an integer and then displays a message indicat-
ing whether or not the number is a perfect square. This can be determined by finding the square root of a
number, truncating it (by casting the double result), and then squaring that result.
RPS Specification
RPS is played between the computer and a single player. The player is
prompted for a throw where 1 corresponds to Rock, 2 to Paper, and 3 to
Scissors. A random number between 1 and 3 is generated for the com-
puter throw. The winner is determined based on the rules of Rock Paper
Scissors.
The RPS interface should be simple. The user will be prompted to enter
an integer between 1 and 3, where 1 represents Rock, 2 represents Paper,
and 3 represents Scissors. The program then generates a random number
between 1 and 3, displays the generated number and the player’s number
and determines a winner.
The RPS output sketch:
RPS Implementation
Based on the code design, the RPS implementation follows:
/*
* RPS.java
*/
import java.util.Scanner;
import java.lang.Math;
/**
* Plays Rock Paper Scissors against one player.
*/
public class RPS {
Chapter Summary
This chapter introduced conditional control structures, random num-
bers, and logical operators. Conditional control structures, also called
decision structures, include the if and switch statements. The if uses the
result of a Boolean expression to determine program flow, and the switch
uses the result of an integer expression to determine program flow.
In the if statement, program flow branches to a set of statements when
the condition evaluates to true. In the if-else statement, program flow
branches to one set of statements for a true condition and a different set
when the condition is false. Nested if-else statements can be used for
even more control over program flow. The if-else if is used to decide
among three or more actions.
Relational operators can be used to form a Boolean expression. They
include the ==, <, <=, >, >=, and != operators. Two or more Boolean expres-
sions can be joined with logical operators to form a compound Boolean
expression. Logical operators include && (logical And), || (logical Or), and
! (logical Not). A truth table shows how a compound Boolean expression
evaluates.
The switch statement contains multiple case clauses. A break statement
is required to move program control out of the switch statement.
Boolean expression An expression that evaluates Logical Or The || operator used to form a compound
to true or false. Boolean expression.
Compound Boolean expression An expression that Nested A statement placed within the same type
includes more than one Boolean expression. of statement.
Conditional control structure A statement that Pseudorandom Not truly random, but like
branches program flow depending on a condition. random.
Also called a decision structure.
Relational operator Operators (==, <, <=, >, >=, !=)
Decision structure see Conditional control that can be used to form a Boolean expression.
structure.
Short circuit evaluation A process for determin-
Linear Congruential Method A method that uses ing the result of a Boolean expression where the left
a formula to generate a sequence of pseudorandom operand is evaluated first. If the result of the entire
numbers. expression can be determined by the left operand,
no other operands are evaluated.
Logical And The && operator used to form a com-
pound Boolean expression. Truth table A table that shows the possible outcomes
of two expressions joined by a logical operator.
Logical Not The ! operator used to reverse the
value of a Boolean expression.
Java
== The equality relational operator. if-else A decision structure that executes one set
of statements when a condition is true and another
< The less than relational operator. set of statements when the condition is false.
<= The less than or equal relational operator. if-else if A decision structure used to decide
> The greater than relational operator. among three or more actions.
>= The greater than or equal relational operator. Math A java.lang class with methods for generating
random numbers and performing math functions.
!= The not equal relational operator.
switch A decision structure that uses the result of
&& The logical And operator. an expression to determine which set of statements
to execute.
|| The logical Or operator.
1. Use a decision structure to write an appropriate 6. Given the following assignments, determine if
statement for each of the following: each of the following expressions evaluates to
a) Display Great job! when g r ade is 90 or true or false:
higher. size = 100 weight = 50 value = 75
b) Display Error when number is less than 20 or a) size > 50 && weight == 50
greater than 50. b) value < 100 && !(weight == 50)
c) Add 2 to the value of y when y is less than c) size >= 100 || value >= 100
100. d) weight < 50 || size > 50
e) !(value < 75)
2. Assume num1 and num2 contain integer values. f) !(size > 100 && weight >50 && value > 75)
Write an if-else if statement that displays one g) (value < 125 || weight < 76) && size ==100
of the following messages as appropriate:
First number is larger. 7. a) Write a statement that will calculate yx.
Second number is larger. b) Write a statement that will calculate the abso-
Numbers are equal. lute value of y.
c) Write a statement that will calculate the
3. a) Which is the appropriate word, odd or even square root of y.
for the blanks below?
if (num % 2 == 0) { True/False
System.out.println("___ number");
} else { 8. Determine if each of the following are true or
System.out.println("___ number"); false. If false, explain why.
} a) The condition of an if statement must be a
b) Rewrite the if-else as a switch statement. Boolean expression.
b) A nested if statement and an if-else if
4. Write statements that use Math.random() to statement are the same.
generate random numbers for each of the fol- c) The expression in a switch statement must
lowing situations: evaluate to a double.
a) Generate a random integer between 1 and d) Numbers generated by a computer program
50. are actually pseudorandom.
b) Generate a random integer between 20 and e) The (double) cast is needed to generate a
100. random integer.
c) Generate a random double between 10 and f) A compound Boolean expression can contain
20, inclusive. more than two Boolean expressions.
g) In a logical And expression, both operands
5. Identify the logic errors in the statements below, must be true for the expression to evaluate
which should display a single appropriate mes- to true.
sage for any value of age: h) In logical expressions, && is evaluated before
if (age < 18) { !.
System.out.println("child"); i) The pow() method in the Math class is used
} else if (age > 18 && age < 65) { for exponentiation.
System.out.println("adult"); j) The statement x = abs(-3); will return the
} else if (age > 65) {
value 3.
System.out.println("senior");
} l) A diamond shaped object represents a deci-
sion in a flowchart.
a) Display eight fractions and prompt the user to match pairs of equivalent fractions.
Application output should look similar to:
Use constant integers for a, c, and m. Choose a seed integer value for X0. Show 10 numbers from the
sequence. Application output should look similar to:
Note the sequence shown in the output repeats after five numbers. Experiment by changing the values
for a, c, m, and X0 (the seed) to see which values create the most “random” sequence of numbers (the
largest set of nonrepeating numbers).
c) Write down how the application was tested and list any debugging techniques used.
Create a Volumes application that prompts the user for the length, width, and height
of a rectangular prism and then calculates the volume.
b) The volume of a sphere is calculated using the formula:
Modify the Volumes application to prompt the user for the radius (d = 2*r) of a sphere
after displaying the volume of the rectangular prism. The application should then
display the volume of the sphere.
Modify the Volumes application to prompt the user for the length of each side of a cube
after displaying the volume of the rectangular prism and the sphere. The application
should then display the volume of the cube.
The application output should look similar to:
The Math library provides methods for calculating base 10 and base e (natural) logarithms. The exp()
method raises e to a given power:
Class Math ( java.lang.Math)
Methods
log(double num) returns the natural logarithm of num.
log10(double num) returns the base 10 logarithm of num.
exp(double num) returns e raised to the power of num.
For example, this formula could be used for estimating population growth in a region or for estimating
cell growth in a lab experiment. Create a BacteriaGrowth application that calculates how many bacte-
ria will be present based on this formula. The application should prompt the user initial bacteria, the
constant k, and the time. Refer to Exercise 12 for documentation for the Math methods for this exercise.
Chapter 5 Conditional Control Structures 127
Application output should look similar to:
The application should prompt the user to select one of the three choices and based on the selected
option prompts the user to enter the appropriate known information. For example, a radioactive mass of
200 grams will reduce to 100 grams in 10 years. Based on this information, the half-life is calculated to
be –0.06931. Refer to Exercise 12 for documentation for the Math methods for this exercise. Application
output should look similar to:
Infinite Loops
The condition of a loop is used to determine when the loop should stop
executing. A while continues until its condition is false. What happens,
though, if the condition never becomes false? The result is an infinite
loop—one which continues forever. For example, the following generates
an infinite loop. Can you see why?
int num = -1;
while (num < 0) {
num = -1;
}
The code causes the application to simply stop responding or just “hang.”
When this happens, close the output window to end the application. Note
that some compilers may require a different procedure to end an infinite
loop.
Syntax errors are a common cause of infinite loops. For example, a
semicolon after the condition causes the statement to check the condition,
do nothing, check the condition, do nothing, and on and on:
while (num < 0); { //an infinite loop here--added semicolon
num += 1;
}
In this case, only the first statement is executed and num is never assigned
the input. Although properly done, the indentation makes it difficult to
find the syntax error.
A logic error can also lead to an infinite loop condition. For example, in
the code below num is initialized to 1 and never decremented to a number
less than 0 in the loop, making the condition of the loop structure always
true:
int num = 1;
do {
num += 1;
} while (num >= 0);
In this case, the loop isn’t infinite because num is eventually assigned a
overflow number so large that an overflow results. An overflow occurs when there
are not enough bits to store a number. This may generate a run-time error
or, in the case of the code above, actually cause the condition to become
false. An overflow changes the sign of the number stored.
Each time the statement executes, one is added to the current value of the
variable. This type of variable is called a counter because it is incremented
by a constant value. Counters are useful for keeping track of the number
of times a user enters a value, makes a guess, or types a password. A
counter should be initialized when it is declared and then incremented
by a fixed amount.
A similar assignment statement is used to sum values as they are
entered by the user:
sumOfValues += newValue;
Each time the statement executes, the value of newValue is added to the
current value of the variable. This type of variable is called an accumulator
because its value “accumulates.” As with a counter, an accumulator should
be initialized when it is declared.
import java.util.Scanner;
/**
* Displays the average of a set of numbers
*/
public class AverageValue {
Review: Evens
Create an Evens application that displays the even numbers between 1 and 20, inclusive.
Review: NumbersSum
Create a NumbersSum application that prompts the user for a number and then displays the numbers 1
through the number entered, each on a separate line. Below the numbers, the sum is displayed.
Review: PercentPassing
Create a PercentPassing application that prompts the user for a set of scores and then calculates the percent-
age of scores above 70%. The user should have the option to enter as many scores as needed. (Hint: Use an
if statement and another counter.)
loop control variable The following statement uses a counter to control the iterations of a for
statement. The counter i is the loop control variable. When i is greater than
10, looping terminates:
TIP Counter variables in a for (int i = 1; i <= 10; i++) {
for loop are often named i, System.out.println(i);
j, or k. }
Note that the counter is declared in the initialization of the for statement
scope (int i = 1). With a declaration in this location, the scope of the counter
is from the initialization to the closing curly brace of the for statement.
The application will not recognize the variable outside of that statement.
programming style Declaring variables so that their scope is limited to where they are needed
is good programming style because it produces cleaner code and helps
eliminate the possibility of errors.
The statement above uses the ++ operator in the increment part of the
increment operator for statement (i++). The ++ operator is called the increment operator because
it increases the value of a variable by 1. The ++ operator is a good choice
in the increment of a for statement because the effect is to increase the
operand by 1. However, ++ should not be used within an expression, such
Expressions Using ++ as i++ <= 10, because the value returned by the operator is used in the
or –– expression, not the final value of the operand.
If the + + or - - operator Any combination of components can be left out of a for statement. This
appears before the operand, can be useful when a counter is declared and initialized outside the state-
it is called prefix (i.e. ++i). An
ment, as in the following code:
operator after the operand is
called postfix (i.e. i++). Either int num;
operator location has the System.out.print("Enter the starting number: ");
same effect on the final value num = input.nextInt();
of the operand. However, for (; num <= 10; num++) {
in an expression, the prefix System.out.println(num);
version uses the value of the }
operand after the operation.
For example, when x is 12, A for statement may also count down from a start value to an end value
the statement ++x returns 13. using the decrement operator, --:
In the postfix version, x + +,
for (int countDown = 10; countDown <= 0; countDown--) {
12 is returned. Therefore, a
System.out.println(countDown);
statement such as x++ >= 13 is }
false and could be ambiguous.
Using the ++ and -- operators While it is possible to modify a loop control variable from within a for
in an expre ssion is po or loop or to terminate a loop prematurely, this is considered poor program-
programming style.
ming style. Good programming style dictates that changes to the loop
control variable occur in the increment portion of the loop only and that
the loop end only when the condition is false.
Review: OddSum
Create an OddSum application that prompts the user for a number and then sums the odd numbers from 1
to the number entered.
Debugging Techniques
TIP A “bug” is an error in a The source of bugs, which are often logic errors, can be hard to deter-
program. mine without tools for debugging an application. Debugging is the process
of getting an application to work correctly. One tool included with many
compilers is called a debugger.
The variables are listed in the order that assignment occurs within the
loop. Output is also listed to better understand the code:
When run, the code above displays the following output, which can be
compared to the values expected. Note the similarity to a variable trace:
commenting out code Commenting out statements can be an effective way to locate a bug
through process of elimination. Typically the // characters are easiest to
type at the beginning of a statement to “comment it out.”
index The position of a character in a string is called its index. The first char-
acter of a string is at index 0. The last character of a string is at index
length() – 1. The MiddleThree class below displays the three letters in the
middle of a string:
public class MiddleThree {
public static void main(String[] args) {
String phrase, threeLetters;
int phraseLength;
int mid;
Scanner input = new Scanner(System.in);
Note that the String objects (phrase, threeLetters) can be declared in the
same way primitives are declared—the data type followed by the vari-
able name. With the String class, the following two statements perform
the same task:
String alpha = new String("abc"); //these assignments are
String alpha = "abc"; //efffectively the same
null Until a String object is assigned a value, it refers to null. Calling a method
NullPointerException from a null String object generates the exception NullPointerException.
Review: AccountSetup
Create an AccountSetup application that prompts the user for a user name and a password. The application
should prompt the user until a password with at least eight characters is entered. The user name and pass-
word should be converted to all lowercase letters and then an appropriate message displayed. Application
output should look similar to:
Methods
equals(String str)
returns true when the string is the same as str.
Returns false otherwise.
equalsIgnoreCase(String str)
Unicode same as equals() except that uppercase and
The Unicode Standard is a lowercase differences between the strings are
16-bit encoding system that ignored.
assigns a value for each char- compareTo(String str)
acter and symbol of every returns 0 when str is the same as the string, a
language. Java uses this stan- negative integer is returned when str comes
dard when defining strings, alphabetically after the string, and a positive
and String class methods use integer is returned when str comes alphabeti-
the character values when cally before the string. Note that uppercase and
comparing strings. lowercase letters are considered different.
compareToIgnoreCase(String str)
same as compareTo() except that uppercase and
lowercase differences between the strings are
ignored.
indexOf(String str)
returns the integer corresponding to the
location of the first occurrence of str in the
string. Otherwise –1 is returned.
lastIndexOf(String str)
returns the integer corresponding to the
location of the last occurrence of str in the
string. Otherwise –1 is returned.
startsWith(String str)
returns true when the string begins with str.
Returns false otherwise.
endsWith(String str)
returns true when the string ends with str.
Returns false otherwise.
The AlphaOrder class compares two strings and then displays them in
alphabetical order:
public class AlphaOrder {
if (word1.compareToIgnoreCase(word2) == 0) {
System.out.println("Words are equal.");
} else if (word1.compareToIgnoreCase(word2) < 0) {
System.out.println("In alphabetical order: " + word1
+ " " + word2);
} else {
System.out.println("In alphabetical order: " + word2
+ " " + word1);
}
}
}
Review: FormalGreeting
Create a FormalGreeting application that prompts the user for his or her name, including title. The applica-
tion should display “Hello, sir.” if the string starts with Mr., “Hello, ma’am.” if the string starts with Ms., Mrs.,
or Miss, and “Hello, name.” otherwise where name is the user’s name.
WordGuess Specification
WordGuess is played between the computer and a single player. The
secret word is BRAIN. At the start of the game, six dashes are displayed
(––––––), one for each letter of the word. The player is repeatedly prompted
for a letter guess. When a letter matching one in the word is guessed, the
letter replaces the corresponding dash. Letters may be entered as upper-
case or lowercase. However, only uppercase letters should be displayed. If
the player enters an exclamation point (!), the player is prompted to guess
the word. At that point the player either wins (a correct guess) or loses
(an incorrect guess). Alternatively, the player can continue to guess letters
until the entire word is revealed. The games ends by showing the player
the total number of guesses.
WordGuess Implementation
Based on the code design, the WordGuess implementation follows:
/*
* WordGuess.java
*/
import java.util.Scanner;
/* begin game */
System.out.println("WordGuess game.\n");
for (int i = 0; i < SECRET _ WORD.length(); i++) {
wordSoFar += "-"; //word as dashes
}
System.out.println(wordSoFar + "\n"); //display dashes
Review: WordGuess
Modify the WordGuess Chapter 6 Case Study to display a score at the end of each game. The player should
start with 100 points and have 10 points taken off for each guess. The score should be updated and displayed
as the game is played. Display a player loses message if the score gets down to 0.
Chapter Summary
This chapter introduced loop structures and the String class. The while
statement and do-while statement are loop structures that iterate a set of
statements repeatedly based on a condition. The difference between the
loops is when the condition is evaluated. The while statement evaluates
the condition before any iterations are performed. The do-while does not
evaluate the condition until after the first iteration.
Debugging The process of getting an application Overflow A condition that occurs when a number
to work correctly. is too large to be stored in a specified number of
bits.
Decrement operator The - - operator, which
decreases the value of a variable by 1. Sentinel A constant that stores a value that is used
to signify that a loop should stop iterating. Also
Flag see Sentinel.
called a flag.
Immutable Unable to change.
Scope The set of statements that can access a declared
Increment operator The ++ operator, which increases variable.
the value of a variable by 1.
Variable trace A table listing the values of vari-
Index The position of a character in a string. ables at the points of assignment. Used for manually
debugging an application.
Infinite loop A loop that continues forever.
Java
b) Modify the application to determine what integers of two, three, and four digits are
equal to the sum of the cubes of their digits.
1. Guess the number halfway between the lowest and highest numbers.
2. If the number guessed matches the secret number, then the player wins.
3. If the number guessed is too high, then take the number guessed minus one and
make this the highest number and go back to Step 1.
4. If the number guessed is too low, then take the number guessed plus one and make
this the lowest number and go back to Step 1.
For example, assuming 15 is the random number generated in the Guessing Game
application, the game would play out as follows when the player uses a divide-and-
conquer technique:
In another program run, assuming the random number generated is 20, the game
would play out as follows using the same divide-and-conquer technique:
When this approach is taken, it has been proven that a player will not be required
to make more than Log2n guesses, in this case Log250, or at most 6 guesses. Try this
technique yourself. Explain in your own words why this works. Would this strategy
be possible if hints were not given after each guess?
Create a Necklace application that prompts the user for two single-digit integers and then displays the
sequence and the number of steps taken. The application output should look similar to:
Start with any real number x between 0 and 1. Generate a new number using the
“logistic equation:”
x = 2*x(1 - x)
Create a RandomWalk application that determines how many steps the person will walk before taking
a step off the bridge. Have the application average 50 trials, and display the average and the greatest
number of steps. (Hint: Generate a random number between 0 and 1, with 0 meaning to go forward
and 1 meaning to go backward.)
fahrenheitToCelsius()
Prompt the user for a temperature in degrees Fahrenheit
Convert the temperature to degrees Celsius
Display the temperature
celsiusToFahrenheit()
Prompt the user for a temperature in degrees Celsius
Convert the temperature to degrees Fahrenheit
Display the temperature
import java.util.Scanner;
In this run of the application, the user entered 1 and therefore the
fahrenheitToCelsius() method was called.
Writing Methods
method declaration A method consists of a declaration and a body. The method declaration
includes access level, return type, name, and parameters, if any. The method
method body body contains the statements that implement the method. A method takes
the form:
<access _ level> <return _ type> <name>(<parameters>) {
<statements>
}
The method above is a class method with access level public, return
access level type void, name fahrenheitToCelsius, and no parameters. The access level
of a method determines if other classes can call the method. The keyword
access modifier public is an access modifier. A public method can be called by any other
visibility method. The access level of a method can also be thought of as its visibility.
Access levels are discussed further in Chapter 8.
class method The keyword static declares the method a class method. A class method
can be called from the class itself. Methods that are not class methods must
be called from an instantiated object of that class.
void The return type void means that the method will not return a value,
and parameters are specified when a method needs values to perform its
task. The body of the method starts with the first opening brace ({) and
ends with the closing brace (}).
local scope Methods can also have their own set of variables, constants, and objects.
Variable, constant, and object declarations in the body of a method have
a scope that extends from the declaration to the end of the method
body. These variables, constants, and objects are said to be local to the
method because their scope is limited to that method. For example, the
fahrenheitToCelsius() method contains local variables fTemp and cTemp and
a local object named input.
Review: TimeConverter
Create a TimeConverter application that allows the user to choose among converting hours to minutes, days
to hours, minutes to hours, or hours to days. Use methods as appropriate.
Method Parameters
A method declaration can include method parameters, which accept values
from the method call. The data passed to the method can then be used
TIP The terms “parameter” inside the method to perform its task. For example, the drawBar() method
and “argument” are often used
includes an int parameter named length:
synonymously.
public static void drawBar(int length) {
passing data Data is given, or passed, to a method by enclosing the data in parentheses
in the method call. The value or variable passed to a method is called the
argument argument. For example, the RightTriangle application makes six calls to
drawBar(). Each call passes a different variable argument:
public class RightTriangle {
TIP The term “formal parame- public static void drawBar(int length) {
ter” is sometimes used to refer
to a parameter in the method for (int i = 1; i <= length; i++) {
declaration, and the term System.out.print("*");
“actual parameter” is used to }
refer to the argument being System.out.println();
passed to the method. }
pass by value In Java, arguments are passed by value, which means that the data stored
in an argument is passed. An argument that is a primitive data type gives
the method a copy of its value. An argument that is an object gives the
method a copy of its reference that points to methods for changing object
data. Therefore, a method can change the data stored in an object because
it has access to the object’s methods, but it cannot change the data stored
in a primitive variable because the method does not have access to the
actual location of the primitive data.
multiple parameters When a method declaration includes more than one parameter, the
parameters are separated by commas. For example, a modified drawBar()
has an int parameter for the length of the bar and a String parameter for
the character to use to draw the bar:
TIP Passing an argument of a public static void drawBar(int length, String mark) {
type that is not expected by a
method generates the exception for (int i = 1; i <= length; i++) {
IllegalArgumentException. System.out.print(mark);
}
System.out.println();
}
Review: SpanishNumbers
Create a SpanishNumbers application that displays numbers 1 through 10 in Spanish. A method with an int
parameter should display the Spanish word for the number passed. A loop structure in the main() method
should be used to call the method ten times. The Spanish word equivalents for numbers 1 through 10 are:
1 uno 6 seis
2 dos 7 siete
3 tres 8 ocho
4 cuatro 9 nueve
5 cinco 10 diez
Method Overloading
The method declaration is used by the compiler to determine which
method to execute. Therefore, method names do not have to be unique
as long as the parameters are different for methods with the same name.
Method overloading is when more than one method of the same name is
included in a class. For example, the following application contains two
drawBar() methods:
public class MethodOverloadingExample {
drawBar(10);
drawBar(5, "@");
}
}
Note that the first call in main() executes the drawBar() method containing
only one parameter. The second call executes the drawBar() method that
contains two parameters. The compiler uses the types, order, and number
of parameters to determine which method to execute.
The return statement is used to send a value back to the calling statement.
A return statement can return only one value.
A method that returns a value must include the return type in the
method declaration. For example, the cubeOf() method declaration
declares a return type double. Return types can be primitive types, such
as int, double, and boolean, or abstract types, such as the String class. The
return type void is used when there will be no return value. A method
declared as void does not contain a return statement.
A method that returns a value is called from a statement that will
make use of the returned value, such as an expression or an assignment
statement. For example, the following application calls cubeOf() from an
assignment statement:
public class CubeCalculator {
xCubed = x * x * x;
return(xCubed);
cube = cubeOf(num);
System.out.println(cube);
}
}
Documenting Methods
Methods should be carefully commented so that a reader of the program
understands what task the method is performing and what data, if any,
will be returned by the method. Method documentation is in the form of
documentation comments (/** */) that appear just above the method
declaration. For example, the drawBar() method with documentation:
/**
* Print a bar of asterisks across the screen.
* pre: length > 0
* post: Bar drawn of length characters, insertion
* point moved to next line.
*/
public static void drawBar(int length) {
xCubed = x * x * x;
return(xCubed);
}
Review
Modify each of the Reviews in this chapter so that the methods are properly documented.
GradeConverter Specification
The GradeConverter application prompts the user for a numeric grade in
the range 0 to 100 or a –1 to end the application. When a valid numeric
grade is entered, the corresponding letter grade is then displayed. Grades
from 90 to 100 are an A, grades from 80 to 89 are a B, grades from 70 to 79
are a C, grades from 60 to 69 are a D, and grades below 60 are an F. After
displaying the corresponding letter grade, the user is prompted to enter
another letter grade or can choose to quit the application.
The GradeConverter interface should include a prompt asking for the
numeric grade. The prompt should give the option of quitting the appli-
cation. After displaying the letter grade, the user should be prompted to
enter another numeric grade or quit the application.
The GradeConverter output sketch:
getLetterGrade(numericGrade)
if (numericGrade < 60) {
return ("F");
} else if (numericGrade < 70) {
return ("D");
} else if (numericGrade < 80) {
return ("C");
} else if (numericGrade < 90) {
return ("B");
} else {
return ("A");
}
GradeConverter Implementation
Testing methods in isolation is important to ensure that the program
as a whole will run without error. When testing a method, statements in
main() should call the method using test data. The main() method should
not call any other method or perform any other task except test the current
method.
Rather than writing code for the entire application at once, one method
at a time will be added and then tested. When testing the methods is com-
plete, the main() method will be rewritten to implement the GradeConverter
pseudocode.
/**
* Determines if a numeric entry is valid.
* pre: none
* post: true return if minNum <= userNum <= maxNum;
* false returned otherwise
*/
public static boolean isValidNumber(int userNum, int minNum, int maxNum) {
if (minNum <= userNum && userNum <= maxNum) {
return(true);
} else {
return(false);
}
}
numericGrade = 0;
if (isValidNumber(numericGrade, minValue, maxValue)) {
System.out.println(numericGrade + " is valid.");
} else {
System.out.println(numericGrade + " is NOT valid.");
}
numericGrade = 100;
if (isValidNumber(numericGrade, minValue, maxValue)) {
System.out.println(numericGrade + " is valid.");
} else {
System.out.println(numericGrade + " is NOT valid.");
}
numericGrade = -1;
if (isValidNumber(numericGrade, minValue, maxValue)) {
System.out.println(numericGrade + " is valid.");
} else {
System.out.println(numericGrade + " is NOT valid.");
}
numericGrade = 101;
if (isValidNumber(numericGrade, minValue, maxValue)) {
System.out.println(numericGrade + " is valid.");
} else {
System.out.println(numericGrade + " is NOT valid.");
}
}
}
/**
* Determines if a numeric entry is valid.
* pre: none
* post: true has been returned if minNum <= userNum <= maxNum;
* false has been returned otherwise
*/
public static boolean isValidNumber(int userNum, int minNum, int maxNum) {
if (minNum <= userNum && userNum <= maxNum) {
return(true);
} else {
return(false);
}
}
/**
* Determines the letter grade that corresponds to the numeric grade.
* pre: 0 <= numGrade <= 100
* post: The letter grade A, B, C, D, or F has been returned.
*/
public static String getLetterGrade(int numGrade) {
if (numGrade < 60) {
return("F");
} else if (numGrade < 70){
return("D");
} else if (numGrade < 80) {
return("C");
} else if (numGrade < 90) {
return("B");
} else {
return("A");
}
}
numericGrade = 90;
System.out.println(numericGrade + " is " + getLetterGrade(numericGrade));
numericGrade = 89;
System.out.println(numericGrade + " is " + getLetterGrade(numericGrade));
numericGrade = 80;
System.out.println(numericGrade + " is " + getLetterGrade(numericGrade));
numericGrade = 79;
System.out.println(numericGrade + " is " + getLetterGrade(numericGrade));
numericGrade = 70;
System.out.println(numericGrade + " is " + getLetterGrade(numericGrade));
numericGrade = 69;
System.out.println(numericGrade + " is " + getLetterGrade(numericGrade));
numericGrade = 60;
System.out.println(numericGrade + " is " + getLetterGrade(numericGrade));
numericGrade = 59;
System.out.println(numericGrade + " is " + getLetterGrade(numericGrade));
}
After verifying that the methods are working as expected, the final
GradeConverter application can be completed:
/*
* GradeConverter.java
*/
import java.util.Scanner;
/**
* Display the letter grade that corresponds to the numeric
* grade entered by the user.
*/
public class GradeConverter {
/**
* Determines if a numeric entry is valid.
* pre: none
* post: true has been returned if minNum <= userNum <= maxNum;
* false has been returned otherwise
*/
public static boolean isValidNumber(int userNum, int minNum, int maxNum) {
if (minNum <= userNum && userNum <= maxNum) {
return(true);
} else {
return(false);
}
}
/**
* Determines the letter grade that corresponds to the numeric grade.
* pre: 0 <= numGrade <= 100
* post: The letter grade A, B, C, D, or F has been returned.
*/
public static String getLetterGrade(int numGrade) {
if (numGrade < 60) {
return("F");
} else if (numGrade < 70){
return("D");
} else if (numGrade < 80) {
return("C");
} else if (numGrade < 90) {
return("B");
} else {
return("A");
}
}
}
The GradeConverter application produces output similar to:
Review: GradeConverter
Modify the GradeConverter Case Study to display an A+ for a grade of 100, a B+ for a grade of 89, a C+ for
a grade of 79, and a D+ for a grade of 69.
Chapter Summary
This chapter introduced a new level of software development that
included writing methods to perform tasks. In the software development
process, top-down development is a problem-solving approach that breaks a
task down into smaller subtasks and then further into units. Implementing
these tasks with methods is called procedural abstraction.
Access level The part of a method declaration that Method overloading Writing more than one method
determines if the method can be called by other of the same name in a class.
classes.
Method parameters The part of a method declara-
Access modifier A keyword in the declaration tion that accepts values from the method call.
of a method that determines the access level of a
Pass Giving data to a method by enclosing the data
method.
in parentheses in the method call.
Argument The value or variable passed to a
Pass by value Passing the value of an argument to a
method.
method. The type of data passed depends on whether
Call A statement that contains a method name the argument is a primitive or an object.
followed by parentheses.
Precondition The part of a method’s documentation
Boundary value A value that lies just inside or just that states the assumptions, or initial requirements,
outside the range of valid values. of the method. Also called pre.
Class method A method that can be called from Procedural abstraction Breaking a task down into
the class itself. methods.
Local Variables, constants, and objects that are Postcondition The part of a method’s documenta-
declared within a method and therefore have a scope tion that states what must be true after the method
limited to that method. has been executed. Also called post.
Java
1. Use top-down development and procedural 8. a) What is the return statement used for?
abstraction to write pseudocode for the follow- b) How many values can a return statement
ing specification: send back to the calling statement?
The Pizza application allows the user to c) How is the declaration of a method return-
choose to display the instructions for mak- ing a value different from the declaration of
ing a pizza in either English or Spanish. a method that does not return a value?
2. Explain the difference between method declara- 9. Find and explain the error in the code below:
tion and method body. public class MethodCallExample {
3. What type of keyword is used to change the public static int doSomething() {
return(5);
access level of a method? }
}
4. What is another word used for describing the
access level of a method? public static void main(String[] args) {
int num;
5. Explain the scope of each of the variables in the doSomething();
num = doSomething();
code below: }
public class ScopeExample {
public static void method1() { 10. a) What type of comments should be used for
int var3; describing a method?
for (int var4 = 0; var4 < 2; var4++) { b) What three things should the comments for
var3 += 1; a method describe?
}
}
True/False
}
11. Determine if each of the following are true or
public static void main(String[] args) {
int var1;
false. If false, explain why.
for (int var2 = 0; var2 < 5; var2++) { a) Breaking a task down into methods is called
method1(); procedural abstraction.
} b) A method call consists of the method decla-
} ration in an assignment statement.
c) A void method must return a value.
6. Write a method declaration for each of the fol- d) An access modifier declares the return type
lowing descriptions: of a method.
a) A class method named getVowels that can be e) The keyword static declares a method is a
called by any other method, requires a String class method.
parameter, and returns an integer value. f) Method parameters are enclosed by braces
b) A class method named extractDigit that can ({}).
be called by any other method, requires an g) Local variables can be used by any method
integer parameter, and returns an integer in a class.
value. h) The value of an argument passed to a method
c) A class method named insertString that can can be changed in an assignment statement
be called by any other method, requires a in the method.
String parameter and an integer parameter, i) Method overloading means that an applica-
and returns a String parameter. tion contains more than 10 methods.
j) The return statement is used to send a value
7. a) How does the compiler distinguish one back to the calling statement.
method from another? k) The precondition of a method states the data
b) Can two methods in the same class have the types of the method’s parameters.
same name? Explain. l) The postcondition of a method describes the
way the method accomplishes its task.
b) Modify the application to allow the player to continue until there are 0 points left. At
the end of the game, display the number of guesses the user took before running out
of points.
a) Modify the algorithm to include a call to a method named giveHint(), which displays
a hint, but does not return a value.
b) Modify the flowchart based on the algorithm modifications.
c) Modify the GuessingGame code. Application output should look similar to:
What is an Object?
In object-oriented programming, an object stores data and can perform
state actions and provide communication. The state of an object refers to the
behavior data it stores. The behavior of an object is defined by the action and com-
munication it provides.
Objects often model, or simulate, real-world things. For example, con-
sider a circle shape. To create a Circle object modeled after the circle shape,
we analyze the state and behavior of the shape. A circle is defined by its
radius, so this will make up the state of the object. A circle shape doesn’t
do much in the way of actions, but a Circle object could change its radius,
calculate its area, and tell us what its radius is. These actions will make
up the behavior of a Circle object.
An object is an instance of a class. A class is a data type that defines vari-
TIP A class is an abstract data ables for the state of an object and methods for an object’s behavior. Good
type, which was discussed in
programming style dictates that the state of an object can only be changed
Chapter 4.
through its behavior. For example, to change the radius of a Circle object,
a method for changing the radius variable must be called. Protecting an
encapsulation object’s data is called encapsulation. Encapsulation is also called information
information hiding hiding because the object hides certain data from code outside the class.
For example, a Circle object declared in client code can be visualized as:
spot.setRadius(5);
/**
* Changes the radius of the circle.
* pre: none
* post: Radius has been changed.
*/
public void setRadius(double newRadius) {
radius = newRadius;
}
Interface
The public methods of a class
define the interface of an /**
object. The interface is how * Calculates the area of the circle.
client code can interact with * pre: none
an object. * post: The area of the circle has been returned.
*/
public double area() {
double circleArea;
circleArea = PI * radius * radius;
return(circleArea);
}
/**
* Returns the radius of the circle.
* pre: none
* post: The radius of the circle has been returned.
*/
public double getRadius() {
return(radius);
}
}
The Circle class has access level public which means that it is visible
to other classes and can be used to instantiate objects in those classes.
naming conventions The class name is Circle. A class name should be a noun, begin with an
uppercase letter, and each word within the name should also begin with
an uppercase letter. Class names may not contain spaces.
The body of a class starts with an opening brace ({) and ends with a
closing brace (}). Member variables are declared after the opening brace,
and outside of any methods. Variable declarations in the body of a class
have a local scope that extends from the opening brace of the class body
to the closing. Note that the Circle class also has a member variable that
is a constant.
The constructor of a class does not have a return type and always has the
same name as the class. When a constructor contains parameters, they
are separated by commas.
overloading constructors Constructors can be overloaded to provide more options for instantiat-
ing an object. For example, if the radius of the circle object is known when
the Circle object is created, it would be more efficient to assign the value
to radius when the object is created:
Circle spot = new Circle(5);
/**
* constructor
* pre: none
* post: A Circle object created. Radius initialized to 1.
*/
public Circle() {
radius = 1; //default radius
}
/**
* constructor
* pre: none
* post: A Circle object created with radius r.
*/
public Circle(double r) {
radius = r;
}
TIP Class methods cannot be The class method is called from the class itself (Circle) rather than an object
used to change the value of an of the class. The TestCircle application displays the following output:
instance variable.
TIP If a subclass does not over- A subclass typically contains its own version of the equals() and toString()
ride the equals() and toString() superclass methods to better suit the object of the subclass. For example,
methods, then the Object class two Circle objects are equal when they both have the same radius, and two
methods are used. String objects are equal when they consist of the same set of characters.
When a subclass redefines a superclass method, the subclass method
override is said to override the superclass method. The Circle class should con-
tain an equals() method that compares the state of the object to another
Circle object and a toString() method that returns a String describing the
object:
/**
* Determines if the object is equal to another
* Circle object.
* pre: c is a Circle object.
equals() vs. == * post: true has been returned if the objects have
* the same radii. false has been returned otherwise.
Objects compared using the */
== operator are equal only if public boolean equals(Object c) {
they refer to the same object. Circle testObj = (Circle)c;
The == operator compares the
references of the objects, not if (testObj.getRadius() == radius) {
the data stored by the objects return(true);
as the equals() methods does. } else {
return(false);
}
}
/**
* Returns a String that represents the Circle object.
* pre: none
* post: A string representing the Circle object has
* been returned.
*/
public String toString() {
String circleString;
if (spot1.equals(spot2)) {
System.out.println("Objects are equal.");
} else {
System.out.println("Objects are not equal.");
}
TIP The concatenation opera- System.out.println(spot1);
tor + also invokes the toString() System.out.println(spot2);
method of an object. }
The Bank client code uses the class designs and looks similar to:
import java.util.Scanner;
import java.text.NumberFormat;
System.out.println(munozAccount);
/**
* constructor
* pre: none
* post: An account created. Balance and
this * customer data initialized with parameters.
*/
The keyword t h i s can be
public Account(double bal, String fName, String lName,
used to distinguish between
String str, String city, String st, String zip) {
a parameter and a member balance = bal;
variable. For example, it can cust = new Customer(fName, lName, str, city, st, zip);
be convenient to use the }
same name for both a method
parameter and a member
variable in a class, in which /**
case, the member variable is * Returns the current balance.
preceded by this. If in the * pre: none
Account class, the constructor * post: The account balance has been returned.
used dou ble bala nce as a */
parameter, then the statement public double getBalance() {
in the body must be written as: return(balance);
this.balance = balance; }
/**
* A deposit is made to the account.
* pre: none
* post: The balance has been increased by the amount of the deposit.
*/
public void deposit(double amt) {
balance += amt;
}
/**
* A withdrawal is made from the account if there is enough money.
* pre: none
* post: The balance has been decreased by the amount withdrawn.
*/
public void withdrawal(double amt) {
if (amt <= balance) {
balance -= amt;
} else {
System.out.println("Not enough money in account.");
}
}
accountString = cust.toString();
accountString += "Current balance is " + money.format(balance);
return(accountString);
}
}
/**
* constructor
* pre: none
* post: A Customer object has been created.
* Customer data has been initialized with parameters.
*/
public Customer(String fName, String lName, String str,
String c, String s, String z) {
firstName = fName;
lastName = lName;
street = str;
city = c;
state = s;
zip = z;
}
/**
* Returns a String that represents the Customer object.
* pre: none
* post: A string representing the Account object has
* been returned.
*/
public String toString() {
String custString;
Review: Bank
Modify the Customer class to include changeStreet(), changeCity(), changeState(), and changeZip() methods.
Modify the Account class to include a changeAddress() method that has street, city, state, and zip parameters.
Modify the Bank application to test the changeAddress() method.
Object-Oriented Development
Object-oriented programming requires that the solution to a task be
implemented as a system of objects. In this system, objects communicate
with other objects to provide a solution to the task. This approach to creat-
ing software is called object-oriented development.
In object-oriented development, the programmer reads the specification
TIP The JDK was discussed in and selects objects to model the specification. Some of these objects will
Chapter 4. require new classes designed and written by the programmer. Other
objects can be created from existing classes previously written by the
programmer or by other programmers. For example, the JDK contains
reusability numerous classes for use in a Java application. Reusability is an important
feature of object-oriented programming because it reduces development
time and decreases the likelihood of bugs.
To demonstrate object-oriented development, consider the following
Carnival program specification:
A carnival has many games that are similar in nature. These games
allow the player three tries, and the player who is successful all
three times is a winner. For example, the Balloon Dart Toss game
allows the player to throw three darts at a wall of balloons. If each
dart pops a balloon, then the player is a winner. The Ring Toss and
Break A Plate games work similarly.
selecting objects for the In the first step of object-oriented development, objects are selected to
model model the specification. In this case, the carnival can be modeled with
game booth objects and player objects. A game booth object should store
data about the cost of playing the game, the winning prize, and the con-
solation prize. Game booth methods should start the game and give the
cost to play. A player object should store data about the spending money
of the player and the prizes won. Player methods should play the game
and show the list of prizes won.
designing objects The designs for the Carnival classes are:
Note how simple the application appears. All the work is being done by
the objects, rather than with individual statements in the main() method.
modular The Carnival application, like other object-oriented applications, is modular.
It uses components that are separately written and maintained.
Another aspect of object-oriented development is that objects send
information to other objects to perform a task. When information is passed
message from one object to another, the object is said to be passing a message. For
example, in the pseudocode above, the Player objects are passed a message
that includes the cost of a game and the prize the player won.
implementing the classes The GameBooth class is implemented below. Note that in the start()
method, the player’s throws are simulated with random numbers. The
player is said to win if three ones are generated:
import java.lang.Math;
/**
* constructor
* pre: none
* post: A GameBooth object created.
* The cost and prizes are set.
*/
public GameBooth(double charge, String p1, String p2) {
cost = charge;
firstPrize = p1;
consolationPrize = p2;
}
/* play game */
for (int i = 0; i < 3; i++) { //player gets three tries
toss = (int)(Math.random() + 0.5); //0 or 1
if (toss == 1) {
successes += 1; //1 is a successful toss
}
}
/* award prize */
if (successes == 3) {
return(firstPrize);
} else {
return(consolationPrize);
}
}
/**
* Returns the cost to play the game.
* pre: none
* post: Cost of the game has been returned.
*/
public double getCost() {
return(cost);
}
}
/**
* constructor
* pre: none
* post: A Player object created. Spending money given to
* player. The prizes won set to none.
*/
public Player(double money) {
spendingMoney = money;
prizesWon = "";
}
/**
/**
* Returns the list of prizes won.
* pre: none
* post: The list of prizes has been returned.
*/
public String showPrizes() {
return(prizesWon);
}
}
Notice that the start() method uses both casting and rounding in the
statement toss = (int)(Math.random() + 0.5); to produce an integer that is
either a 0 or a 1.
Although the classes may look long, once written they are available for
many different implementations of a Carnival or another application that
involves games.
Review: Carnival
Modify the Player class to override the toString() method. When a Player object is passed to the println()
method, a message should display how much money the player has left and the prizes won so far.
Modify the GameBooth class to keep track of the number of prizes awarded. There should be separate
totals for the first prizes awarded and the consolation prizes awarded. Add a method to the GameBooth
class named prizesAwarded() that displays the number of first prizes and the number of consolation prizes
given away.
Modify the Carnival client code to pass the Player objects to println() in the last two statements, and in
separate statements, display how many prizes were given away by each booth.
RPS2 Specification
The computerized version of the Rock Paper Scissors game is played
by one user that “throws” either rock, paper, or scissors. The game then
randomly selects either rock, paper, or scissors for the computer’s “throw”
and the winner is determined by comparing the two choices. Rock wins
over scissors, scissors wins over paper, and rock wins over scissors. The
player can initially choose to play multiple rounds. At the end of the
rounds, an overall winner is declared.
The RPS2 interface should show the result of each round and the overall
winner. The RPS2 output sketch:
Based on the algorithm and the class designs, the RPS2 code design will
include two objects and a loop. The pseudocode for the RPS2 client code
follows:
declare game object
declare player object
/**
* constructor
* pre: none
* post: RPSPlayer object created. The player is given a
* default throw.
*/
public RPSPlayer() {
playerThrow = 1; //default throw
}
/**
* Sets the player's throw.
* pre: newThrow is the integer 1, 2, or 3.
* post: Player's throw has been made.
*/
public void makeThrow(int newThrow){
playerThrow = newThrow;
}
/**
* Returns the player's throw.
* pre: none
* post: Player's throw has been returned.
*/
public int getThrow() {
return(playerThrow);
}
import java.lang.Math;
/**
* constructor
* pre: none
* post: RPSGame object created. Computer throw generated.
*/
public RPSGame() {
compThrow = (int)(3 * Math.random() + 1); //1, 2, or 3
playerWins = 0;
computerWins = 0;
}
/**
* Computer's throw is generated (ROCK, PAPER, or SCISSORS)
* pre: none
* post: Computer's throw has been made.
*/
public void makeCompThrow(){
compThrow = (int)(3 * Math.random() + 1); //1, 2, or 3
}
/**
* Returns the computer's throw.
* pre: none
* post: Computer's throw has been returned.
*/
public int getCompThrow() {
return(compThrow);
}
import java.util.Scanner;
/**
* Computer plays Rock Paper Scissors against one player.
*/
public class RPS2 {
/* play RPS */
System.out.print("How many rounds? ");
rounds = input.nextInt();
for (int i = 0; i < rounds; i++) {
System.out.print("Enter your throw (ROCK=1,
PAPER=2, SCISSORS=3): ");
playerThrow = input.nextInt();
rpsOpponent.makeThrow(playerThrow);
rps.makeCompThrow();
rps.announceWinner(rpsOpponent.getThrow());
}
rps.bigWinner();
}
}
Note how concise the client code is. The RPS2 application uses objects
to perform all the work.
Although the classes may look long, once written they are available
for many different implementations of the RPS game. Client code can be
written to use the classes in many different ways. For example, multiple
players and games can be instantiated for tournaments.
Java
class The keyword used to declare a class. private An access modifier used to declare class
members visible to the class but not to client code.
public An access modifier used to declare a class
that is visible to client code. Also used in the decla- static The keyword used in the declaration of a
ration of class methods to indicate that the method variable or method in a class to indicate that the
is visible to client code. member is a class method.
1. W h ich members of t he Circle class are 7. Imagine a band festival where there are many
encapsulated? bands playing—the TwoToos, the EggRolls, and
Goop. Each band can TuneUp, PlayMusic, and
2. What name must the constructor of a class TakeABow. A set list can be read or created. If
have? this was simulated in an object-oriented pro-
gram, what would appropriate names be for:
3. Explain the difference between the private and a) the class
public access modifiers. b) the objects
c) a data member
4. Consider the following code. Is the last state- d) the method members
ment valid or invalid? Explain.
Circle dot = new Circle(2); 8. Assume a class for a sports team named
dot.radius = 5; Team.
a) List three possible object names.
5. Use the following class to answer the questions b) List three possible method members.
below: c) List three possible data members.
public class Roo {
9. Use the following class data member definitions
private int x; to answer the questions below:
public Roo { public class Moo {
x = 1; private double y;
} private static int x;
private static final z;
public void setX(int z) {
x = z; …
}
a) Which data member is a constant?
public int getX() { b) Which data members are variables?
return(x); c) W h ic h dat a member (s) a re i n st a nce
} members?
d) Which data member(s) are class members?
public int calculate() {
x = x * factor();
return(x); 10. Explain the difference between calling an
} instance method member and a class method
member.
private int factor() {
return(0.12); 11. Compare and contrast overriding methods to
}
overloading methods.
}
a) What is the name of the class? 12. The Customer class in the Bank application also
b) What is the name of the data member? demonstrates a has-a relationship. Explain.
c) List the accessor method.
d) List the modifier method. 13. How can reusing code decrease the likelihood
e) List the helper method. of bugs in an application?
f) What is the name of the constructor?
g) How many method members are there? 14. Explain what is meant by passing a message.
Extending a Class
Often times there is an existing class that provides a basis for an object
that models a specification. However, the existing class may need addi-
tional methods or different implementations of existing methods to more
closely represent the object for the model. For example, consider a disk,
which has circular shape. It is similar to a circle. However, a disk is three-
dimensional and also has a thickness. Rather than create a whole new class
to represent a disk, a class named Disk could extend the Circle class.
inheritance Making one class an extension of another involves inheritance. Inheritance
allows a class to define a specialized type of an already existing class. In
this case, a disk is a solid circle with a thickness. Classes that are derived
is-a relationship from existing classes demonstrate an is-a relationship. A class “is a” type
of another class. In this case, a disk is a circle with a thickness.
A class can have many levels of inheritance. For example, consider the
TIP The Object class is the following class hierarchy:
superclass of all other classes.
The Puck class inherits the Disk class, which inherits the Circle class. The
Circle class is the superclass of Disk. Disk is the subclass of Circle and the
superclass of Puck. Puck is the subclass of Disk.
base class Designing a subclass requires selecting the superclass, or base class,
and then defining any additional variable and method members for the
subclass. In many cases, existing methods in the base class will also be
derived class overridden by new definitions in the subclass, also called the derived class.
For example, the Disk class design appears similar to:
/**
* constructor
* pre: none
* post: A Disk object has been created with radius r
* and thickness t.
*/
public Disk(double r, double t) {
super(r);
thickness = t;
}
/**
* Changes the thickness of the disk.
* pre: none
* post: Thickness has been changed.
*/
public void setThickness(double newThickness) {
thickness = newThickness;
}
/**
* Returns the volume of the disk.
* pre: none
* post: The volume of the disk has been returned.
*/
public double volume() {
double v;
v = super.area() * thickness;
return(v);
}
/**
* Determines if the object is equal to another
* Disk object.
* pre: d is a Disk object.
* post: true has been returned if objects have the same
* radii and thickness. false has been returned otherwise.
*/
public boolean equals(Object d) {
Disk testObj = (Disk)d;
if (testObj.getRadius() == super.getRadius()
&& testObj.getThickness() == thickness) {
return(true);
} else {
return(false);
}
}
/**
* Returns a String that represents the Disk object.
TIP The equals() and toString() * pre: none
methods override the methods * post: A string representing the Disk object has
by the same name in the Circle * been returned.
class. */
public String toString() {
String diskString;
/* assign instruments */
bandMember1 = assignInstrument();
bandMember2 = assignInstrument();
bandMember3 = assignInstrument();
System.out.println(bandMember1 + " " + bandMember2 + " "
+ bandMember3 + "\n");
The Music application allows the user numerous combinations for select-
ing a band and hearing performances. The code for such an application
would be more complicated and less flexible without the object-oriented
principles of inheritance and polymorphism. Music is versatile because it
takes advantage of inheritance and polymorphism.
The documentation for the Instrument, Vocal, Woodwind, Piccolo,
and Clarinet classes is below. Note that the makeSound() method in the
Instrument class is a method that must be implemented (written) in a sub-
class. This is discussed further in the next section. The code for the classes
is also shown in the next section where abstract classes are discussed.
Class Instrument
Constructor/Methods
Instrument(String name)
creates an instrument object with musician
name.
getMusician() returns a string that is the musician’s name.
makeSound() an abstract method that should return a String
representing the instrument’s sound.
/**
* constructor
* pre: none
* post: A soloist has been selected.
*/
public Performance(Instrument s) {
solo = s;
arrangement = solo.makeSound();
}
/**
* constructor
* pre: none
* post: The members of a trio have been selected.
*/
public Performance(Instrument t1, Instrument t2,
Instrument t3) {
trio _ 1 = t1;
trio _ 2 = t2;
trio _ 3 = t3;
arrangement = trio _ 1.makeSound() + trio _ 2.makeSound()
+ trio _ 3.makeSound();
}
/**
* Begins the performance.
* pre: none
* post: The performance has been played.
*/
public void begin() {
System.out.println(arrangement);
}
/**
* Returns a String that represents the performers.
* pre: none
* post: A string representing the performers has
* been returned.
*/
public String toString() {
String program = "The performance includes ";
program += arrangement;
return(program);
}
}
/**
* constructor
* pre: none
* post: A musician has been assigned to the instrument.
*/
public Instrument(String name) {
musician = name;
}
/**
* Returns the name of the musician
* pre: none
* post: The name of the musician playing the instrument
* has been returned.
*/
public String getMusician() {
return(musician);
}
/**
* Should return the sound of the instrument.
* pre: none
* post: The sound made by the instrument is returned.
*/
abstract String makeSound();
}
The Vocal class is a subclass of Instrument. It provides the body for the
makeSound() method:
/**
* constructor
* pre: none
* post: A singer has been created.
*/
public Vocal(String singerName) {
super(singerName);
}
/**
* Returns the sound of the instrument.
* pre: none
* post: The sound made by the singer.
*/
public String makeSound() {
return("LaLaLa");
}
/**
* Returns a String that represents the instrument.
* pre: none
* post: A string representing the singer.
*/
public String toString() {
return(super.getMusician() + " sings " + makeSound() + ".");
}
}
/**
* constructor
* pre: none
* post: A woodwind instrument has been created.
*/
public Woodwind(String player) {
super(player);
}
/**
* Returns the sound of the instrument.
* pre: none
* post: The sound made by the instrument is returned.
*/
public String makeSound() {
return("toot");
}
}
/**
* constructor
* pre: none
* post: A piccolo has been created.
*/
public Piccolo(String piccoloist) {
super(piccoloist);
}
/**
* Returns the sound of the instrument.
* pre: none
* post: The sound made by the instrument is returned.
*/
public String makeSound() {
return("peep");
}
/**
* Returns a String that represents the instrument.
* pre: none
* post: A string representing the instrument has
* been returned.
*/
public String toString() {
return(super.getMusician() + " plays " + makeSound() + ".");
}
}
/**
* constructor
* pre: none
* post: A clarinet has been created.
*/
public Clarinet(String clarinetist) {
super(clarinetist);
}
/**
* Returns the sound of the instrument.
* pre: none
* post: The sound made by the instrument is returned.
*/
public String makeSound() {
return("squawk");
}
Interfaces
An interface is a class with method declarations that have no implemen-
tations. Although an interface may seem similar to an abstract class, it is
very different. An interface cannot be inherited. It may only be imple-
mented in a class. An interface can add behavior to a class, but it does not
provide a hierarchy for the class.
An interface takes the form:
<access _ level> interface <name> {
<return _ type> <method _ name> (<method _ param>);
…additional methods
}
Comparable interface The Comparable interface is part of the java.lang package. It contains
one method:
Interface Comparable (java.lang.Comparable)
Method
compareTo(Object obj)
returns 0 when obj is the same as the object,
a negative integer is returned when obj is
less than the object, and a positive integer is
returned when obj is greater than the object.
/**
* constructor
* pre: none
* post: A Circle object created. Radius initialized to 1.
*/
public Circle() {
radius = 1; //default radius
}
multiple interfaces A class can implement multiple interfaces. When more than one inter-
face is implemented, the interface names are separated by commas in the
class declaration.
Review: Disk
Modify the Disk class to implement the Comparable interface. Two disks are equal when they have the same
thickness and same radius. Modify the existing client code to test the new method.
payEmployee(emp, payArg) {
System.out.println(emp);
pay = emp.pay(payArg);
System.out.println(pay);
}
if (not quit) {
prompt user for employee number 1, 2, or 3
get empNum
switch (empNum) {
case 1: emp = emp1; break;
case 2: emp = emp2; break;
case 3: emp = emp3; break;
}
if (choice == employee) {
display employee name and title;
} else if (choice == pay) {
prompt user for hours or pay period;
payEmployee(emp, payArg);
}
}
} while (not quit);
}
}
SalesCenter Implementation
The SalesCenter implementation involves creating four files. Three files
are the classes and one file is the client code.
/**
* constructor
* pre: none
* post: An employee has been created.
*/
public Employee(String fName, String lName) {
firstName = fName;
lastName = lName;
}
/**
* Returns the employee name.
* pre: none
* post: The employee name has been returned.
*/
public String toString() {
return(firstName + " " + lastName);
}
/**
* Returns the employee pay.
* pre: none
* post: The employee pay has been returned.
*/
abstract double pay(double period);
}
/**
* constructor
* pre: none
* post: A manager has been created.
*/
public Manager(String fName, String lName, double sal) {
super(fName, lName);
yearlySalary = sal;
}
/**
* Returns the manager salary.
* pre: none
* post: The manager salary has been returned.
*/
public double getSalary() {
return(yearlySalary);
}
/**
* Returns the employee name and title.
* pre: none
* post: The employee name and title has been returned.
*/
public String toString() {
return(super.toString() + ", manager");
}
}
/**
* constructor
* pre: none
* post: An associate has been created.
*/
public Associate(String fName, String lName, double rate) {
super(fName, lName);
hourlyPayRate = rate;
}
/**
* Returns the associate pay rate.
* pre: none
* post: The associate pay rate has been returned.
*/
public double getRate() {
return(hourlyPayRate);
}
/**
* Returns the associate pay for the hours worked.
* pre: none
* post: The associate pay for the hours worked
* has been returned.
*/
public double pay(double hours) {
double payEarned;
/**
* Displays employee name and pay.
* pre: none
* post: Employee name and pay has been displayed
*/
public static void payEmployee(Employee emp, double payArg) {
NumberFormat money = NumberFormat.getCurrencyInstance();
double pay;
System.out.println(emp);
pay = emp.pay(payArg);
System.out.println(money.format(pay));
}
do {
System.out.println("\nEmployee\\Pay\\Quit");
System.out.print("Enter choice: ");
action = input.next();
if (!action.equalsIgnoreCase("Q")) {
System.out.print("Enter employee number (1, 2, or 3):");
empNum = input.nextInt();
switch (empNum) {
case 1: emp = emp1; break;
case 2: emp = emp2; break;
case 3: emp = emp3; break;
}
if (action.equalsIgnoreCase("E")) {
System.out.println(emp);
} else if (action.equalsIgnoreCase("P")) {
System.out.print("Enter the hours for associate or
pay period for manager: ");
payArg = input.nextDouble();
payEmployee(emp, payArg);
}
}
} while (!action.equalsIgnoreCase("Q"));
}
}
Review: SalesCenter
Modify the SalesCenter application to compensate associates when they have worked more than 40 hours.
Associates should be paid their hourly wage when 40 or fewer hours are worked. However, associates earn
time and a half for hours over 40. For example, an associate paid $10 per hour will earn $300 for 30 hours of
work. However, an associate working 42 hours will earn $400 + $30, or $430. The overtime pay is calculated
as (hours over 40) * (1.5 * base hourly rate).
Chapter Summary
This chapter discussed inheritance and polymorphism, two key aspects
of object-oriented programming. Inheritance allows classes to be derived
from existing classes. By extending an existing class, there is less devel-
opment and debugging necessary. A class derived from an existing class
demonstrates an is-a relationship.
A superclass is also called a base class, and a subclass is called a derived
class. The keyword extends is used to create a derived class from a base
class. The keyword super is used to access members of a base class from
the derived class.
Polymorphism is the ability of an object to assume different types. In
OOP, polymorphism is based on inheritance. An object can assume the
type of any of its subclasses.
Abstract classes model abstract concepts. They cannot be instantiated
because they should not represent objects. An abstract class is intended
to be inherited.
Java
1. Explain the difference between a has-a and is-a e) How does the implementation of doThis() in
relationship among classes. Roo affect the implementation of doThis() in
Bo?
2. If a base class has a public method go() and a f) What action does the statement super(1) in
derived class has a public method stop(), which Roo perform?
methods will be available to an object of the g) Can the doThis() method in Bo be called
derived class? from a Roo object? If so, how?
h) Can a method in Roo call the doThis()
3. Compare and contrast implementing an abstract method in Bo? If so, how?
method to overriding a method.
True/False
4. Compare and contrast an abstract class to an
interface. 7. Determine if each of the following are true or
false. If false, explain why.
5. List the method(s) contained in the Comparable a) Inheritance allows a class to define a special-
interface. ized type of an already existing class.
b) Classes that are derived from existing classes
6. Use the following classes to answer the questions demonstrate a has-a relationship.
below: c) A c l a s s c a n h ave o n ly o ne leve l of
inheritance.
interface Wo { d) A class that inherits another class includes
public int doThat();
the keyword i n h e r i t a n c e in the class
}
declaration.
public class Bo { e) When implementing a subclass, existing
private int x; methods i n the base class can be
public Bo(int z) { overridden.
x = z; f) Members of a base class that are declared
} private are accessible to derived classes.
g) Inherited methods are called directly from
public int doThis() { an object.
return(2);
h) Polymorphism is an OOP property in which
}
objects have the ability to assume different
public int doNow() { types.
return(15); i) Abstract classes can be instantiated.
} j) An abstract class must be implemented in its
} subclass.
public class Roo extends Bo implements Wo { k) An abstract method contains a method
declaration and a body.
public Roo {
super(1); l) Inheritance and abstraction allow a hierarchy
} of classes to be created.
m) An interface can be inherited.
public int doThis() { n) An interface can add behavior to a class.
return(10); o) The methods defined in an interface are pri-
}
vate by default.
private int doThat() { p) The Comparable interface contains three
return(20); methods.
}
}
Declaring Arrays
An array is a structure that can store many of the same kind of data
together at once. For example, an array can store 20 integers, another
array can store 50 doubles, and a third array can store 100 objects, such as
Strings. Arrays are an important and useful programming concept because
they allow a collection of related values to be stored together with a single
descriptive name.
An array has a fixed length and can contain only as many data items
as its length allows:
array element An array element is one of the data items in an array. For example, in the
index array of Strings above, Roxy is an element. Each element has an index value,
with 0 being the index of the first item, 1 the index of the second item,
and so on. In the array above, Roxy is the fourth element in the array and
has the index value 3.
declaring and allocating An array must be declared and then space allocated for the elements of
space for an array the array. The statements for declaring an array and allocating space for
its elements take the form:
<type>[] <name>; //declare array
<name> = new <type>[<num>]; //allocate space for elements
TIP The [ ] bracke t s are
operators used for declaring The declaration includes the type followed by brackets ([]) to indicate an
and creating arrays and for array. The array name can be any valid identifier. The new operator allocates
accessing array elements. space for the number of elements indicated in brackets. The statements on
the next page declare an array and then prompt the user for the number
of elements:
If the size of the array is known when the application is written, then
the array can be created and space allocated for elements in one statement,
similar to:
String[] friends = new String[5]; //5 friends
initial array values When space has been allocated for the elements of an array, the array is
initialized to the default values for that element type. For example, each
element of an int array is automatically initialized to 0. An array of objects,
such as a String array, contains null for each element.
declaring and initializing A third way to create an array is to initialize it in the declaration.
Initializing an array means that a value is given for each element. In this
case, the length of the array is determined by the number of elements
between the curly braces:
String[] friends = {"Kermit", "Lucille", "Sammy", "Roxy", "Myah"};
Using Arrays
accessing an element An array element is accessed by including its index in brackets after
the array name. For example, the following statement displays the third
element:
System.out.println(friends[2]); //displays Sammy
changing an element An array element is changed through assignment. For example, the
assignment statement below changes the third element to “Sunshine”:
friends[2] = "Sunshine";
ArrayIndexOutOfBounds A run-time error is generated when an invalid index is used. For exam-
ple, the exception ArrayIndexOutOfBoundsException is thrown when the
following statement tries to execute:
friends[5] = "Wilbur"; //ERROR! Generates an exception.
TIP length is a property, not The Array structure includes the length attribute, which can be used at
a method. Therefore, paren- run time to determine the length of an array:
theses should not follow its
name. numElements = friends.length; //5
Note that the loop iterates from 0 to one less than the length of the array
because length is a count of the elements, not the greatest index value.
The statement above is read “for each String element in friends.” It displays
the names in the array one after the other. Using a for-each loop to traverse
an array does not require a loop control variable. This type of for statement
helps prevent the exception ArrayIndexOutOfBoundsException.
Although convenient at times, the modified for statement above cannot
be used in situations where the array index value is needed. One example
is when the elements of an array are to be accessed in reverse order.
Review: StudentRoster
Create a StudentRoster application that prompts the user for the number of students in the class and then
prompts the user for each student’s name and stores the names in an array. After all the names have been
entered, the application should display the title ”Student Roster” and then list the names in the array.
Review: Squares
Create a Squares application that stores the square of an element’s index in an integer array of 5 elements.
For example, the third element, which has index 2, should store 4. The application should then display the
value of each element in the array.
Review: Reverse
Create a Reverse application that stores the number corresponding to the element’s index in an integer array
of 10 elements. For example, the second element, which has index 1, should store 1. The application should
display the title “Countdown” and then list numbers stored in the array in reverse order.
Array Parameters
A method declaration can include array parameters. The array passed
to a method can be either an entire array or an element of the array. The
method below includes an array parameter. A second parameter, an int
parameter, corresponds to an element of the array:
public static void tryChanging(int[] numbers, int aNum) {
numbers[1] = 123;
aNum = 456;
}
Note that the data type followed by brackets indicates an array parameter,
similar to an array declaration.
offset array indexes To determine the array size when offset array indexes will be used,
subtract the low value from the high and add 1:
int[] counts;
counts = new int[HIGH - LOW + 1];
Review: NumberCounts
Create a NumberCounts application that prompts the user for a number and then counts the occurrences of
each digit in that number.
charAt() The value returned by the charAt() method is a char data type. A char
data type represents a single character, such as a letter or symbol. The
toCharArray() toCharArray() method converts each character in the string to a char and
then assigns it to the appropriate element in an existing char array.
Letters of every alphabet and symbols of every culture have been given a
Unicode representation in a digital code called Unicode. Unicode uses a set of sixteen
1s and 0s to form a sixteen-bit binary code for each symbol. For example,
TIP Refer to Appendix A in the uppercase letter V is Unicode 00000000 01010110, which translates to
this text for more Unicode the base 10 number 86. Lowercase v has a separate code that translates to
symbols and their values. the base 10 number 118.
When a letter is assigned to a char variable, the variable actually stores
the Unicode representation of the letter. Uppercase letters from A to Z have
values from 65 through 90. Lowercase letters from a to z have values from
97 through 122. Because char is a primitive data type, char values can be
compared with relational operators, as the code below demonstrates:
char letter1, letter2;
letter1 = 'a';
letter2 = 'A'
if (letter1 > letter2) {
System.out.println("greater than") //greater than displayed
} else {
System.out.println("less than")
}
Note the statements for creating a char array from a String object. First,
the char array wordLetters was declared. Later, wordLetters was initialized
using the toCharArray() method in the statement:
wordLetters = word.toCharArray();
type casting Type casting was used in the last statement of the CountLetters applica-
tion ((char)i) to produce labels for the contents of the array. Casting the
int to a char produces the Unicode equivalent character for that number.
Review: NameBackwards
Create a NameBackwards application that prompts the user for his or her name and then displays the name
backwards.
Searching an Array
There are many ways to search an array for a specific value. The sim-
linear search plest searching algorithm is called linear search and works by proceeding
from one array element to the next until the specified value is found or
until the entire array has been searched. The Search class below contains
a linear() method that returns the index of a specified int element. If the
element is not found, then -1 is returned:
public class Search {
The condition of the while statement checks all but the last element of
the array, unless the search element is found earlier. If the while statement
completes without finding the element, the index value has been incre-
mented to the last index of the array. The if statement then checks the last
element of the array.
Review: FindName
Add a static method to the Search class that performs a linear search on a String array. The linear() method
should overload the existing method, have parameters for accepting a String array and a String variable,
and return an int indicating the position of the String. Create a FindName application that uses the Search
class. FindName should prompt the user for names to fill an array and then prompt the user for the name
to find.
Two-Dimensional Arrays
An array with two dimensions can be used to represent data that cor-
responds to a grid. For example, a checkerboard, the streets in a city, and
seats in a theater can all be represented with a grid. A tic-tac-toe board
represented in a two-dimensional array can be visualized as shown on
the next page.
The declaration includes the type followed by two sets of brackets ([][]).
The array name can be any valid identifier. The new operator allocates space
for the number of elements indicated in brackets. For example, a tic-tac-toe
board could be created with the statement:
String[][] tttBoard = new String[3][3];
length The length property can be used to determine the number of rows and
columns in a two-dimensional array with two separate statements:
rows = tttBoard.length;
cols = tttBoard[0].length;
nested for statements Nested for statements are often used to access the elements of a two-
dimensional array because one loop counter indicates the row and the
second counter indicates the column. For example, the following state-
ments display the contents of a two-dimensional array:
for(int row = 0; row < tttBoard.length; row++) {
for (int col = 0; col < tttBoard[0].length; col++) {
System.out.print(tttBoard[row][col]);
}
System.out.println();
}
/**
* TTT class.
*/
import java.util.Scanner;
/**
* constructor
* pre: none
* post: tttBoard has been initialized.
* player1 is X and player2 is O.
*/
public TTT() {
player1 = "X";
player2 = "O";
tttBoard = new String[3][3];
for(int row = 0; row < tttBoard.length; row++) {
for (int col = 0; col < tttBoard[0].length; col++) {
tttBoard[row][col] = " ";
}
}
}
/**
* Plays a game of tic-tac-toe with two users,
* keeping track of player (X or O) turns.
* player1 goes first.
* pre: none
* post: A game of tic-tac-toe has been played.
*/
public void play() {
String currPlayer = player1;
int movesMade = 0;
do {
displayBoard();
makeMove(currPlayer);
movesMade += 1;
if (currPlayer == player1){
currPlayer = player2;
} else {
currPlayer = player1;
}
} while (movesMade <= 9 && winner() == " ");
displayBoard();
System.out.println("Winner is " + winner());
}
/**
* Prompt user for a move until a valid move has been made.
* pre: none
* post: A mark has been made in an empty tic-tac-toe
* board square.
*/
private void makeMove(String player) {
Scanner input = new Scanner(System.in);
boolean validMove = false;
int row, col;
do {
System.out.print("Enter row number (0, 1, 2): ");
row = input.nextInt();
System.out.print("Enter column number (0, 1, 2): ");
col = input.nextInt();
if ((row >= 0 && row < tttBoard.length &&
col >= 0 && col < tttBoard[0].length) &&
tttBoard[row][col].equals(" ")) {
tttBoard[row][col] = player;
validMove = true;
} else {
System.out.println("Invalid move. Try again.");
}
} while (!validMove);
}
/**
* Determine winner. Return " " if no winner.
* pre: none
* post: X, O, or " " has been returned as the winner.
*/
private String winner() {
/* test rows */
for (int row = 0; row < tttBoard.length; row++) {
if (tttBoard[row][0].equals(tttBoard[row][1]) &&
tttBoard[row][1].equals(tttBoard[row][2]) &&
!(tttBoard[row][0].equals(" "))) {
return(tttBoard[row][0]);
}
}
/* test diagonal */
if (tttBoard[0][0].equals(tttBoard[1][1]) &&
tttBoard[1][1].equals(tttBoard[2][2]) &&
!(tttBoard[0][0].equals(" "))) {
return(tttBoard[0][0]);
}
dynamic array The ArrayList class implements a dynamic array. A dynamic array var-
ies in size during run time and is used in applications where the size
of an array may need to grow or shrink. An ArrayList object shifts ele-
ments up one position when a new element is added at a specific index.
Elements added to the end of the ArrayList do not move existing elements.
Removing an element from an ArrayList also shifts elements as necessary
to close the gap left by the removed element.
When using an ArrayList object, it is important to understand that only
objects, not primitive types, can be stored. Because the indexOf() method
compares its object parameter to each element of the array, it is important
equals() that the object’s class has an appropriately overridden equals() method.
type parameter The <String> part of the statement is a type parameter informing the com-
piler of what type of objects the ArrayList can contain. The type parameter
is read “of Type” or in this case “of String.”
myStrings.add("Kermit");
myStrings.add("Lucille");
myStrings.add("Sammy");
myStrings.add("Roxy");
myStrings.add("Myah");
myStrings.remove(3);
TIP The for-each statement for (String name : myStrings) {
is not a safe structure for find- System.out.println(name);
ing and removing elements }
from an ArrayList. }
}
Wrapper Classes
Primitive data types cannot be directly stored in an ArrayList because
TIP Java also includes the the elements in an ArrayList must be objects. The Integer and Double
Character, Boolean, Byte, classes, provided with Java, are used to “wrap” primitive values in an
Short, Long, and Float wrap-
object. The Integer and Double wrapper classes include methods for com-
per classes.
paring objects and for returning, or “unwrapping”, the primitive value
stored by the object:
Class Integer ( java.lang.Integer)
Method
compareTo(Integer intObject)
returns 0 when the Integer object value is the
same as intObject. A negative int is returned
when the Integer object is less than intObject,
and a positive int is returned when the Integer
object is greater than intObject.
intValue() returns the int value of the Integer object.
The Integer and Double wrapper classes are in the java.lang package.
Therefore applications do not require an import statement to use the
wrapper classes.
The DataArrayList application creates an ArrayList of Integer values,
compares the values, and then sums the elements:
import java.util.ArrayList;
public class DataArrayList {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
Integer element, element1, element2;
int sum = 0;
numbers.add(new Integer(5));
numbers.add(new Integer(2));
/* compare values */
element1 = numbers.get(0);
element2 = numbers.get(1);
if (element1.compareTo(element2) == 0) {
System.out.println("The elements have the same value.");
} else if (element1.compareTo(element2) < 0) {
System.out.println("element1 value is less than element2.");
} else {
System.out.println("element1 value is greater than element2.");
}
/* sum values */
for (Integer num : numbers) {
element = num;
sum += element.intValue(); //use int value for sum
}
System.out.println("Sum of the elements is: " + sum);
}
}
Review: HighestGrade
Create a HighestGrade application that prompts the user for five grades between 0 and 100 points and stores
the grades in an ArrayList. HighestGrade then traverses the grades to determine the highest grade and then
displays the grade along with an appropriate message.
LocalBank Specification
The LocalBank application allows accounts to be opened, modified,
and closed. Each account has a unique account number, which is required
for all transactions. Transactions include deposits and withdrawals. An
account balance can also be checked.
The LocalBank interface should provide a menu of options. Depending
on the option selected, additional input may be needed. When a transac-
tion is performed, updated account information should be displayed. The
LocalBank output sketch:
if (add account) {
easySave.addAccount();
} else if (not Quit) {
prompt user for account ID;
if (deposit) {
prompt user for deposit amount
easySave.transaction(make deposit, acctID, amt);
} else if (withdrawal) {
prompt user for withdrawal amount
easySave.transaction(make withdrawal, acctID, amt);
} else if (check balance) {
easySave.checkBalance(acctID);
} else if (remove account) {
easySave.deleteAccount(acctID);
}
}
} while (not quit);
LocalBank Implementation
The LocalBank implementation involves creating four files. Three files
are the classes and one file is the client code.
The Bank class is implemented below:
/**
* Bank class.
*/
import java.util.ArrayList;
import java.util.Scanner;
/**
* constructor
* pre: none
* post: accounts has been initialized.
*/
public Bank() {
accounts = new ArrayList<Account>();
}
/**
* Adds a new account to the bank accounts.
* pre: none
* post: An account has been added to the bank's accounts.
*/
public void addAccount() {
Account newAcct;
double bal;
String fName, lName;
Scanner input = new Scanner(System.in);
System.out.print("First name: ");
fName = input.nextLine();
System.out.print("Last name: ");
lName = input.nextLine();
System.out.print("Beginning balance: ");
bal = input.nextDouble();
/**
* Deletes an existing account.
* pre: none
* post: An existing account has been deleted.
*/
public void deleteAccount(String acctID) {
int acctIndex;
Account acctToMatch;
acctToMatch = new Account(acctID);
acctIndex = accounts.indexOf(acctToMatch); //retrieve location of account
if (acctIndex > -1) {
accounts.remove(acctIndex); //remove account
System.out.println("Account removed.");
} else {
System.out.println("Account does not exist.");
}
}
/**
* Displays the account information, including the current balance,
* for an existing account.
* pre: none
* post: Account information, including balance, has been displayed.
*/
public void checkBalance(String acctID) {
int acctIndex;
Account acctToMatch, acct;
import java.text.NumberFormat;
/**
* constructor
* pre: none
* post: An account has been created. Balance and
* customer data has been initialized with parameters.
*/
public Account(double bal, String fName, String lName) {
balance = bal;
cust = new Customer(fName, lName);
acctID = fName.substring(0,1) + lName;
}
/**
* constructor
* pre: none
* post: An empty account has been created with the specified account ID.
*/
public Account(String ID) {
balance = 0;
cust = new Customer("", "");
acctID = ID;
}
/**
* Returns the account ID.
* pre: none
* post: The account ID has been returned.
*/
public String getID() {
return(acctID);
}
/**
* Returns the current balance.
* pre: none
* post: The account balance has been returned.
*/
public double getBalance() {
return(balance);
}
/**
* A deposit is made to the account.
* pre: none
* post: The balance has been increased by the amount of the deposit.
*/
public void deposit(double amt) {
balance += amt;
}
/**
* Returns a true when objects have matching account IDs.
* pre: none
* post: true has been returned when the objects are equal,
* false returned otherwise.
*/
public boolean equals(Object acct) {
Account testAcct = (Account)acct;
if (acctID.equals(testAcct.acctID)) {
return(true);
} else {
return(false);
}
}
/**
* Returns a String that represents the Account object.
* pre: none
* post: A string representing the Account object has been returned.
*/
public String toString() {
String accountString;
NumberFormat money = NumberFormat.getCurrencyInstance();
The Account class has two constructors. The second constructor is used
in the deleteAccount() and transaction() methods of the Bank class for the
purposes of finding the index of the account matching the given account
ID.
The Customer class is implemented on the next page:
/**
* constructor
* pre: none
* post: A Customer object has been created.
* Customer data has been initialized with parameters.
*/
public Customer(String fName, String lName) {
firstName = fName;
lastName = lName;
}
/**
* Returns a String that represents the Customer object.
* pre: none
* post: A string representing the Customer object has
* been returned.
*/
public String toString() {
String custString;
import java.util.Scanner;
Review: LocalBank
Modify the Bank class to prompt the user for a full address (street, city, state, and zip) when an account is
opened. Modify the Customer class to include street, city, state, and zip variable members and changeStreet(),
changeCity(), changeState(), and changeZip() method members. Modify the Customer toString() method
to display complete customer information. Modify the Account class to include a changeAddress() method
member. Modify the Bank class to include a modifyAccount() method member that requires a parameter
for the account ID. modifyAccount() should prompt the user for the new street, city, state, and zip for the
account, find the account with the matching account ID, and then overwrite the existing account object with
the object containing the updated information.
Chapter Summary
This chapter discussed arrays as a structure for storing many of the
same kind of data together at once. A data item stored by an array is called
an element. An element has an index value and is accessed by using the
index inside of [] brackets along with the array name. A for statement and
the for-each statement can be used to access all the elements of an array.
Accessing the elements of an array is called traversing the array. When
the index of an element is needed, the for statement should be used.
An array can be passed to a method as a parameter and is a reference
data type. Passing a single element passes the data stored, not a reference
to the data location.
Many algorithms make use of the array index values for simplifying the
storage and retrieval of data. Offset array indexes are used when a range
should be shifted to correlate to a lower range of index values.
A String can be converted to an array of characters so that individual
characters can be manipulated. Unicode is the standard for numeric rep-
resentation of every letter and symbol in use.
The linear search is an algorithm for searching an array where each ele-
ment is checked one after the other until the desired element is found.
Two-dimensional arrays represent data that corresponds to a grid. The
number of rows in an existing two-dimensional array corresponds to the
length of the array. The number of columns corresponds to the length of
the first row. Elements in a two-dimensional array are accessed by using
a double bracket ([][]) along with the array name.
The ArrayList class is used for storing a collection of objects. Methods
are used for accessing and retrieving elements and for determining the
number of elements in the collection. An ArrayList object is a dynamic
array, which can vary in size at run time. Because an ArrayList can store
only objects, wrapper classes are used to convert primitives to objects.
Autoboxing and auto-unboxing reduces the clutter of wrapper classes.
Array A structure that can store many of the same Generics Used for communicating to the compiler
kind of data together at once. the type of data stored in an ArrayList.
Autoboxing The process in which a primitive is Linear search An algorithm for searching an array
automatically converted to a wrapper class object. in which each element of the array is checked one
after the other.
Auto-unboxing The process in which a primitive
is automatically extracted from a wrapper class Traversing Iterating through element of an array.
object.
Type parameter The part of an ArrayList statement
Collection A group of related elements that are that informs the compiler of what type of objects the
stored together as a single unit. ArrayList can contain, for example, <String>.
Collections framework Classes for implementing Unicode The sixteen-bit digital code used to
collections. represent every letter and symbol.
Dynamic array An array that varies in size at run Wrapper class A class that wraps primitive values
time. in an object.
Java
1. What index value does the third element of an 13. a) Explain the process of autoboxing and give
array have? an example.
b) Explain the process of auto-unboxing and
2. Write the declaration for an array named give an example.
quantities that stores 20 integers. c) What are the advantages of autoboxing and
auto-unboxing?
3. Write a declaration for an array named heights
storing the numbers 1.65, 2.15, and 4.95. True/False
4. Write a for-each statement that displays the inte- 14. Determine if each of the following are true or
ger values stored in an array named grades. false. If false, explain why.
a) All data in an array has the same data
5. a) Write an algorithm for inserting data into an type.
array so that existing data is moved up one b) Index values always begin at 0.
position to make room for the new data. c) The statement int[] empNums = new int[10]
b) Write an algorithm for deleting data from an declares an array with 10 elements.
array so that existing data is moved to close d) In the statement int[] empNums = new int[10],
the gap made by the deleted data. the elements are automatically initialized to
1.
6. How does passing an entire array to a method e) An entire array can be passed to a method.
differ from passing a single element of the f) The method toCharArray() converts a String
array? object to a char array.
g) A linear search never searches an entire
7. Why are offset array indexes required in some array.
cases. h) The statement int[][] grid = new int[4][4]
declares a total of eight elements.
8. What output is displayed by the statements i) In Unicode, uppercase letters have higher
below? base 10 number values than lowercase
letters.
String name = "Elaine"; j) The size of an array can change during the
System.out.println(name.charAt(3));
execution of a program.
k) The ArrayList class implements a dynamic
9. Compare and contrast an array to an ArrayList
array.
by describing the differences between the two
l) Primitive data types can be stored directly
for:
in an ArrayList.
a) accessing an element.
b) adding an element.
c) deleting an element.
d) assigning a new value to an element.
e) determining the size of the collection.
Create a SelectionSort class with a constructor that has an int array parameter, member variables
originalArray and sortedArray, public method display() that displays the contents of the sorted array,
private methods sort() that populates a new array with the elements of the original array in order from
lowest to highest, and findLowest() that returns the index of the element containing the lowest value.
Hint: Since elements of an array cannot actually be “removed” an element can be set to a very high
value after determining its value is the lowest.
Create client code SortedArray, which tests the SelectionSort class. Use the pseudocode below when
implementing the SortedArray client code:
int[] myNums;
SelectionSort sortedArray;
The prizes available on this board are puzzle, game, ball, poster, and doll. At the end of the game, if all
of the squares that say BALL are covered by a penny, the player gets the ball. This is also true for the
other prizes. The board is made up of 25 squares (5 x 5). Each prize appears on three randomly chosen
squares so that 15 squares contain prizes.
Create a PennyPitch application that displays a Penny Pitch board (use [ and ] to indicate squares) with
prizes randomly placed and then simulates ten pennies being randomly pitched onto the board. After
the pennies have been pitched, the application should display a message indicating which prizes have
been won, it any.
Players sit on opposite sides with the large bin to a player’s right designated her home bin. On a turn,
a player selects one of the six pits to remove the stones from and then “sows” the stones counterclock-
wise around the board, placing one stone in each pit including the player’s home bin (but excluding
the opponent’s home bin). If the last stone lands in the player’s home bin, the player gets another turn.
If the last stone lands in an empty pit on the player’s side of the board, the player takes all stones in
the corresponding pit on the opponent’s side and places them in the player’s home bin. When a player
cannot play, the game is over and all stones remaining in the opponent’s pits go to the opponent’s home
bin. The winner is the player with the most stones in the player’s home bin at the end of the game.
For example, if the bottom player plays first and chooses the fourth pit to play from, the board
looks like:
Since the last stone landed in the player’s home bin, the player takes nother turn. The player may
choose the first pit this time in order to capture the opponent’s stones:
The player’s turn is now over, and the opponent now has a turn.
Create a Mankala application. The application should use simple characters to illustrate the board,
and letters to identify the pits, similar to that shown below:
3 3 3 3 3 3
0 0
3 3 3 3 3 3
A B C D E F
What is a GUI?
A GUI is a graphical user interface (sometimes pronounced “gooey”). An
TIP The applications created application written for the Microsoft Windows or Mac OSX Tiger operating
prior to this chapter had a text- system typically has a GUI. The GUI below includes a frame, also called
based, or console, interface. a window, and a label:
Not only does a GUI use components such as frames, buttons, and
text fields to communicate with the user, but GUIs are event-driven. An
event-driven application event-driven application executes code in response to events. An event is an
interaction from the user, such as a button click. A GUI responds to an
event handler event by executing a method called an event handler. For example, when
the user clicks a button, the application must be able to determine which
button was clicked and then execute the code that relates to that button.
JPanel content pane A JFrame object uses a content pane to hold GUI components. A JPanel
object is one choice for a simple content pane. The JPanel class includes
the following methods for adding and removing components:
Class JPanel ( javax.swing.JPanel)
Method
add(Component GUIcomponent)
adds a GUIcomponent to the content pane. When
added, components are given an index value,
with the first component at index 0.
remove(int index)
removes the component with index value
index.
After adding components to the JPanel object, the content frame is added
to the JFrame object using the JFrame setContentPane() method described
above.
The swing package includes the JLabel class for creating labels that
can be added to a content pane. JLabels have several constructors, two of
which are described, in addition to the setText() method:
public HelloWorldWithGUI1(){
/* Create and set up the frame */
frame = new JFrame("HelloWorldWithGUI");
frame.setDefaultCloseOperation(JFrame.EXIT _ ON _ CLOSE);
/**
* Create and show the GUI.
*/
private static void runGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
The swing package includes the JButton class for creating buttons:
Class JButton ( javax.swing.JButton)
Method
JButton(String str)
creates a JButton object displaying the text
str.
setActionCommand(String cmd)
sets the name of the action performed when the
button is clicked to cmd .
getActionCommand()
returns the name of the action that has been
performed by the button.
addActionListener(Object)
adds an object that listens for the user to click
this component.
public HelloWorldWithGUI2(){
/* Create and set up the frame */
frame = new JFrame("HelloWorldWithGUI");
frame.setDefaultCloseOperation(JFrame.EXIT _ ON _ CLOSE);
if (eventName.equals("Hide")) {
label.setText(" ");
button.setText("Show");
button.setActionCommand("Show");
} else {
label.setText(LABEL _ TEXT);
button.setText("Hide");
button.setActionCommand("Hide");
}
}
/**
* Create and show the GUI.
*/
private static void runGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
Review: NumClicks
Create a NumClicks application that contains a button displaying how many times the user has clicked that
button. The application interface should look similar to the following after the user has clicked the button
12 times:
For this application it is not necessary to set the action command. A call to the getActionCommand() method
in the actionPerformed() method is also not needed.
Controlling Layout
layout Layout refers to the arrangement of components. In a Swing GUI, the
layout of a content pane can be controlled by adding borders, using a layout
manager, and setting alignments.
borders A border can be added to most components, including the content pane.
An invisible, or empty, border can be used to add “padding” around a
component to give it distance from other components. Adding an empty
border to the content pane adds space between the components and the
TIP Pixel stands for picture edges of the frame. For example, the content pane in the GUI on the left
element and the number of
has no border, but the content pane on the right has an empty border of
pixels in a surface depends on
the screen resolution. 20 pixels on the top, left, bottom, and right:
layout manager A layout manager determines the order of components on a content pane.
There are many layout managers to choose from, including FlowLayout,
FlowLayout manager BoxLayout, and GridLayout. The FlowLayout manager places components
one next to the other in a row. When a row becomes too long, a new
row is started. The FlowLayout manager is the default manager. The
HelloWorldWithGUI applications use this manager.
GridLayout manager The GridLayout manager places components into a grid of rows and col-
umns. The intersection of a row and column is called a cell. There is one
component per cell in a GridLayout. The GUI below uses a GridLayout.
An additional button was added to illustrate the grid:
alignment Another factor that affects layout is alignment. Alignment refers to the
placement of a component within a layout. For example, both GUIs below
use a BoxLayout, have an empty border of 20, 20, 20, and 20 in the content
pane, and a 20, 50, 20, 50 empty border around the label. The GUI on the
left specifies no aligment for the components, and the GUI on the right
center aligns the label and the button:
public HelloWorldWithGUI2(){
/* Create and set up the frame */
frame = new JFrame("HelloWorldWithGUI");
frame.setDefaultCloseOperation(JFrame.EXIT _ ON _ CLOSE);
setLayout() method The JPanel setLayout() method is used to specify a layout for the content
pane. A BoxLayout object requires arguments for the content pane and the
arrangement. To arrange components in a vertical line, the class constant
PAGE _ AXIS is specified.
setBorder() method The JPanel setBorder() method is used to specify borders for the con-
tent pane. The BorderFactory class has many different kinds of borders
to choose from. For invisible, or empty borders, the createEmptyBorder()
method is used. The arguments specify the width of the top, left, bottom,
and right of the border.
setAlignment() method The JLabel and JButton setAlignmentX() methods are used to specify
the vertical alignment of the components within the layout. Both classes
include several alignment constants, including CENTER _ ALIGNMENT.
GridLayout manager For GUIs with components that should be side by side in rows, the
GridLayout manager may be a better choice. The GridLayout manager is
specified in a statement similar to:
TIP The GridLayout manager contentPane.setLayout(new GridLayout(0, 2, 10, 5))
places components in rows
from left to right in the order The GridLayout object requires arguments for specifying the number
that they are added to the con- of rows and columns and the space between columns and rows. If 0 is
tent pane.
specified for either the rows or columns, the class creates an object with
as many rows or columns as needed. However, only one argument can be
0. In the statement above, the GridLayout object will have as many rows
as needed and 2 columns. There will be 10 pixels between columns and 5
pixels between rows. The GridLayout class is part of the java.awt package.
java.awt Code using this manager requires an import java.awt.* statement.
Review: Sunflower
Create a Sunflower application that displays the Latin name for the sunflower when Latin is clicked and the
English name when English is clicked. The application GUI should use a BoxLayout manager and look similar
to the following after Latin has been clicked:
Review: Riddle
Create a Riddle application that displays a riddle and then solves it when Answer is clicked. The application
GUI should use a GridLayout manager and look similar to the following after Answer has been clicked:
The swing package includes the JTextField class with the following
constructors and methods:
Class JTextField ( javax.swing.JTextField)
Constructor/Methods
JTextField(int col)
creates a JTextField object with width col.
JTextField(String text, int col)
creates a JTextField object displaying default
text text in a field with width col.
getText() returns a String containing the text in the
JTextField.
addActionListener(Object)
adds an object that listens for the user to press
the Enter key in this component.
converting between text and The information typed into a text field is a string, even when numeric
numeric data data is entered. Conversly, the setText() method of a JLabel expects a string
even when the data is numeric. Class methods in the Double and Integer
classes can be used to convert data between numeric and String types:
Class Double ( java.lang.Double)
Method
parseDouble(String text)
returns the double value in the String text.
toString(double num)
returns the String representation of num.
public SemesterAvg(){
/* Create and set up the frame */
frame = new JFrame("Semester Average");
frame.setDefaultCloseOperation(JFrame.EXIT _ ON _ CLOSE);
/**
* Handle button click action event
* pre: none
* post: The average of the grades entered has been
* calculated and displayed.
*/
public void actionPerformed(ActionEvent event) {
String eventName = event.getActionCommand();
if (eventName.equals("Average")) {
double avgGrade;
String g1 = grade1.getText();
String g2 = grade2.getText();
String g3 = grade3.getText();
/**
* Create and show the GUI.
*/
private static void runGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
In the actionPerformed() method, the strings are read from the text
fields. To calculate the average grade, each string is parsed for a double
value (with parseDouble()). The avgGrade value was then converted to a
String with the Double class method toString().
Review: DivisibleBy3
Create a DivisibleBy3 application that prompts the user for an integer and then displays a message when
Check is clicked indicating whether the number is divisible by 3. The application interface should look similar
to the following after the user has typed a number and clicked Check:
The swing package includes the JComboBox class for creating combo
boxes:
Class JComboBox (javax.swing.JComboBox)
Methods
JComboBox(Object[] items)
creates a JComboBox object that contains the
items from the items array, which must be an
array of objects.
setSelectedIndex(int index)
makes the item at index index the selected
item.
getSelectedItem()
returns the String corresponding to the selected
JComboBox item.
setEditable(boolean)
allows text to be typed in the combo box when
true is the boolean argument.
addActionListener(Object)
adds an object that listens for the user to select
an item from this component’s list.
JComboBox event Handling an event from a JComboBox requires two lines of code that
are similar to:
JComboBox comboBox = (JComboBox)event.getSource();
String itemName = (String)comboBox.getSelectedItem();
The first statement determines the source of the action event and then the
second statement determines which item has been selected.
public LatinPlantNames(){
/* Create and set up the frame */
frame = new JFrame("LatinPlantNames");
frame.setDefaultCloseOperation(JFrame.EXIT _ ON _ CLOSE);
if (plantName == "basil") {
latinName.setText("Ocimum");
} else if (plantName == "lavender") {
latinName.setText("Lavandula spica");
} else if (plantName == "parsley") {
latinName.setText("Apium");
} else if (plantName == "perppermint") {
latinName.setText("Mentha piperita");
} else if (plantName == "saffron") {
latinName.setText("Crocus");
} else if (plantName == "sage") {
latinName.setText("Salvia");
}
}
Review: MetricConversion
Create a MetricConversion application that allows the user to select a type of conversion from a combo box
and then the corresponding formula is displayed in a label. To convert from the length measurement inches
to centimeters, the formula is 1 inch = 2.54 centimeters. The formula 1 foot = 0.3048 meters converts the dis-
tance measurement feet to meters. The volume measurement gallon is converted to liters with the fomula
1 gallon = 4.5461 liters. The formula 1 pound = 0.4536 kilograms converts the mass measurement pound to
kilograms. The application interface should look similar to the following after the user has selected feet to
meters:
Color class The java.awt package includes the Color class with numerous color
constant members. The following methods, in the Swing component
classes, can be used to change the background and foreground colors of
the components:
setBackground(Color.constant)
sets the background color of a component to
constant from the Color class.
setForeground(Color.constant)
sets the foreground color of a component to
constant from the Color class.
How the color change affects the component varies. For a JLabel, the
foreground color refers to the color of the text. For a JComboBox, the fore-
ground color refers to the color of the text in the list.
The ColorDemo application demonstrates the color possibilities for
components. The application GUI and the code, except for the runGUI()
and main() methods, follow:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public ColorDemo(){
/* Create and set up the frame */
frame = new JFrame("ColorDemo");
frame.setDefaultCloseOperation(JFrame.EXIT _ ON _ CLOSE);
/**
* Handle a the button click
* pre: none
* post: A message has been displayed.
*/
public void actionPerformed(ActionEvent event) {
String text = name.getText();
Adding Images
Images can make an application more informative, easier to to use, and
fun. Labels and buttons are often used to display an image, but many
GIF, JPG Swing components support images. Images that are GIF and JPG format
work best. Unless a different path is specified in the application code, the
image files must be in the same location as the compiled code.
The JLabel class includes a constructor and a method for displaying
images in a label:
Class JLabel ( javax.swing.JLabel)
Constructor/Method
JLabel(ImageIcon pic)
creates a JLabel object containing pic.
setIcon(ImageIcon pic)
sets the JLabel to contain pic.
The Roll application displays a die face. The user can click Roll Die to
“roll the die” and display the outcome of the roll. The application GUI and
the code, except for the runGUI() and main() methods, follow:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.Math;
public Roll(){
/* Create and set up the frame */
frame = new JFrame("Roll");
frame.setDefaultCloseOperation(JFrame.EXIT _ ON _ CLOSE);
/**
* Handle a button click
* pre: none
* post: A die has been rolled. Matching image shown.
*/
public void actionPerformed(ActionEvent event) {
int newRoll;
Review: Roll
Modify the Roll application to roll two dice. Include an image for each die. Change the colors of the com-
ponents to be more exciting, while still allowing the user to easily read the text on the button and to see the
die images. The die images are name die1.tif, die2.tif, die3.tif, die4.tif, die5.tif, and die6.tif and are supplied
as data files for this text.
public SemesterStats(){
/* Create and set up the frame */
frame = new JFrame("Semester Stats");
frame.setDefaultCloseOperation(JFrame.EXIT _ ON _ CLOSE);
/* Create and add button that will display the min grade */
minButton = new JButton("Min");
minButton.setActionCommand("Min");
minButton.addActionListener(new MinMaxListener());
contentPane.add(minButton);
/* Create and add button that will display the max grade */
maxButton = new JButton("Max");
maxButton.setActionCommand("Max");
maxButton.addActionListener(new MinMaxListener());
contentPane.add(maxButton);
/**
* Handle Average button click event
* pre: none
* post: The grade average has been calculated and displayed.
*/
public void actionPerformed(ActionEvent event) {
double avgGrade;
String g1 = grade1.getText();
String g2 = grade2.getText();
String g3 = grade3.getText();
/**
* Handles the Min and Max button click events
* pre: none
* post: The minimum or maximum grade has been
* determined and displayed.
*/
public void actionPerformed(ActionEvent event) {
String eventName = event.getActionCommand();
double minGrade = 999;
double maxGrade = 0;
double[] grades = new double[3];
grades[0] = Double.parseDouble(grade1.getText());
grades[1] = Double.parseDouble(grade2.getText());
grades[2] = Double.parseDouble(grade3.getText());
if (eventName.equals("Min")) {
for (int i = 0; i < 3; i++) {
if (minGrade > grades[i]) {
minGrade = grades[i];
}
}
stat.setText(Double.toString(minGrade));
} else if (eventName.equals("Max")) {
for (int i = 0; i < 3; i++) {
if (maxGrade < grades[i]) {
maxGrade = grades[i];
}
}
stat.setText(Double.toString(maxGrade));
}
}
}
/**
* Create and show the GUI.
*/
private static void runGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
One class (AvgListener) was used to implement a listener for the Average
button and a second class (MinMaxListener) implements a listener for
the Min and Max buttons. These buttons were combined into one listener
because their algorithms closely match.
BreakAPlate Specification
The BreakAPlate application displays three unbroken plates at the start.
Clicking Play plays the game, displays broken plates, and displays the prize
won. If all three plates are broken, a tiger plush first prize is awarded. If
less than three plates are broken, a sticker consolation prize is awarded.
At the end of a game the Play button changes to Play Again. Clicking Play
Again displays a set of unbroken plates and the button changes back to Play
allowing the user to play repeatedly. The application ends when the user
closes the window.
The BreakAPlate game uses random numbers to determine if a player
has broken all three plates. When three 1s are generated by the random
number generator then the application displays three broken plates. If zero,
one, or two ones are generated, then the application displays two broken
plates indicating a loss.
The BreakAPlate interface should be a GUI that includes a label for dis-
playing the image of the plates, a button for allowing the user to play or
play again, and a label for displaying the the prize won. The BreakAPlate
GUI should look similar to the following before a game is played, after
a losing game has been played, and after a winning game has been
played:
if (Play) {
prize = breakAPlate.start();
if (prize is tiger plush) {
display all broken plates;
} else if (prize is sticker)) {
display two broken plates
}
display prize won
change button to Play Again
} else if (Play Again) {
display unbroken plates
clear prize won text
change button to Play
BreakAPlate Implementation
The BreakAPlate implementation involves creating the BreakAPlate java
file and adding the GameBooth java file to the project.
The BreakAPlate application is implemented below:
/**
* BreakAPlate.
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public BreakAPlate(){
/* initialize game booth and player */
breakAPlate = new GameBooth(0, FIRST _ PRIZE, CONSOLATION _ PRIZE);
/**
* Handle the button click
* pre: none
* post: The appropriate image and message are displayed.
*/
public void actionPerformed(ActionEvent event) {
String eventName = event.getActionCommand();
String prize;
if (eventName == "Play") {
prize = breakAPlate.start();
if (prize.equals(FIRST _ PRIZE)) {
plates.setIcon(new ImageIcon("plates _ all _ broken.gif"));
} else if (prize.equals(CONSOLATION _ PRIZE)) {
plates.setIcon(new ImageIcon("plates _ two _ broken.gif"));
}
prizeWon.setText("You win: " + prize);
play.setText("Play Again");
play.setActionCommand("Play Again");
} else if (eventName == "Play Again") {
plates.setIcon(new ImageIcon("plates.gif"));
prizeWon.setText(" ");
play.setText("Play");
play.setActionCommand("Play");
}
}
When Play is clicked, the user either wins or loses. The output below
shows a losing game:
Review: BreakAPlate
Modify the BreakAPlate application to display a picture of the prize won rather than text naming the prize.
The tiger_plush.gif, sticker.gif, and placeholder.gif are supplied as data files for this text. The placeholder.gif
file is a white square that is the same size as the tiger_plush and sticker images. The placeholder.gif file
should be displayed in the label at the start of each game. The modified BreakAPlate interface should look
similar to the following after the user has played a winning game:
ActionListener The java.awt.event interface that FlowLayout A javax.swing class for setting the
contains the actionListener() method. layout of a content pane.
actionPerformed() A method that is implemented Swing API A part of the Java Foundation Classes
to respond to events. This method is the only method that contains numerous components for creating
in the ActionListener interface. GUIs.
BorderFactory The java.lang class with class meth- this The keyword for indicating an object itself.
ods for creating a border object.
BoxLayout A javax.swing class for setting the layout
of a content pane.
Color The java.awt class that contains constants
for changing component colors.
Double A java.lang class for converting numbers
between numeric and text data.
GridLayout A java.awt class for setting the layout
of a content pane.
ImageIcon A java.swing class for converting
an image, such as a GIF or JPG, to an ImageIcon
object.
Integer A java.lang class for converting numbers
between numeric and text data.
java.awt The package containing the GridLayout
class and Color class constants.
java.awt.event The package containing the
ActionListener interface.
java.swing The package containing the Swing
API classes.
JButton A java.swing class for creating a button in
a GUI. The class includes methods for adding text
or images to the label.
JComboBox A java.swing class for creating a combo
box in a GUI.
JFrame A java.swing class for creating a window,
also called a frame, in a GUI.
JLabel The java.swing class for creating a label in
a GUI. The class includes methods for adding text
or images to the label.
JPanel The java.swing class for creating a content
panel for a frame. The class includes methods for
adding and removing components.
JTextField The java.swing class for creating a text
field.
1. Explain the difference between an event-driven 15. An application prompts a user to select a name
application and a console-based application. from a list of six names. Which is a better
component choice: a text field or a combo box?
2. Explain how code is executed in an event-driven Explain.
application.
16. Would white text on a pink background be a
3. Can components be added directly to a frame? good color combination for a GUI? Why or why
Explain. not?
4. Can a label respond to events? Explain. 17. What image types are supported in a Swing
GUI?
5. Why do you think a GUI needs to be run from
an event-dispatching thread? 18. Which components are often used to display an
image?
6. What is the difference between a label and a
button? 19. What must an image be converted to in order
to be displayed by a Swing component?
7. a) What does this indicate when used as the
argument for the the addActionListener() True/False
method?
b) What must the object listening for an event 20. Determine if each of the following are true or
contain? false. If false, explain why.
a) JFra me is a class i n t he javax.swi ng
8. List three ways to control the layout of a content package.
pane. b) A button click is an event handler.
c) Labels can be changed by the user.
9. What type of borders are used to add padding d) A JFrame object uses a content pane to hold
around components? GUI components.
e) The index value for the first component on
10. List three layout managers and explain how a content pane is 1.
each arranges the components on a content f) The JLabel class constant LEADING indicates
pane. right alignment.
g) A thread is a sequential process that runs
11. Which class is used to return an object for the from start to finish.
setBorder() method? h) Swing components use listeners to determine
if an event has occurred.
12. Are borders for padding necessary when the i) A class that uses a listener must implement
GridLayout manager is used? Explain. an ActionListener class.
j) An empty border indicates that there is no
13. What must first be done with numeric data space around a component.
typed in a text field before it can be used in a k) The FlowLayout manager places components
calculation? one after the other in a column, with one
column per line.
14. What is the value of num1 in the last statement l) All components on a GUI must have the
below? same alignment.
m) The class content PAGE_AXIS specifies that
double num1; components should be arranged in a vertical
Double num2 = new Double(3);
line.
String num3 = "5";
num1 = num2.doubleValue() + n) The JLabel setAlignmentX() method is used
Double.valueOf(num3).doubleValue(); to specify the horizontal alignment of the
components within the layout.
Create a Clacker application that displays 12 buttons numbered 1 through 12. Each of these buttons
can be clicked to ”cover” it. A covered button displays nothing. Another button labeled Roll can be
clicked to roll the dice. Include labels to display the appropriate die images for each roll. Another label
displays the number of rolls taken. A New Game button can be clicked to clear the labels and uncover
the buttons for a new game.
F iles are used by many applications for storing and retrieving data. In
this chapter, sequential file access, including object serialization will be
discussed. Exception handling will also be explained.
What is a File?
Up to this point, the applications created in this text have stored data
in the computer’s memory. However, storage in memory is available only
when the computer is on and an application is running. A file is a collec-
tion of related data stored on a persistent medium such as a hard disk or
persistent a CD. Persistent simply means lasting.
Files often store data used by an application. Files are also used to store
the data generated by an application. In either case, a file is separate from
the application accessing it and can be read from and written to by more
than one application. Most applications require access to one or more files
on disk.
Handling Exceptions
exception An exception is an error affecting program execution. If an exception is
not taken care of, or handled, the application abruptly terminates. Although
many types of exceptions may still require program termination, an excep-
tion handler can allow an application to terminate gracefully by providing
the user with an informative error message.
exception handler An exception handler is a block of code that performs an action when an
try-catch-finally exception occurs. The try-catch-finally statement can be used to write
an exception handler. It takes the form:
try {
<statements>
} catch (exception err _ code) {
<statements>
} …additional catch clauses
} finally (exception err _ code) {
<statements>
The try statements are the statements that could possibly generate an
exception. The catch clause waits for the exception matching the exception
parameter and then executes its code. If more than one type of exception is
possible from the statements in the try clause, then a separate catch should
be written for each type of exception. The finally clause is optional and
executes its statements regardless of what happens in the try-catch por-
tion of the error handler.
file position The file stream keeps track of the file position, which is the point where
reading or writing last occurred. File streams are used to perform sequential
sequential file access file access, with all the reading and writing performed one character after
another or one line after another.
The carriage return character (Cr) followed by a line feed character (Lf) is
line terminator, end of file called a line terminator. A –1 is the end of file.
try {
in = new FileReader(textFile);
readFile = new BufferedReader(in);
while ((lineOfText = readFile.readLine()) != null ) {
System.out.println(lineOfText);
}
readFile.close();
in.close();
} catch (FileNotFoundException e) {
System.out.println("File does not exist or could
not be found.");
System.err.println("FileNotFoundException: "
+ e.getMessage());
} catch (IOException e) {
System.out.println("Problem reading file.");
System.err.println("IOException: " + e.getMessage());
}
}
The ReadFile application reads and displays the file contents within
a try-catch statement because both the FileReader and BufferedReader
constructors and methods throw exceptions if there is a problem reading
the file. A try can have multiple catch statements. The catch statements are
in the order that they may occur. For example, the FileNotFoundException
is handled first because the FileReader object is created first in the try
statement.
The close() methods are used to close the FileReader and BufferedReader
streams. It is important that the streams be closed in the reverse order that
they were opened.
The ReadFile application displays the following output when run:
Review: Assignment
Create a Assignment application that reads and then displays the contents of a file containing instructions for
this assignment. Use Notepad or some other word processor to create the file. Be sure that the file is saved as
a Text file (TXT). The Assignment application will need to include the correct path to the location of the file.
If a path is not specified, the file must be placed in the same folder as the Assignment executable file.
The AvgScore application reads tests scores that are stored one score
per line in a text file and then reports the average:
import java.io.*;
try {
in = new FileReader(dataFile);
readFile = new BufferedReader(in);
while ((score = readFile.readLine()) != null ) {
numScores += 1;
System.out.println(score);
totalScores += Double.parseDouble(score);
}
avgScore = totalScores / numScores;
System.out.println("Average = " + avgScore);
readFile.close();
in.close();
} catch (FileNotFoundException e) {
System.out.println("File does not exist or could
not be found.");
System.err.println("FileNotFoundException: "
+ e.getMessage());
} catch (IOException e) {
System.out.println("Problem reading file.");
System.err.println("IOException: " + e.getMessage());
}
}
}
When a FileWriter object is created, the file referenced by the File object
is automatically overwritten unless the FileWriter object is set to append. In
either case, if the file does not yet exist, a new one will be created. Caution
must be used so that a file is not inadvertently overwritten.
The CreateDataFile application prompts the user for names and scores
and then writes them to a new file:
import java.io.*;
import java.util.Scanner;
try {
out = new FileWriter(dataFile);
writeFile = new BufferedWriter(out);
for (int i = 0; i < 5; i++) {
System.out.print(:Enter student name: ");
name = input.next();
System.out.print("Enter test score: ");
score = input.nextDouble();
writeFile.write(name);
writeFile.newLine();
writeFile.write(String.valueOf(score));
writeFile.newLine();
}
writeFile.close();
out.close();
System.out.println("Data written to file.");
} catch (IOException e) {
System.out.println("Problem writing to file.");
System.err.println("IOException: " + e.getMessage());
}
}
}
Note that the application will overwrite the StuScores.dat file each time
that it is run. The CreateDataFile application displays output similar to
that shown on the next page:
Object Serialization
A file can also be used to store object data. Writing objects to a file is
called object serialization. In this process, class information about an object
is written out to a stream. If a class uses another class, this information is
also written out, and so on. When information about an object is retrieved
from a file, it is called object deserialization.
Object serialization and deserialization is performed with object out-
put and input streams. The FileOutputStream and ObjectOutputStream
classes, both from the java.io package, are used together to write objects
to a file. The FileInputStream and ObjectInputStream classes, also from
the java.io package, are used together to read objects from a file. Some of
the methods from the classes for writing and reading objects include:
Class FileOutputStream (java.io)
Constructor/Method
FileOutputStream(File fileName, boolean append)
creates an output file stream for the File object.
If append is true, then data written to the file
will be added after existing data, otherwise
the file will be overwritten or created if the
file does not exist. This method throws a
FileNotFoundException exception if the file
cannot be opened or created.
close() closes the output file stream. This method
throws an IOException exception if the file
cannot be closed.
try {
/* write objects */
FileOutputStream out = new FileOutputStream(stuFile);
ObjectOutputStream writeStu = new ObjectOutputStream(out);
writeStu.writeObject(new Student("Drew", 87));
writeStu.writeObject(new Student("Tia", 92));
writeStu.close();
System.out.println("Data written to file.");
/* read objects */
FileInputStream in = new FileInputStream(stuFile);
ObjectInputStream readStu = new ObjectInputStream(in);
Student stu1 = (Student)readStu.readObject();
Student stu2 = (Student)readStu.readObject();
readStu.close();
System.out.println(stu1);
System.out.println (stu2);
} catch (FileNotFoundException e) {
System.out.println("File could not be found.");
System.err.println("FileNotFoundException: "
+ e.getMessage());
} catch (IOException e) {
System.out.println("Problem with input/output.");
System.err.println("IOException: " + e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println("Class could not be used to
cast object.");
System.err.println("ClassNotFoundException: "
+ e.getMessage());
}
}
}
/**
* constructor
* pre: none
* post: A Student object has been created.
* Student data has been initialized with parameters.
*/
public Student(String name, double grade) {
stuName = name;
stuGrade = grade;
}
/**
* Creates a string representing the student object
* pre: none
* post: A string representing the student object
* has been returned.
*/
public String toString() {
String stuString;
If the objects of a class are to be written to a file, the class must imple-
Serializable interface ment the Serializable interface. This interface is part of the java.io package
and contains no methods to implement. It simply allows information about
an instance of the class to be written out.
Note that reading an object from a file requires casting. The readObject()
method reads Object data from the file. It is up to the programmer to cast
the object to the appropriate type.
The ObjectWriteRead application catches several exceptions. First, a
FileNotFoundException occurs when there is a problem creating a File
object. IOException is a more general exception and occurs for various
input/output problems. If IOException were first in the catch clauses,
the other more specific exceptions would not be caught and the user
would not be able to read their descriptive error messages. Finally, the
ClassNotFoundException occurs if the class for an object written to the
file cannot be found.
Review: Roster
Create a Roster application that prompts the user for the name of the file to store student names and then
prompts the user for the number of students in a class. The application should then prompt the user for
the first and last name of each student and write this data to a file. After all the data is written to a file, the
application displays the class roster with one name after the other in a list. Create a StuName class that has
member variables firstName and lastName and a toString() member method.
LocalBank2 Specification
The LocalBank2 application has the same specification as LocalBank.
It allows accounts to be opened, modified, and closed. Each account
has a unique account number, which is required for all transactions.
Transactions include deposits and withdrawals. An account balance can
also be checked.
The LocalBank2 interface will not change from LocalBank. It will pro-
vide a menu of options:
The LocalBank2 algorithm will not change from the LocalBank applica-
tion algorithm.
do {
prompt user for transaction type
if (add account) {
easySave.addAccount();
} else if (not Quit) {
prompt user for account ID;
if (deposit) {
prompt user for deposit amount
easySave.transaction(make deposit, acctID, amt);
} else if (withdrawal) {
prompt user for withdrawal amount
easySave.transaction(make withdrawal, acctID, amt);
} else if (check balance) {
easySave.checkBalance(acctID);
} else if (remove account) {
easySave.deleteAccount(acctID);
}
}
} while (not quit);
easySave.updateAccounts(accountsFile);
LocalBank2 Implementation
The LocalBank2 application is shown below:
/**
* LocalBank2 client code.
*/
import java.io.*;
import java.util.Scanner;
if (action.equalsIgnoreCase("A")) {
easySave.addAccount();
} else if (!action.equalsIgnoreCase("Q")) {
System.out.print("Enter account ID: ");
acctID = input.next();
if (action.equalsIgnoreCase("D")) {
System.out.print("Enter deposit amount: ");
amt = input.nextDouble();
easySave.transaction(1, acctID, amt);
} else if (action.equalsIgnoreCase("W")) {
System.out.print("Enter withdrawal amount: ");
amt = input.nextDouble();
easySave.transaction(2, acctID, amt);
} else if (action.equalsIgnoreCase("C")) {
easySave.checkBalance(acctID);
} else if (action.equalsIgnoreCase("R")) {
easySave.deleteAccount(acctID);
}
}
} while (!action.equalsIgnoreCase("Q"));
The Bank class is shown below. The accounts are expected to be loaded
from a file. Additionally, the number of accounts is also kept in the file.
This number is the first data item in the file. It is read first and then used
to determine how many accounts to read from the file. Throughout the
class, the number of accounts is updated when a new account is added and
when an account is deleted. When updateAccounts() is called, the number
of accounts is written to the file first, followed by the accounts:
/**
* Bank class.
*/
import java.util.ArrayList;
import java.io.*;
import java.util.Scanner;
/**
* Adds a new account to the bank accounts.
* pre: none
* post: An account has been added to the bank's accounts.
*/
public void addAccount() {
Account newAcct;
double bal;
String fName, lName;
Scanner input = new Scanner(System.in);
/**
* Deletes an existing account.
* pre: none
* post: An existing account has been deleted.
*/
public void deleteAccount(String acctID) {
int acctIndex;
Account acctToMatch;
/**
* Performs a transaction on an existing account. A transCode of 1 is for deposits
* and a transCode of 2 is for withdrawals.
* pre: transCode is 1 or 2.
* post: A transaction has occurred for an existing account.
*/
public void transaction(int transCode, String acctID, double amt) {
int acctIndex;
Account acctToMatch, acct;
/**
* Accounts are written to a file for storage.
* pre: none
* post: accounts have been written to acctFile.
*/
public void updateAccounts(File acctsFile) {
try {
FileOutputStream out = new FileOutputStream(acctsFile);
ObjectOutputStream writeAccts = new ObjectOutputStream(out);
writeAccts.writeInt(numAccts);
for (Object acct : accounts){
writeAccts.writeObject(acct);
}
writeAccts.close();
} catch (FileNotFoundException e) {
System.out.println("File could not be found.");
System.err.println("FileNotFoundException: " + e.getMessage());
} catch (IOException e) {
System.out.println("Problem with input/output.");
System.err.println("IOException: " + e.getMessage());
}
}
}
import java.io.*;
import java.text.NumberFormat;
import java.io.*;
Chapter Summary
This chapter discussed files and exception handling. A file is a data
stored on a persistent medium such as a hard disk or CD. In Java, a File
object is associated with a file name. A File object can be used to create or
delete a file.
An exception is an error affecting program execution. An exception
handler is a block of code that performs an action when an exception
occurs. This chapter introduced the try-catch-finally statement for writ-
ing exception handlers.
A file must be associated with a stream in order to read and write to the
file. A file stream processes characters and is used to perform sequential
file access. The FileReader, BufferedReader, FileWriter, and BufferWriter
classes are used to read and write to a file.
An application written to process numeric data from a file must convert
the file data from a strings to numerics. The Double and Integer classes
contain methods for converting numeric characters in a string to an int
or a double.
Objects can be written to a file in a process called object serialization.
Reading objects from a file is called object deserialization. Serialization and
deserialization are performed with an object stream. The FileOutputStream,
ObjectOutputStream, FileInputStream, and ObjectInputStream classes are
used to write and read objects to a file. The ObjectOutputStream and
ObjectInputStream classes can also be used to write and read primitve
data to a file.
End of file A –1 in the file stream. Line terminator A carriage return followed by a
line feed in the file stream.
err stream The stream used for displaying error
messages to the user. Object deserialization The process used to read
objects from a file.
Exception An error affecting program execution.
Object serialization The process used to write
Exception handler A block of code that performs
objects to a file.
an action when an exception occurs.
Output file stream A file stream for writing to a
File A collection of related data stored on a per-
file.
sistent medium.
Persistent Lasting.
FileNotFoundException An exception thrown
when a file does not exist. Sequential file access Reading and writing one
character after another.
File position The point at which reading or writing
in the stream last occurred. Stream The construct used for processing
characters.
Handle Take care of.
Throw Generate.
Input file stream A file stream for reading a file.
Java
BufferedReader A java.io class used for creating FileWriter The java.io class used for creating a file
a buffered file stream for reading a file. stream for writing to a file.
BufferedWriter A java.io class used for creating a Integer A java.lang class for converting numeric
buffered file stream for writing to a file. text in a string to an int.
Double A java.lang class for converting numeric try-catch-finally Statement used to write an excep-
text in a string to a double. tion handler.
File The java.io class used for creating an object ObjectInputStream A java.io class used for creating
that refers to a file. an object for reading objects from a file.
FileInputStream A java.io class used for creating ObjectOutputStream A java.io class used for creat-
an object input stream. ing an object for writing objects to a file.
FileOutputStream A java.io class used for creating
an object output stream.
FileReader The java.io class used for creating a file
stream for reading a file.
1. Can data in memory be called a file? Explain. c) Z-1 is the end of file.
d) A file on disk is a set of numbers ranging
2. Write the import statement required to access from 0 to 9.
the File Class in an application. e) Numeric data in a file must be converted to
a primitive data type before it can be pro-
3. Identify the error in the following statement: cessed numerically.
File textFile = new File("c:\inventory.txt"); f) A FileNotFoundException exception is
thrown if a file cannot be closed.
4. a) Which statement is used to write an excep- g) The output file stream is a file stream for
tion handler? writing to the screen.
b) Write an exception handler to handle an h) Reading an object from a file requires
IOException if a specified file name cannot casting.
be used to create a file. The exception han-
dler should display appropriate messages to
the user.
True/False
12. Determine if each of the following are true or
false. If false, explain why.
a) An exception always results in program
termination.
b) Sequential file access reads and writes data
one character after another or one line after
another.
b) Modify the WordStats application to list the words in alphabetical order. This can be
done by either using the sorting algorithm presented in Chapter 10, Exercise 11 or by
keeping the words in order as they are read.
For example:
BADED
Smithgall
BADDD
DeSalvo
CAEED
Darji
BADED
Create a TestProcessor application that processes the test results file for any number of students. The
application should provide statistics similar to:
Smithgall 80%
DeSalvo 60%
Darji 100%
Application output should display the story with apporpriate replacements made. A possible output
would produce a MadLib similar to:
Bugsy Kludge is a vegetable with our company.
His job is to display all of the elephants.
Create a MergeFiles application that merges the integers ordered from low to high in two files into a
third file, keeping the order from low to high. For example, two files of integers could contain:
File 1: 12 23 34 45 56 67 69 123 133
File 2: 4 5 10 20 35 44 100 130 150 160 180
The application should not use an array to temporarily store the numbers, but should merge the two
files by taking one element at a time from each. After MergeFiles has been run, the third file should
contain:
4 5 10 12 20 23 34 35 44 45 56 67 69 100 123 130 133 150 160 180
Tags are enclosed in angle brackets, < >. The tag <br> means to start a new line. The tag <p> means to
start a new paragraph (a blank line). The tag <hr> means to draw a horizontal rule. When these tags
are interpreted, the HTML document above is displayed as:
JUNE BUGS
by Avis Harley
------------------------------------------------
by Avis Harley
-----------------------------------
Selection Sort
Sorting is the process of putting items in a designated order, either from
low to high or high to low. The selection sort algorithm starts by finding
the lowest item in a list and swapping it with the first. Next, the lowest
item among items 2 through the last is found and swapped with item 2,
and then the lowest item among items 3 through the last is swapped with
item 3. This process is continued until the last item is reached, at which
point all the items are sorted.
The selection sort algorithm compares an element to the items in the
array after the element. This algorithm can be implemented with nested
for loops. The outer loop controls which element to compare and the inner
for loop iterates through the array after the element (the subarray). The
selection sort pseudocode for sorting an array of items from low to high
appears like:
for (arrayIndex = 0 to numItems-1) {
for (subarrayIndex = arrayIndex to numItems-1) {
if (items[subarrayIndex] < items[arrayIndex]) {
swap items[subarrayIndex] and items[arrayIndex]
}
}
}
/**
* Sorts an array of data from low to high
* pre: none
* post: items has been sorted from low to high
*/
public static void selectionSort(int[] items) {
Sorts.selectionSort(test);
System.out.println("Sorted:");
displayArray(test);
}
}
Sorting Objects
Relational operators, such as > and <, cannot be used to compare objects.
Objects use methods of their class to determine if one object is greater
equals(), compareTo() than, less than, or equal to another. The equals() method in a class is used
to determine equality. For determining order, the compareTo() method is
used.
Comparable interface Objects that are to be sorted must have a class that implements the
Comparable interface. The String, Double, and Integer clases implement
the Comparable interface. The Circle class in Chapter 9 also implements
the Comparable interface.
An interface cannot be used to instantiate a class. However, an interface
can be used as a data type. An interface data type can reference any class
polymorphism that implements it. This polymorphic behavior makes it possible to imple-
ment a generic sort that works with any list of objects that implement the
Comparable interface.
The Sorts class has been modified to include an overloaded SelectionSort()
method, which has a Comparable array parameter:
/**
* Sorts an array of objects from low to high
* pre: none
* post: Objects have been sorted from low to high
*/
public static void selectionSort(Comparable[] items) {
The TestSorts application, on the next page, has been modified to sort
an array of Circle objects:
Sorts.selectionSort(test);
System.out.println("Sorted:");
displayArray(test);
}
}
Insertion Sort
More efficient than the selection sort algorithm is the insertion sort
algorithm. An insertion sort starts by sorting the first two items in a list.
This sort is performed by shifting the first item into the second spot if
the second item belongs in the first spot. Next, the third item is properly
inserted within the first three items by again shifting items into their
appropriate position to make room for the moved item. This process is
repeated for the remaining elements.
The insertion sort is illustrated below with an array containing four
elements. Step 1 shows the original list, which contains items 40, 10, 30,
and 20. Step 2 shows that 40 is shifted to make room for the second item,
10. Next, 30 compared to the value in the previous position (40), 40 is
shifted into position 3, 30 is then compared to the value in the previous
position (10), and then 30 is placed at position 2. This process repeats for
the remaining items.
Sorts.insertionSort(test);
Review: ObjectsInsertionSort
Create an ObjectsInsertionSort application that implements an insertion sort on an array of objects. Test the
sort on an array of String objects.
Recursion
A method can call itself. This process is called recursion and the calls
recursive call are referred to as recursive calls. The RecursiveDemo application contains
a method that calls itself:
public class RecursiveDemo {
The call showRecursion(2) from the main() method is the initial call. In
the showRecursion() method, a call is made to itself passing num - 1. When
showRecursion is called with num equal to 1, the if is skipped and the
remaining statement in the method is executed. At this point the stack of
calls made before num was 1 are executed in the reverse order they were
made, with each call executing the statement in the method after the
recursive call (after the if).
The RecursiveDemo produces the output shown on the next page:
/**
* Returns num to the power power.
* pre: num and power are not 0.
* post: num to the power power has been returned.
*/
public static int intPower(int num, int power) {
int result;
if (power == 0) {
result = 1;
} else {
result = num * intPower(num, power-1);
}
return(result);
}
Mergesort
The selection sort is simple, but inefficient, especially for large arrays.
TIP Measuring an algorithm’s Imagine using the selection sort process by hand for a pile of 1000 index
efficiency is discussed later in
cards. Searching through the cards for the lowest item would take a long
this chapter.
time, but more importantly, after each search the remaining cards must
be searched again! Each card ends up being examined about 500 times.
The mergesort algorithm takes a “divide-and-conquer” approach to sort-
ing. Imagine the 1000 cards being divided into two piles of 500. Each pile
could then be sorted (a simpler problem) and the two sorted piles could
be combined (merged) into a single ordered pile. To further simplify the
sorting, each subpile could be divided and sorted, and so on. This algo-
rithm is best implemented recursively.
The mergesort pseudocode is:
if there are items remaining {
mergesort the left half of the items
mergesort the right half of the items
merge the two halves into a completely sorted list
}
The array is sorted from start to mid and from mid+1 to end. The merge()
method starts by examining the first element of each sorted portion, start
and mid+1, as indicated by pos1 and pos2:
This process is repeated until all items have been moved. Since it is likely
that one array portion will be exhausted before the other, merge() tests for
this case and just moves items from the remaining list. Finally, merge()
copies the merged items in the temporary array to the original array.
The Sorts class has been modified to include a mergesort() method.
Note that the merge() method is private because it is a helper method:
/**
* Sorts items[start..end]
* pre: start > 0, end > 0
* post: items[start..end] is sorted low to high
*/
public static void mergesort(int[] items, int start, int end) {
if (start < end) {
int mid = (start + end) / 2;
mergesort(items, start, mid);
mergesort(items, mid + 1, end);
merge(items, start, mid, end);
}
}
The if in the merge() method says that if the pos1 (left) subarray is
exhausted, or if the pos2 (right) subarray is not exhausted and the pos2
element is less than the pos1 element, then move an item from the pos2
subarray to the temp array, otherwise move an item from the pos1 subar-
ray. This process continues until both subarrays are exhausted.
System.out.println("Sorted:");
displayArray(test);
}
}
Review: ObjectsMergesort
Create an ObjectsMergesort application that implements a mergesort on an array of objects. Test the sort on
an array of String objects.
/**
* Searches items array for goal
* pre: items is sorted from low to high
* post: Position of goal has been returned,
* or -1 has been returned if goal not found.
*/
public static int binarySearch(int[] items, int start,
int end, int goal) {
Review: SearchLocations
Create a SearchLocations application that displays the positions examined during a binary search. The
application output should look similar to:
Review: BinarySearch2
Create a BinarySearch2 application that implements a nonrecursive binary search. The binary search algo-
rithm can be implemented without recursion by doing the following:
• Enclose the method body with a do-while loop
• Replace the recursive calls with appropriate assignments to the values of start or
end.
Depth-First Searching
Many programs generate and search through a series of possibilities,
such as:
• different paths through a maze
• different possible ways of making change
• different possible plays in a game
• different schedules for a student in a school
• different pixels reachable from an initial pixel
All these tasks can be solved through the recursive technique called depth-
first searching. The depth-first searching algorithm works by searching from
a given starting position, processing that position, and then (recursively)
searching from all adjacent positions.
Depth-first searching can be illustrated in a DetectColonies application
that allows a researcher to determine the number and size of distinct
colonies of bacteria on a microscope slide. The slide has been converted to
digital format, where a * represents a cell that is part of a colony, and a -
represents the background color of the slide. A slide file has the format:
First line: length of slide
Second line: width of slide
Remaining lines: slide data.
For example, a slide file could look similar to:
7
9
---------
---*--*--
--***-**-
***---*--
**-**----
---****--
---*--*--
The latter four lines are recursive calls. To find the starting cells, each cell
in the slide is tested with a nested for loop.
When implementing a depth-first search algorithm, code must be
included to avoid infinite recursion. For example, a starting cell of (1, 3)
generates a recursive call with cell (2, 3), which generates a call with (1, 3)
again, which generates a call with (2, 3), and so on. For this application, a
cell will be changed to the background color once it has been examined.
This makes counting colonies a destructive algorithm.
The DetectColonies application can be modeled with a Slide class. The
constructor will load the slide data into variable member slideData, which
is a two-dimensional array appropriate for modeling the slide. Method
members displaySlide() and displayColonies() will display the slide and
determine the colonies. Member constants COLONY and NON _ COLONY will
represent * and -.
The displayColonies() method checks each cell of the entire slide, and
whenever a colony cell is encountered, displayColonies() determines the
colony size and displays data about the colony. To determine the size,
displayColonies() calls a private member method collectCells(), which
changes a cell to the background once it is counted.
The Slide class is implemented on the next page:
/**
* constructor
* pre: Slide file contains valid slide data in the format:
* first line: lenght of slide
* second line: width of slide
* remaining lines: slide data
* post: Slide data has been loaded from slide file.
*/
public Slide(String s) {
try {
File slideFile = new File(s);
FileReader in = new FileReader(slideFile);
BufferedReader readSlide = new BufferedReader(in);
int length = Integer.parseInt(readSlide.readLine());
int width = Integer.parseInt(readSlide.readLine());
slideData = new char[length][width];
for (int row = 0; row < length; row++) {
for (int col = 0; col < width; col++) {
slideData[row][col] = (char)readSlide.read();
}
readSlide.readLine(); //read past end-of-line
}
readSlide.close();
in.close();
} catch (FileNotFoundException e) {
System.out.println("File does not exist or could not
be found.");
System.err.println("FileNotFoundException: "
+ e.getMessage());
} catch (IOException e) {
System.out.println("Problem reading file.");
System.err.println("IOException: " + e.getMessage());
}
}
/**
* Determines a colony size
* pre: none
* post: All colony cells adjoining and including
* cell (Row, Col) have been changed to NON _ COLONY,
* and count of these cells is returned.
*/
private int collectCells(int row, int col) {
/**
* Displays a slide.
* pre: none
* post: Slide data has been displayed.
*/
public void displaySlide() {
Algorithm Analysis
Algorithm analysis includes measuring how efficiently an algorithm
TIP Theoretical running times performs its task. A more efficient algorithm has a shorter running time.
can be writ ten in Big Oh Running time is related to the number of statements executed to implement
notation, which is a theoretical an algorithm. It can be estimated by calculating statement executions.
measure of an algorithm’s
Running time estimations are usually based on a worst-case set of data.
efficiency.
For example, an array that is already sorted or nearly sorted may require
fewer statement executions than an array of data that is in reverse sorted
order. Since the original state of the data is usually unknown, the worst
case should be assumed.
As a first analysis, consider the selection sort algorithm, which uses
nested for loops to sort items. If the sort is thought of in simplified terms,
with each for statement containing a single statement, for an array of n
items, n * n statements are executed. The selection sort is therefore said
to have a running time of n2.
Chapter Summary
Sorting is the process of putting items in a designated order, either from
low to high or high to low. The selection sort, insertion sort, and mergesort
algorithms were presented in this chapter. The merge sort algorithm takes
a divide-and-conquer approach to sorting. It is implemented recursively
and is much faster than the selection and insertion sorts.
Objects cannot be compared with relational operators. Therefore, lists of
objects are sorted by implementing an algorithm that uses the Comparable
interface. Interfaces can be used as data types, which allows a generic
implementation of an algorithm that sorts objects. Objects that are to be
sorted must have a class that implements the Comparable interface.
A method can call itself in a process called recursion. Recursion is a
programming technique that can be used whenever a problem can be
solved by solving one or more smaller versions of the same problem and
combining the results. To prevent infinite recursion, a base case that
requires no recursion must be part of the recursive solution.
A binary search algorithm can be used to find an element in a sorted
array. Binary search is implemented recursively and is very efficient. The
depth-first searching algorithm can be used to search through a series
of possibilities. When implementing depth-first searching, code must be
included to avoid infinite recursion.
Algorithm analysis includes how efficiently an algorithm performs its
task. A more efficient algorithm has a shorter running time.
Binary search A searching algorithm that recursively Insertion sort A sorting algorithm that repeat-
checks the middle of a sorted list for the item being edly inserts an item into the appropriate position
searched for. of a subarray until the subarray has no items left
to insert.
Base case The part of a recursive solution that
requires no recursion. Recursion The process in which a method calls
itself. A programming technique that can be used
Depth-first search A searching algorithm that
whenever a problem can be solved by solving one
recursively checks a starting position, processes that
or more smaller versions of the same problem and
position, and then searches adjacent positions.
combining the results.
Infinite recursion A recursive solution which has
Recursive call A call to a method from within the
no base case.
same method.
Mergesort A sorting algorithm that recursively
Selection sort A sorting algorithm that repeatedly
divides a list into halves, sorting those halves,
selects the lowest item in a subarray of an array and
and then merging the lists so that the items are in
moves it to the position just before the subarray until
order.
the subarray has no items left to search.
Java
1. For the list 4, 6, 2, 10, 9, show how the numbers 5. Use the recursive method below to answer the
are ordered after each loop iteration of the questions:
algorithms: public void ct(int n) {
a) selection sort if (n > 0) {
b) insertion sort ct(n/10);
System.out.println(n % 10);
2. What must be done to a list of items in order to }
}
use a binary search to find a specific item?
a) What output is generated when ct (13) is
3. Use the recursive method below to answer the called?
questions: b) What output is generated when ct(124) is
public void ct(int n) { called?
System.out.println("Starting " + n); c) What output is generated when ct(21785) is
if (n > 0) { called?
ct(n/3); d) What in general does this method do?
System.out.println("Middle " + n);
}
}
6. Use the recursive method below to answer the
questions:
a) What output is generated when ct(13) is
public void whatzItDo() {
called? Scanner input = new Scanner(System.in);
b) What output is generated when ct(3) is String letter = input.next();
called? if (!letter.equals(".")) {
c) What output is generated when ct(0) is whatzItDo();
called? System.out.print(letter);
}
}
4. Use the recursive method below to answer the
questions: a) What output is generated when the user
public void ct(int n) {
enters T, E, S, T, . ?
System.out.println(n); b) What in general does this method do?
if (n > 0) {
if (n % 2 == 1) { 7. A sorting algorithm is said to be “stable” if two
ct(n/3); items in the original array that have the same
} else { “key value” (the value to be sorted on) maintain
ct(n/2);
}
their relative position in the sorted version. For
} example, assume an array with the following
} data:
Ann Jon Mel Tom Kim
a) What output is generated when ct (13) is
20 19 18 19 22
called?
b) What output is generated when ct(14) is When the array is sorted by age, a stable sort
called? would guarantee that Jon would stay ahead of
c) What output is generated when ct(15) is Tom in the sorted array, as in:
called? Kim Ann Jon Tom Mel
22 20 19 19 18
and not:
Kim Ann Tom Jon Mel
22 20 19 19 18
Which of the sorts presented in this chapter
(selection, mergesort) is stable? For each which
is not stable, give an example of data to illustrate
this.
The digits 1 through 9 represent various colors. The digit 0 represents black (background color).
The DetectColonies2 application should display a listing of the size, location, and color value of each
colony on the slide. A colony is defined as a connected (horizontally or vertically) sequence of cells
holding the same color value. For the above slide, the application should report:
Color Size Location
5 3 1, 3
5 2 3, 5
1 5 4, 2
2 1 4, 3
3 1 6, 7
The fillKnapsack algorithm determines if the goal can be found in all of the items not including the
first, or if it can be found by including the first in the subset. The pseudocode is:
if (simple case) {
handle simple cases
} else {
if (fillKnapsack(weights, goal, start+1)) {
return(true);
} else if (fillKnapsack(weights, goal-weights[start], start+1)) {
return(true);
} else {
return(false);
}
}
Note that the simple cases will need to be determined and handled properly.
The starting point is assumed to be location (1, 1) and the maze is assumed to have a border. Create a
Maze application that displays the sequence of positions in a path from the start to the goal, or indicate
if no path is available. For example, for the maze above, the application should report:
Path: (6,8) (6,7) (6,6) (5,6) (4,6) (3,6)
(2,6) (1,6) (1,5) (1,4) (1,3) (1,2) (1,1)
contains the words WAS, WAXY, JOB, and others, but not the word BOX. Words can contain duplicate
letters, but a single letter on the board may not appear twice in a single word, for example POP is not
contained on this board.
Create a MyBoggle application that displays a board of random letters, and allows the user to enter
words found on the board. The application should report if the word entered by the user is indeed on
the board.
Hint: Search the board for the first letter of the word entered, and then recursively search around the
found letter for the remaining letters of the word.
There are two standard operations that can be performed on the items
pop in a stack, and only the top item of a stack can be processed. The pop
operation removes the top item. For example, when a pop is executed on
the stack above, the top value, 11, is removed:
The next item, 34, is now at the top of the stack, and is the only item that
can be accessed.
push Another operation is the push operation, which adds an item to the top
of the stack. For example, if the value 27 is pushed onto the stack, the stack
becomes:
The Stack class below is a very simple stack implementation that stores
data in an array:
public class Stack {
private int[] data;
private int top;
/**
* constructor
* pre: none
* post: An empty stack that can hold up to maxItems
* has been created.
*/
public Stack(int maxItems) {
data = new int[maxItems];
top = -1; //no items in the array
}
/**
* Returns the top item without removing it from the stack.
* pre: Stack contains at least one item.
* post: The top item has been returned while leaving it
* on the stack.
*/
public int top() {
return(data[top]);
}
/**
* Removes the top item from the stack and returns it.
* pre: Stack contains at least one item.
* post: The top item of the stack has been removed
* and returned.
*/
public int pop() {
top -= 1;
return(data[top + 1]);
}
/**
* Determines if there are items on the stack.
* pre: none
* post: true returned if there are items on the stack,
* false returned otherwise.
*/
public boolean isEmpty() {
if (top == -1) {
return(true);
} else {
return(false);
}
}
/**
* Returns the number of items in the stack.
* pre: none
* post: The number of items in the stack is returned.
*/
public int size() {
if (isEmpty()) {
return(0);
} else {
return(top + 1);
}
}
/**
* Empties the stack.
* pre: none
* post: There are no items in the stack.
*/
public void makeEmpty() {
top = -1;
}
}
The Stack class implements a stack for int values. A generic implemen-
tation would use objects. This implementation is completed in the Stack2
review.
Review: Stack2
Create a Stack2 class that implements a stack data structure for data type Object. Since Object is the super-
class of other objects, a Stack2 object can store objects from any class. Write appropriate client code to test
the Stack2 class.
All insertions are made at the rear and all removals are made at the
front.
There are two standard operations that can be performed on a queue.
dequeue The dequeue operation removes an item from the front. For example, when
a dequeue is executed on the queue above, the value at the front, 12, is
removed from the queue:
enqueue The enqueue operation adds an item to the rear of the queue. For example,
if the value 27 is enqueued, the queue becomes:
Other queue operations include the front operation, which returns the
front item without removing it from the queue. The isEmpty query returns
true when there are no items in the queue, and false otherwise. The size
operation determines the number of items in a queue. A queue can be
emptied with the makeEmpty operation.
A queue is analogous to a line at a ticket counter where “first come,
FIFO first served,” and is sometimes referred to as a first in first out (FIFO) data
structure. There are a number of real-world situations that can be repre-
sented as a queue structure. For example:
do {
System.out.print("Add/Remove/Count/Front/Quit: ");
choice = input.next();
if (choice.equalsIgnoreCase("a")) {
if (q.size() < MAX _ ITEMS) {
System.out.print("Number to add: ");
num = input.nextInt();
q.enqueue(num);
} else {
System.out.println("Queue is full.");
}
} else if (choice.equalsIgnoreCase("r")) {
System.out.println("Dequeueing: " + q.dequeue());
} else if (choice.equalsIgnoreCase("c")) {
System.out.println("Items in queue: " + q.size());
} else if (choice.equalsIgnoreCase("f")) {
System.out.println("Front of queue: " + q.front());
} else {
System.out.println("quitting");
}
} while (!choice.equalsIgnoreCase("q"));
}
The Queue class on the next two pages is a very simple queue imple-
mentation that stores data in an array:
/**
* constructor
* pre: none
* post: An empty queue that can hold up to maxItems
* has been created.
*/
public Queue(int maxItems) {
data = new int[maxItems];
front = -1; //no items in the array
rear = -1;
maxSize = maxItems;
}
/**
* Returns the front item without removing it from
* the queue.
* pre: Queue contains at least one item.
* post: The front item has been returned while leaving
* it in the queue.
*/
public int front() {
return(data[front]);
}
/**
* Removes the front item from the queue and returns it.
* pre: Queue contains at least one item.
* post: The front item of the queue has been removed
* and returned.
*/
public int dequeue() {
int num;
/**
* Adds an item to the queue if there is room.
* pre: none
* post: A new item has been added to the queue.
*/
public void enqueue(int num) {
if (isEmpty()) { //first item queued
rear = 0;
front = 0;
data[rear] = num;
} else {
rear = (rear + 1) % maxSize;
data[rear] = num;
}
}
/**
* Returns the number of items in the queue.
* pre: none
* post: The number of items in the queue is returned.
*/
public int size() {
if (isEmpty()) {
return(0);
} else { //front item is "in front" of rear item
if (rear > front) {
return(rear - front + 1);
} else if (front == rear + 1) { //queue is full
return(maxSize);
} else { //front item is "behind" rear item
return(front - rear + 1);
}
}
}
/**
* Empties the queue.
* pre: none
* post: There are no items in the queue.
*/
public void makeEmpty() {
front = -1;
rear = -1;
}
}
Because the queue is limited to the number of items it can store, the
front and rear pointers must cycle through the spots available in the
array. Therefore, the front and rear values are calculated using modular
arithmetic (%).
The Queue class implements a queue for int values. A generic imple-
mentation would use objects. This implementation is left as a review.
Review: Queue2
Create a Queue2 class that implements a queue data structure for data type Object. Since Object is the super-
class of other objects, a Queue2 object can store objects from any class. Write appropriate client code to test
the Object2 class.
head, tail The first item in a linked list is called the head. The last item points to
node null and is called the tail. Each element of a linked list is called a node.
There are three nodes in the list above.
TIP Objects stored in memory
are stored in dynamic memory. Because each item in a linked list must contain data and a pointer, an
Dynamic memory is allocated item is best modeled with a class. Therefore, a linked list is a list of objects.
from an area called the heap, The objects in a linked list are organized because they point to each other.
which is used during program There is no need to place them in a structure, such as an array, for orga-
execution. nization. This mean that linked links are not restricted by the size of an
array.
There are two standard operations that can be performed on a linked
addAtFront list. The addAtFront operation adds a new node to the front of the list. When
a new node is added to the front of a linked list, it is simply designated
the head and its pointer is set to the current head. For example, if Raj was
the head, adding a new item means that the new object is now the head
and its pointer points to the Raj object:
remove The remove operation removes an item from the linked list. Removing
an item from a linked list means that the pointer of the previous item is
changed to point to the item after the one to be removed. For example,
removing Raj from the list below means that the object is no longer refer-
enced by another object in the list:
Linked lists are useful for maintaining dynamic lists because the num-
ber of items in a linked list can shrink and grow as needed.
list.addAtFront("Sachar");
list.addAtFront("Osborne");
list.addAtFront("Suess");
System.out.println(list);
list.remove("Suess");
list.remove("Sachar");
list.remove("Osborne");
System.out.println(list);
}
}
nested class The LinkedList class below contains a nested class. A nested class is a
class within a class. A nested class is a member of the class it is within. As
a class member, it has access to all the other members of the class, includ-
ing private member variables and methods. A class that contains a class
outer class member is called an outer class. The Node class is a nested class because
its members should only be accessed by a LinkedList object:
public class LinkedList {
private Node head;
/**
* constructor
* pre: none
* post: A linked list with a null item has been created.
*/
public LinkedList() {
head = null;
}
/**
* Adds a node to the linked list.
* pre: none
* post: The linked list has a new node at the head.
*/
public void addAtFront(String str) {
Node newNode = new Node(str);
newNode.setNext(head);
head = newNode;
}
if (current.getData().equals(str)) {
head = current.getNext();
} else {
while (current.getNext() != null) {
previous = current;
current = current.getNext();
if (current.getData().equals(str)) {
previous.setNext(current.getNext());
}
}
}
}
/**
* Creates a string that lists the nodes of the
* linked list.
* pre: none
* post: The linked list has been written to a string.
*/
public String toString() {
Node current = head;
String listString;
if (current != null) {
listString = current.getData() + "\n";
while (current.getNext() != null) {
current = current.getNext();
listString += current.getData() + "\n";
}
return(listString);
} else {
return("There are no items in list.");
}
}
/**
* constructor
* pre: none
* post: A node has been created.
*/
public Node(String newData) {
data = newData;
next = null;
}
/**
* The node pointed to by next is changed to newNode
* pre: none
* post: next points to newNode.
*/
public void setNext(Node newNode) {
next = newNode;
}
/**
* The node pointed to by next is returned
* pre: none
* post: A node has been returned.
*/
public String getData() {
return(data);
}
}
}
Vocabulary
addAtFront A linked list operation where an item Pop A stack operation where the top item is
is added to the front of the list. removed.
Dequeue A queue operation that removes the item Push A stack operation where a new item is
at the front of the queue. added.
Enqueue A queue operation that adds an item to Queue A data structure that has a front and rear
the rear of the queue. and organizes data so that the first item in is the
first item out.
FIFO First In First Out. A queue data structure.
Rear The end of a queue.
Front The start of a queue.
Remove A linked list operation where an item is
Head The first node in a linked list. removed from the list.
isEmpty A stack or queue operation that returns Size A stack or queue operation that returns the
true when there are no items in the data structure number of items in the data structure.
and false otherwise.
Stack A data structure that has a top and organizes
LIFO Last In First Out. A stack data structure. data so that the last item in is the first item out.
Linked list A data structure that has a head and Tail The last node in a linked list. The tail points
tail and contains nodes that point to each other. to null.
Nested class A class that is a member of another Top The last item pushed onto a stack.
class. A class within a class.
Node A linked list element. A node contains the
item and a pointer to the next node.
Outer class A class that contains a class member.
a) Create a ParenChecker application that prompts the user to enter an expression with
parentheses, and then displays a list of the positions of pairs of parentheses. The
application should store the positions of the left parentheses on a stack when they are
found. Application output should look similar to:
b) Modify the ParenChecker application to detect the two errors below and display
appropriate error messages:
1. Attempt to pop an empty stack.
2. Stack not empty at the end of the program.
&ILE 6IEW
WINDOW CODE EDITOR WINDOW
0ACKAGE 6IEW
WINDOW
• The File View window displays the folders and files associated
with the project workspace.
TIP Commands in the View
menu are used to display • The Package View window displays the classes associated with
and hide the JCreator IDE the project workspace.
windows.
• The code editor window is used to type and edit Java and HTML
code.
• The Output windows display Java program output, build errors,
a task list, and debug output.
Review: Welcome
! START JCREATOR
! START JCREATOR
Select File j Close Workspace if an existing project is displayed when the IDE is
started.
c. Select Next.
d. In the Name box, type Message:
Errors
The JCreator compiler will display any errors in the Task View window
when the program is compiled:
@ PRINT MESSAGE
a. In the File View window, double-click Message.java.
b. Click the code editor window.
c. Select File j Print.
$ QUIT JCREATOR
Help Features
JCreator has several help features that can be accessed in the Help menu.
The Help Contents and JDK Help commands access a database of help topics
that can be searched and the JCreator on the Web command provides links
to technical support information on the JCreator Web site.
Index 393
ArrayList, data structure analysis bus 2, 7 close(), BufferedReader class 312
250 bus topology 7 close(), BufferedWriter class 316
ArrayList class 250 button, Swing API 276 close(), FileInputStream class 318
array element 237 for displaying an image 290 close(), FileOutputStream class 317
accessing 238 byte 9, 79 close(), FileReader class 312
assigning a new value 238 bytecode 62 close(), FileWriter class 315
artificial intelligence 5 converting to machine code 62 close(), ObjectInputStream class
ASCII 10 Byte class 251 319
asin(), Math class 129 close(), ObjectOutputStream class
Ask Jeeves 16 C 318
assembly language 5 C 5 coaxial cable 7
assignment 78, 86 C++ 6, 62 COBOL 5
array element 238 cable modem 14 code convention
constant 87 cache 2 variable identifier 77
variable 78 calling a method 159 code conventions 65
atan(), Math class 129 CAN-SPAM Act 16 collection 250
attributes 46 carpal tunnel syndrome 20 collections framework 250
auto-unboxing 253 carriage return character 312 colors, Swing API 289
autoboxing 253 case clause 108 combo box, Swing API 286
auxiliary storage 12 case sensitivity, identifiers 88 comments 46, 61, 62
awt 278 casting, see type casting 85 block 62
CD-R 12 documentation 62, 164
B CD-RW/DVD drive 1 for debugging 137
backslash character in a string 63 cellular radio 7 inline 107
backslash for escape sequence 63 Central Processing Unit 2 method 164
backup copy 21 chaos theory 154 multiline 62
backup tools 4 char 79, 242 postcondition documentation
bahavior of an object 179 array 242 164
bandwidth 7 Character class 251 precondition documentation
base 10 logarithm 127 charAt(), String class 242 164
base class 212 char array, initializing 243 single line 62
Basic 5 Children’s Online Privacy Communications Privacy Act of
Big Oh notation 244, 250, 356 Protection Act of 1998 19 1986 22
binary files 11 cipher text 19 communications satellites 7
binary number system 9 circuit boards 1 Comparable interface 223, 339
binary search 152, 349 citation 17 compareTo(), Comparable interface
binary search algorithm analysis citations 18 223
357 class 60 compareTo(), Double class 252
BIOS 2 abstract 220 compareTo(), Integer class 251
bit 9 base 212 compareTo(), String class 140
blog 15 body 180 compareTo(), when sorting 339
Bluetooth 4 constructor 182 compareToIgnoreCase(), String
boolean 79, 106 declaration 180 class 140
Boolean class 251 derived 212 compiler 5, 62
Boolean expression 17, 105, 131 designing 180 just-in-time 62
evaluation 112 extending 211 method overloading 162
border, Swing API 279 inner 188, 293 compiling source code 62
boundary value 168 naming 181 compound interest 103
BoxLayout manager, Swing API 280 nested 188, 293, 374 compression program 11
breadth-first-searching 370 outer 293, 374 computers
breakpoint 136 variables 180, 184 desktop 1
break statement 108 wrapper 251 handhelds 5
broadcast radio 7 writing 180 notebook 4
buffer 312 class, objects to be written to a file wearable 5
BufferedReader(), BufferedReader 320 wrist-top 5
class 312 ClassCastException 186 computer vision syndrome 20
BufferedReader class 312 classes using classes 187 concatenation 138
BufferedWriter(), BufferedWriter ClassNotFoundException 320 toString() 187
class 316 class method 159, 184 conditional control structure 105,
BufferedWriter class 315, 316 client/server network 7 108
bug 136 client code 180 constant 87
built-in data types 79 close() 81
394 Index
constructor 180, 183 depth-first searching 352 encapsulation 59, 179, 182
subclass 213 dequeue, queue 369 encryption 19
writing 183 derived class 212 endsWith(), String class 140
container, Swing 273 desktop computer 1 end of file 312
content frame, Swing 273 device driver 4 enqueue, queue 369
controlling class 61 digital camera 1 environment 3
Swing application 276 digital signature 15 distributed 3
control bus 2 Digital Subscriber Line 14 multiprocessing 3
conventional modem 14 disk defragmentation 4 multitasking 3
conversion, numeric 84 disk drive 1 multiuser 3
cookie 18 divide-and-conquer 152, 345, 349 environmental concerns 20
copyright 21 division 83 equals() 186
copyright infringement 21 integer 83 equals(), String class 140
cos(), Math class 129 modulus 83 equals(), use by ArrayList 250
counter 133 real 83 equals() versus == 186
counting values 133 type casting 85 equalsIgnoreCase(), String class
CPU 2 do-while 131 140
crackers 21 documentation equal sign 78
createNewFile(), File class 309 comments 62 ergonomics 20
cross-platform connectivity 5 external 62 error 62, 89
package 80 exception handling 310
D postcondition comments 164 logic 89
data precondition comments 164 run time 89, 238
boundary values 168 documentation comments 164 semantic 89
passing to a method 160 Double 252 syntax 62, 88, 132
processing 81 double 79 err stream 311
processing from a file 314 doubleValue(), Double class 252 escape sequence 63, 310
reading from a file 312 Double class 283 Ethernet 7
reading objects from a file 317 downloading 17 ethical implications of computer
testing a method 168 DSL 14 use 19
writing objects to a file 317 DVD drive 13 ethical responsibilities, IT
writing to a file 315 dynamic array 250 professional 22
data structure dynamic lists 373 ethical responsibilities of an IT
array 237 dynamic memory 373 professional 22
ArrayList 250 ethical use of computers 19
data structures 365 E Euclid’s Algorithm 153
linked list 373 e, natural logarithm 127 Eudora 15
queue 369 E-FOIA 19 event 273
stack 365 e-mail 15 event-driven application 273
data structure analysis address 15 event handler 273
ArrayList 250 attachments 21 exabyte 13
data type 77 corporate 16 exception 81, 89, 310
abstract 80 ethics 16 array 238
interface 339 etiquette 16 handling 89
primitive 79 law prohibiting spam 16 exception handler 310
debugger 136 school 16 Excite 16
debugging 136 e-mail server 16 execution
commenting out statements 137 EBCDIC 10 program 62
debugger 136 ECPA 19 exists(), File class 309
variable trace 136 Electronic Communications Privacy exp(), Math class 127
with println() 137 Act of 1986 19, 21 expansion boards 1
Debug Window 136 Electronic Freedom of Information expectations vii
decision structure 105, 108 Act of 1996 19 exponent 10
declaration electronic mail 15 exponentiation 113
array 237 element extends keyword 212
class 180, 212 array 237 extension 11
method 159 ArrayList 250 extranet 13
two-dimensional array 246 ArrayList, adding 250
variable 77 ArrayList, finding 250 F
decrement operator 135 ArrayList, removing 250 factorial 136
Default package name 61 employee monitoring 20 Fair Credit Reporting Act of 1970
delete(), File class 309 20
Index 395
false 79 DiceRolls 240 lists 46
fiber optic cable 7 Dice Roll 208 style sheets 49
file 11, 309 Game of 21 209 tables 47
creating 315 GuessingGame 125, 151, 178 tags 36
HTML 37, 333 Life 270, 335 text color 50
processing numeric data 314 Mad-Lib story 332 validating 37
reading 312 Mankala 271 HTML 4 45
stream 311 Mastermind 267 hub 8
writing to 315 Maze 363 hyperlink 48
File(), File class 309 MyBoggle 364 hypertext 35
FileInputStream(), FileInputStream Nim 209 HyperText Markup Language 35
class 318 Penny Pitch 270
FileInputStream class 317, 318 Rock Paper Scissors 114, 196 I
FileNotFoundException 313, 320 TicTacToe 246 identifier 77
FileOutputStream(), WordGuess 141, 334 choosing 88
FileOutputStream class 317 generics 250 identity theft 20
FileOutputStream class 317 get(), ArrayList 250 if-else if statement 107
FileReader(), FileReader class 312 getActionCommand(), JButton 276 if-else statement 106
FileReader class 312 getContentPane(), JFrame 274 nested 107
files getMessage(), Throwable class 311 if statement 105
organizing 181 getSelectedItem(), JComboBox 286 IllegalArgumentException 161
FileWriter(), FileWriter class 315 getText(), JTextField 283 IM 15
FileWriter class 315 GIF 48, 290 IMAP server 16
File class 309 gigabytes 10 immutable 139
file position 311 gigahertz 2 import, package 60
file size 11 Google 16 import statement 81
final 87 graphical user interface 3, 273 increment operator 135
Financial Privacy Act of 1978 20 greatest common divisor 153 index 138
Firefox 35 GridLayout manager, Swing API index, array element 237
firewall 13 280, 282 indexOf(), ArrayList 250
FireWire port 12 GUI 3, 273 indexOf(), String class 140
flag 134 Gutenburg, Johann 59 infinite loop 132
float 79 Gutenburg Press 59 infinite recursion 344
floating point 79 information age 19
floating point numbers 10 H information hiding 179, 182
Float class 251 hackers 21 infrared signals 7
flowchart 66 hailstone numbers 154 inherit 186
flowchart symbols 67 HAN 6 inheritance 59, 211
FlowLayout manager, Swing API handheld computers 5 initializing an array 238
279 handwriting recognition software initializing an object 80
folders 11 4 ink jet printer 1
format() method 64 hard-coded data 241 inline comments 107
formatting output 64 hardware 1 inner class 188, 293
Fortran 5 has-a relationship 187 input, getting from user 81
for statement 135, 238 head, linked list 373 input, getting from user in a GUI
array traversal 239 heading tags 46 283
ArrayList traversal 239 heap 373 InputMismatchException 81, 89, 95
nested 246 helper method 182 input devices 1
for-each statement 239, 251 hexadecimal 9, 50 input file stream 312
frame, Swing 273 histogram 267 input stream 81
front, queue 369 Home Area Network 6 input validation loop 149
functional decomposition 180 horizontal rule tag 46 insertion sort 341
Fundamental Theorem of HTML 35, 333 insertion sort algorithm analysis
Arithmetic 150 alignment 51 357
attributes 46 instance 179
G background color 50 instance methods 184
game comments 46 instance variables 184
Adder 210, 334 documents 36, 37 instantiation 80
BirthdayGame 90 document tags 37 instant messaging 15
Bowling 210 elements 36 int 79
Break-A-Plate 296 hyperlinks 47 Integer 251
Carnival 191 images 47 Integer class 283
396 Index
integrated circuits 2 javax.swing.JTextField 283 link 48
Integrated Services Digital Network Java 2 59 linked list 373
14 Java 2 Platform Standard Edition 61 Linux 2
Intel 2 Java applets 41 list, linked 373
interface 223 adding color 43 listener, Swing API 277
as data type 339 drawing shapes 43 LISTSERV 16
Comparable 339 parameters 44 Local-Area Network 6
console 273 placing in an HTML document local scope 160
graphical 273 44 log(), Math class 127
implementing 223 Java application 61 log10(), Math class 127
implementing multiple 225 Java Application Programming logical operators 17
text-based 273 Interface 60 logical topology 8
interface, as variable type 339 Java Foundation Classes 273 logic error 89, 132
interface, object 181 Java platform 59 logistic equation 154
Internet 13 Java Virtual Machine 41, 62 long 79
history of 13 Jaz drives 12 Long class 251
Internet Acceptable Use Policy 19 JButton(), JButton class 276, 291 loop, controlling iterations 134
Internet Explorer 15, 35 JButton class 291 loop control variable 135
Internet filtering software 19 JComboBox(), JComboBox 286 loop structure 131
Internet privacy issues 18 JComboBox class 286 lowercase, converting strings 138
Internet services 15 JCreator 41, 383
Internet Service Provider 14 JDK 80, 191 M
Internet Use Agreement 19 JFrame class 274 Mac 1
interpolation search 361 JIT 62 machine code 62
interpreter 6 JLabel(), JLabel class 275 machine language 5
Java VM 62 JLabel class 274 Mac OSX Tiger 273
interpreting bytecode 62 JPanel class 274 Mac OS X Tiger 2
intranet 13 JPG 48, 290 magnetic technology 13
intValue(), Integer class 251 JRE 42, 80 mailing list server 16
IOException 320 JTextField 283 main() method 61, 62, 157
IP address 18 JTextField(), JTextField class 283 mainframe 3
is-a relationship 211 just-in-time compiler 62 main memory 2
ISDN 14 Majordomo 16
isEmpty(), String class 138 K makeEmpty, queue 369
isEmpty, queue 369 K 11 malicious code 21
isEmpty, stack 366 Kbps 14 MAN 6
IT 22 keyboard 1, 81 mantissa 11
Itanium 2 keyword 88 Mastermind 267
iteration 131 keywords 17 Math class 113, 127, 128, 129
IT Careers 22 kilobytes 11 maze 363
knapsack problem 362 Mbps 14
J median, determining 267
J2SE Runtime Environment 80 L megabytes 10
Java 6 label, Swing API 274 megahertz 2
enabling 41 for displaying an image 290 member, accessing 80
java.awt 282, 289 LAN 6 members, class 180
java.awt.event 278 laser printer 1 memory, dynamic 373
java.io 309, 312, 315, 317 lastIndexOf(), String class 140 memory-resident 4
java.lang 63, 79, 80, 113, 223, 252 layout, Swing API 279 memory keys 1
java.lang.Double 252, 283, 314 layout manager, Swing API 279 mergesort 345
java.lang.Integer 251, 283, 314 leased/dedicated lines 14 mergesort algorithm analysis 357
java.lang.Math 109, 113, 127 length(), String class 138 message, passing 193
java.lang.Object 186 length, array 238 method 157
java.text 86 library 60 abstract 220
java.util 80 Life 270 accessor 182
java.util.ArrayList 250 with GUI 307 array parameter 239
java.util.Random 138 Linear Congruential Method 109 body 159
java.util.Scanner 81, 138, 140, 242 linear search 244, 349 calling 159
JavaScript 38, 40 linear search, algorithm analysis class 159, 184
javax.swing 273 244 declaration 159, 162
javax.swing.Frame 274, 275, 276, 290 line feed character 312 documentation 164
javax.swing.JPanel 274 line terminator 312 helper 182
Index 397
instance 184 nextBoolean(), Scanner class 81 overloading, methods 162
modifier 182 nextDouble(), Scanner class 81 overriding
naming 160 nextInt(), Scanner class 81 methods 212
overloading 162 node 7 overriding a method 186
overriding 186 node, linked list 373 overwriting a file 315
parameters 160 NOT 17
returning a value 163 Not 112 P
testing 167 notebook computer 4 pack(), JFrame 274
test data 168 No Electronic Theft Act of 1997 21 package 60
writing 159 null 139, 238 documentation 80
methods NullPointerException 139 naming 61, 81
behavior of object 179 number package statement 61
Metropolitan Area Network 6 converting type 84 paradigm
microphone 1 whole 77 object-oriented 211
Microsoft Internet Explorer 15 number systems 9 parallel processing 3
Microsoft Windows 273 numeric expression 83 parameter
microwaves 7 array, two-dimensional 246
MLA 17 O Object 186
MLA Handbook for Writers of object 59, 80, 179 parameters 44
Research Papers, Sixth Edition argument 161 array 239
17 object, to be written to a file 320 constructor 183
mobile computing devices 4 object-oriented development 191 method 160
modem 14 object-oriented programming 6, 59 pass by value 161
moderator ObjectInputStream 317 parentheses 84
list serve 16 ObjectInputStream(), parseDouble(), Double class 283,
modifier method 182 ObjectInputStream class 318 314
modular 193 ObjectInputStream class 318 parseInteger(), Integer class 283,
modulus division 83 ObjectOutputStream 317 314
monitor 1 ObjectOutputStream(), Pascal 5
motherboard 1 ObjectOutputStream class 318 passing an array 240
mouse 1 ObjectOutputStream class 318 passing data to a method 160
Mozilla Firefox 15 objects, sorting 339 pass by value 161
MP3 players 5 Object class 185, 211 PC 1
MSN 16 object deserialization 317 PDAs 5
multimedia 36 Object parameter 186 peer-to-peer network 7
multiplication 83 object serialization 317 Pentium 2
multiprocessing 3 offset array index 241 peripheral devices 1
multitasking 3 online profiling 18 persistent data 309
multithreading 3 OOP 6, 59 persistent media 11
multiuser OS 3 Opera 35 petabyte 13
Mylar 12 operand 83 phishing 22
operating systems 2, 59 PI, Math class 113
N operations, order of 84 piracy 21
native format 11 operator 83 pixel 279
natural logarithm 127 relational 105 pixels 42
necklace problem 153 operators, built-in 83 pixel tags 18
nested class 188, 293, 374 operator precedence 84 platform 3, 59
nested statements 107 Opteron™ 2 platform-dependent languages 62
netiquette 9 optical technology 12 platform independence 59, 62
Netscape 35 OR 17 PNG 48
networked environment 7 Or 111 polymorphism 59, 215
networks 6 evaluation 112 polymorphism, interfaces 339
benefits 6 order of operations 112 pop, stack 365
size classifications 6 out 63 POP3 server 16
network architecture 7 outer class 293, 374 ports 1
network interface card 6 Outlook 15 Bluetooth 1
network operating system 7 output, formatting 64 FireWire 1
NET Act 19 output devices 1 parallel 1
new 80, 237, 246 output file stream 315 serial 1
newLine(), BufferedWriter class 316 output stream 63 USB 1
newline character 63 overflow 132 post 164
next(), Scanner class 81 overflow error 10
398 Index
postcondition, method readInt(), ObjectInputStream class searching an array 244
documentation 164 318 Search class 244
postfix 135 readLine(), BufferedReader class search criteria 17
pow(), Math class 113 312 specifying 17
pre 164 readObject(), ObjectInputStream search engine 16
precondition, method class 318 secondary memory 2
documentation 164 Read Only Memory 2 selection sort 269, 337
prefix 135 real-time clock 2 selection sort algorithm analysis
primary memory 2 real-time OS 3 356
prime factors 150 real numbers 10 semantic error 89
prime number 150 rear, queue 369 semicolon 62
primitive data type 79 recursion 343 sentinel 134
argument 161 recursive algorithm, binary search sequential file access 311
primitve data type 349 sequential search 349
array element 240 recursive algorithm, depth-first Serializable interface 320
print() method 63 search 352 server 7
printer 1 recursive algorithm, mergesort 345 setActionCommand(), JButton 276
println() recycling 20 setBackground(), Swing API 289
debugging 137 reference data type setContentPane(), JFrame 274
toString() 187 array 240 setDefaultCloseOperation(), JFrame
println() method 63 interface 339 274
privacy 20 object 80 setDefaultLookAndFeelDecorated()
Privacy Act of 1974 20 object parameters 161 JFrame 274
privacy policy 18 polymorphism 215 setEditable(), JComboBox 286
private keyword 182, 213 String 139 setForeground(), Swing API 289
procedural abstraction 157 relational operator 105 setIcon(), JButton class 291
programming language remove(), ArrayList 250 setSelectedIndex(), JComboBox 286
first generation 5 remove(), JPanel 274 setText(), JLabel 275
second generation 5 remove, linked list 373 setVisible(), JFrame 274
program specification 59 replaceAll(), String class 138 short 79
modeling 211 replaceFirst(), String class 138 short-circuit evaluation 112
program specification, modeling reserved words 88 Short class 251
191 return statement 163 significand 10
prompt 82 reusability 60 sign bit 10
prompt, in a GUI 283 code 191 simple interest 103
pseudocode 66 ring topology 8 sin(), Math class 129
pseudorandom 109 ROM 2 size(), ArrayList 250
public 159 rounding 84 size, queue 369
public keyword 159 rounding double to int 85 size, stack 366
public static void main(String[] roundoff error 11, 105 smartphones 5
args) 61 router 8, 14 SMTP server 16
push, stack 365 run-time error 89 social implications of computer
array 238 use 19
Q running a program 62 software development 157, 191
queue 369 running time 356 solid state technology 13
quotation mark 63 sorting, numbers 337
in a string 63 S sorting objects 339
quotient 83 Safari 35 sorts 337
Safety and Freedom through sound cards 1
R Encryption Act of 1999 19 source code 62
RAM 2 scanner 1 spam 16
random() 109 Scanner object, closing 82 spec 59
Random Access Memory 2 scope 135 spyware 18
random numbers 109 scope, local in a method 160 SQL 5
random walk 155 scripts 38, 40 sqrt(), Math class 113
range, determining 267 search, binary 349 square root 113
read(), BufferedReader class 312 search, depth-first 352 SRAM 2
readDouble(), ObjectInputStream search, interpolation 361 stack 365
class 319 search, linear 349 startsWith(), String class 140
reading numeric and string data 82 search, sequential 349 star topology 8
reading objects 317 search, ternary 361 statement 61
Index 399
state of an object 179 top-down design 157 Watch window 136
static 159 top-down development 157 wearable computers 5
static method 184 topology 7 Web 15
Static Random Access Memory 2 toRadians(), Math class 129 Web site 35
static variables 184 toString() 186 Web site citations 18
step-wise refinement 157 toString(), Double 283 Web Accessibility Initiative 44
Step command 136 toString(), Integer 283 Web beacons 18
storage, file 309 toUpperCase(), String class 138 Web browser 15
storage devices 12 transmission media 7 Web browsers 35
storage media traversing Web bugs 18
care of 13 array 238 Web server 36
stream 311 ArrayList 252 while 131
input 81 trim(), String class 138 whole number 77
string 63 Trojan horse 21 Wi-Fi 8
formatting 64 true 79 Wide-Area Network 6
strings 79 truncate Windows 2
comparing 140 modulus division 83 Windows media player 44
creating 138 toward 0 84 Windows XP environment 3
joining 138 truth table 111 WinZip 11
String class 79, 138 try-catch-finally statement 310 wireless access point 8
student expectations vii twisted-pair wiring 7 Wireless Fidelity 8
style sheets 49 two-dimensional array 245 wireless networks 8, 14
class 50 accessing elements 246 wireless transmission media 7
embedded 49 type casting 84, 243 words 10
linked 50 object 186 World Wide Web 15, 35
rules 50 World Wide Web Consortium 36
stylus 4 U worm 21
subclass 212, 215 ultra-portable devices 12 wrapper classes 251
subclasses 185 underscore (_) 87 wrapping values 253
substring(), String class 138 Unicode 10, 79, 242, 312, 381 wrist-top computers 5
subtraction 83 Unicode Standard 140 write(), BufferedWriter class 316
summing values 133 Unix 2 writeDouble(), ObjectOutputStream
superclass 185, 215 unwrapping values 253 class 318
Object class 211 uppercase, converting strings 138 writeInt(), ObjectOutputStream
supercomputer 3 USB 12 class 318
super keyword 213 utility program 4 writeObject(), ObjectOutputStream
Swing API 273 class 318
switch statement 108 V writing data to a file 317
syntax error 62, 88, 132 variable 77 WWW 35
System.in 81 class 180, 184 www.sun.com 80
System class 63 initializing in a class 183
system reliability 22 instance 184 Y
system restore 4 in println() 78 Yahoo! 16
member 181
T state of object 179 Z
tablet PC 4 variable trace 136 Zip drives 12
tab character 63 video adapters 1
tail, linked list 373 virtual 62
tan(), Math class 129 Virtual Machine 62
TCP/IP 14 virus 21
telecommunications 14 downloaded files 17
terabyte 13 visibility 159, 182
ternary search 361 subclasses 213
text field, GUI 283 Visual Basic 6, 62
this keyword 189, 277 visual organizer 66
thread 276 VM 62
Throwable class 311 void 159
Tim Berners-Lee 36
toCharArray(), String class 242 W
toDegrees(), Math class 129 W3C 36
toLowerCase(), String class 138 WAI 44
top, stack 365 WAN 6
400 Index
! 'UIDE TO 0ROGRAMMING IN *AVA 3ECOND %DITION EMPHASIZES THE DEVELOPMENT OF GOOD PROBLEM SOLVING
AND PROGRAMMING SKILLS IN A CLEAR EASY TO UNDERSTAND FORMAT CONTINUING THE TRADITION OF THE ,AWRENCEVILLE
0RESS SERIES OF PROGRAMMING TEXTS -ILLIONS OF STUDENTS HAVE LEARNED COMPUTING USING A ,AWRENCEVILLE 0RESS
TEXT ! 'UIDE TO 0ROGRAMMING IN *AVA 3ECOND %DITION HAS BEEN DEVELOPED FOR THE !0 #OMPUTER 3CIENCE
CURRICULUM WITH COMPLETE COVERAGE OF THE !0#3 ! *AVA 3UBSET AND AN INTRODUCTION TO SOME !" TOPICS 4HIS
TEXT IS AN EXCELLENT CHOICE FOR AN INTRODUCTORY PROGRAMMING COURSE
® 02/'2!--).' 4%#(.)15%3 3OLUTIONS ARE DESIGNED USING ALGORITHMS AND *AVA CODE
CONVENTIONS ARE MODELLED THROUGHOUT THE TEXT
® 4%!#().' !002/!#( 4HE TEXT IS WRITTEN FOR A VARIETY OF *AVA COMPILERS AND SUPPORTS *AVA 3%
AND *AVA 3% )T IS ALSO WRITTEN FOR DIFFERENT STUDENT LEARNING STYLES AND EFFECTIVELY USES SCREEN
SHOTS OF SOURCE CODE GENERATED OUTPUT AND lNISHED PROJECTS TO STRENGTHEN UNDERSTANDING
® 2%6)%73 !.$ %8%2#)3%3 !FTER A NEW CONCEPT IS DISCUSSED REVIEW PROBLEMS PROVIDE AN
OPPORTUNITY FOR STUDENTS TO APPLY THE CONCEPTS TO CREATING AN APPLICATION !T THE END OF EACH
CHAPTER ARE NUMEROUS HANDS ON EXERCISES OF VARYING DIFlCULTY APPROPRIATE FOR STUDENTS WITH A
WIDE RANGE OF ABILITIES
® #!3% 345$)%3 ! CASE STUDY IS PRESENTED AT THE END OF MOST CHAPTERS 4HE CASE STUDY ILLUSTRATES
A COMPLEX APPLICATION USING GOOD PROGRAMMING METHODOLOGY OF SPECIlCATION DESIGN CODING
TESTING AND DEBUGGING
® #2)4)#!, 4().+).' ! VARIETY OF WRITTEN RESPONSE QUESTIONS THAT PROVOKE CRITICAL THINKING
ARE PROVIDED AT THE END OF EACH CHAPTER
® $!4! 3425#452%3 !RRAYS STACKS QUEUES AND LINK LIST ARE EXPLAINED
® 2%#523)/. !.$ !$6!.#%$ !,'/2)4(-3 "INARY SEARCH DEPTH lRST SEARCH AND SORTING
ALGORITHMS ARE COVERED
® '5) !.$ %6%.4 $2)6%. 02/'2!--).' 4HE 3WING *AVA PACKAGE IS INTRODUCED FOR CREATING
'5) EVENT DRIVEN APPLICATIONS
® !00,%43 !.$ 7%" 02/'2!--).' !PPLETS AND WEB PROGRAMMING ARE INTRODUCED
)3".
k-`Y`.NQOPOW- 3OFTCOVER