0% found this document useful (0 votes)
3 views

Java Software Solutions for AP computer science 3rd Edition Loftus download

The document provides information about the book 'Java Software Solutions for AP Computer Science, 3rd Edition' by John Lewis, William Loftus, and Cara Cocking, which aligns with the AP Computer Science curriculum. It highlights updates in the new edition, including detailed coverage of primitive types, loop analysis, and testing and debugging sections. The book is designed to enhance the learning experience for AP students and teachers with numerous examples, exercises, and supplementary online resources.

Uploaded by

shahszlonsa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java Software Solutions for AP computer science 3rd Edition Loftus download

The document provides information about the book 'Java Software Solutions for AP Computer Science, 3rd Edition' by John Lewis, William Loftus, and Cara Cocking, which aligns with the AP Computer Science curriculum. It highlights updates in the new edition, including detailed coverage of primitive types, loop analysis, and testing and debugging sections. The book is designed to enhance the learning experience for AP students and teachers with numerous examples, exercises, and supplementary online resources.

Uploaded by

shahszlonsa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Java Software Solutions for AP computer science

3rd Edition Loftus pdf download

https://ebookname.com/product/java-software-solutions-for-ap-
computer-science-3rd-edition-loftus/

Get Instant Ebook Downloads – Browse at https://ebookname.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Computing handbook computer science and software


engineering 3ed. Edition Allen B Tucker

https://ebookname.com/product/computing-handbook-computer-
science-and-software-engineering-3ed-edition-allen-b-tucker/

Software Engineering and Testing An Introduction


Computer Science 1st Edition B. B. Agarwal

https://ebookname.com/product/software-engineering-and-testing-
an-introduction-computer-science-1st-edition-b-b-agarwal/

Computer Organization and Design The Hardware Software


Interface 3rd Edition David A. Patterson

https://ebookname.com/product/computer-organization-and-design-
the-hardware-software-interface-3rd-edition-david-a-patterson/

GPU Pro 7 Advanced Rendering Techniques 1st Edition


Wolfgang Engel

https://ebookname.com/product/gpu-pro-7-advanced-rendering-
techniques-1st-edition-wolfgang-engel/
Land in Conflict Managing and Resolving Land Use
Disputes 1st Edition Sean Nolon

https://ebookname.com/product/land-in-conflict-managing-and-
resolving-land-use-disputes-1st-edition-sean-nolon/

Lithium Compounds in Organic Synthesis From


Fundamentals to Applications 1st Edition Luisi Renzo
(Ed.)

https://ebookname.com/product/lithium-compounds-in-organic-
synthesis-from-fundamentals-to-applications-1st-edition-luisi-
renzo-ed/

The Digital God How Technology Will Reshape


Spirituality 1st Edition William Indick

https://ebookname.com/product/the-digital-god-how-technology-
will-reshape-spirituality-1st-edition-william-indick/

Joseph Beuys 1st Edition Claudia Mesch

https://ebookname.com/product/joseph-beuys-1st-edition-claudia-
mesch/

Manual of Traumatic Brain Injury Management 1st Edition


Felise S. Zollman

https://ebookname.com/product/manual-of-traumatic-brain-injury-
management-1st-edition-felise-s-zollman/
The Christians as the Romans Saw Them Second Edition
Robert Lewis Wilken

https://ebookname.com/product/the-christians-as-the-romans-saw-
them-second-edition-robert-lewis-wilken/
J ava 3rd Edition
S O F T WA R E S O L U T I O N S

for AP* Computer Science

*AP and Advanced Placement Program are registered trademarks of The College Board,
which was not involved in the production of, and does not endorse, this product.
This page intentionally left blank
J ava 3rd Edition
S O F T WA R E S O L U T I O N S

for AP* Computer Science

JOHN WILLIAM CARA


LEWIS LOFTUS COCKING

Addison-Wesley
Boston Columbus Indianapolis New York San Francisco Upper Saddle River
Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montreal Toronto
Delhi Mexico City Sao Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo

*AP and Advanced Placement Program are registered trademarks of The College Board,
which was not involved in the production of, and does not endorse, this product.
Editor in Chief: Michael Hirsch
Editorial Assistant: Stephanie Sellinger
Marketing Coordinator: Kathryn Ferranti
Managing Editor: Jeffrey Holcomb
Production Project Manager: Heather McNally
Senior Manufacturing Buyer: Carol Melville
Art Director: Linda Knowles
Cover Designer: Joyce Cosentino Wells
Text Designer: Jerilyn Bockorick, Nesbitt Graphics, Inc.
Cover Art: Michael Shivers / Alamy
Full-Service Project Management: Rose Kernan, Nesbitt Graphics, Inc.
Composition and Art: Nesbitt Graphics, Inc.

Credits and acknowledgments borrowed from other sources and reproduced, with permission, in this textbook appear on appropriate
page within text. Many of the designations by manufacturers and seller to distinguish their products are claimed as trademarks. Where
those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed in initial
caps or all caps.

Microsoft® and Windows® are registered trademarks of the Microsoft Corporation in the U.S.A. and other countries. Screen shots and
icons reprinted with permission from the Microsoft Corporation. This book is not sponsored or endorsed by or affiliated with the
Microsoft Corporation.

The programs and applications presented in this book have been included for their instructional value. They have been tested with care,
but are not guaranteed for any particular purpose. The publisher does not offer any warranties or representations, nor does it accept
any liabilities with respect to the programs or applications.

Copyright © 2011, 2007, 2004 Pearson Education, Inc., publishing as Addison-Wesley, 501 Boylston Street, Suite 900, Boston,
Massachusetts 02116. All rights reserved. Manufactured in the United States of America. This publication is protected by Copyright,
and permission should be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmis-
sion in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. To obtain permission(s) to use material
from this work, please submit a written request to Pearson Education, Inc., Permissions Department, 501 Boylston Street, Suite 900,
Boston, Massachusetts 02116.

Library of Congress Cataloging-in-Publication Data


Lewis, John, 1963-
Java software solutions for AP computer science / John Lewis, William
Loftus, Cara Cocking. -- 3rd ed.
p. cm.
ISBN 0-13-137469-9
1. Java (Computer program language) 2. Electronic data processing--Study
and teaching (Secondary) I. Loftus, William. II. Cocking, Cara. III. Title.
QA76.73.J38L4885 2011
005.13'3076--dc22
2009050911

1 2 3 4 5 6 7 8 9 10--CRK--14 13 12 11 10

ISBN 10: 0-13-137469-9


www.pearsonhighered.com ISBN 13: 978-0-13-137469-0

*AP and Advanced Placement Program are registered trademarks of The College Board,
which was not involved in the production of, and does not endorse, this product.
To Sharon, Justin, Kayla, Nathan, and Samantha Lewis

—J.L.

To Veena, Isaac, and Devi Loftus

—W.L.

To Richard and Doris Cocking

—C.C.
This page intentionally left blank
Preface
Welcome to Java™ Software Solutions for AP* Computer Science. This
Advanced Placement* book matches both the AP* Computer Science topic
outline and Java subset set forth by the College Board.

What’s New in This Edition


We have been pleased to hear that this book has met and exceeded the
needs of many instructors of AP* Computer Science courses. We appreciate
your feedback and suggestions.
This third edition of Java Software Solutions for AP* Computer Science
has been updated to ensure that the most recent requirements for the
Advanced Placement test have been thoroughly covered. In addition, the
flow and discussion of certain topics have been improved and updated.
The specific changes include:
■ The coverage of primitive types in Chapter 2 now provides more
detail of internal representation and a discussion of imprecision and
round-off error.
■ An appendix has been added covering number systems and examples
of conversions between bases.
■ A discussion of the Integer.MAX_VALUE and Integer.MIN_VALUE con-
stants is now part of the Chapter 2 coverage of wrapper classes.
■ The Math.random method is discussed in more detail in Chapter 2 as
an alternative to using the Random class.
■ Chapter 3 now includes a discussion of loop analysis.
■ A new section in Chapter 5 covers Testing and Debugging.
■ End-of-chapter exercises have been updated to reflect the modified
and new material.

About This AP* Book


This book has been specifically designed to meet the needs of today’s AP*
students and AP* teachers. Let’s hit the highlights. Specifically:
■ Online sections for most chapters tie the official AP* case study in
with the concepts covered in that chapter. This material is available
on the book’s Web site.
*AP and Advanced Placement Program are registered trademarks of The College Board,
which was not involved in the production of, and does not endorse, this product. vii
viii PR EFA C E

■ The discussion and examples fully embrace the Java 2 Standard


Edition, Version 6.0.
■ We utilize hundreds of example programs, fully implemented for
experimentation by AP* students and AP* teachers.
■ Graphics are covered in an optional section (called Graphics Track) at
the end of each chapter. Building on the excitement of the Web, the
Graphics Track is intended to further inspire and engage AP* students.
■ The Self-Review Questions, Exercises, and Programming Projects have
been specifically designed to adhere to various learning styles, includ-
ing multiple choice, true/false, and short-answer questions.
■ The reference material in the appendices includes: Glossary, Unicode
Character Set, Java Operators, and Number Systems.
■ A robust ancillary package accompanies this book and is outlined fur-
ther in this preface.
■ The full-color design aids learning by making it easier to distinguish
between various elements in code and diagrams. Full-color screen shots
make the discussions of graphical interfaces more insightful and realistic.

Cornerstones of the Text


This text is based on the following basic ideas that we believe make for a
sound introductory text:
■ True object-orientation. A text that really teaches a solid object-oriented
approach must use what we call object-speak. That is, all processing
should be discussed in object-oriented terms. That does not mean,
however, that the first program an AP* student sees must discuss the
writing of multiple classes and methods. An AP* student should learn
to use objects before learning to write them. This text uses a natural
progression that culminates in the ability to design real object-oriented
solutions.
■ Sound programming practices. AP* students should not be taught
how to program; they should be taught how to write good software.
There’s a difference. Writing software is not a set of cookbook
actions, and a good program is more than a collection of state-
ments. This text integrates practices that serve as the foundation of
good programming skills. These practices are used in all examples
and are reinforced in the discussions. AP* students learn how to
solve problems as well as how to implement solutions. We introduce
and integrate basic software engineering techniques throughout the
text.
■ Examples. AP* students learn by example. This text is filled with fully
implemented examples that demonstrate specific concepts. We have
P REFAC E ix

intertwined small, readily understandable examples with larger, more


realistic ones. There is a balance between graphics and nongraphical
programs and between applets and applications.
■ Graphics and GUIs. Graphics can be a great motivator for AP* students,
and their use can serve as excellent examples of object-orientation. As
such, we use them throughout the text in a well defined set of sections
that we call the Graphics Track. This coverage includes the use of event
processing and graphical user interfaces (GUIs). AP* students learn to
build GUIs in the appropriate way by using a natural progression of
topics. The Graphics Track can be avoided entirely for those who do
not choose to use graphics.

Chapter Breakdown
Chapter 1 (Computer Systems) introduces computer systems in general,
including basic architecture and hardware, networking, programming, and
language translation. Java is introduced in this chapter, and the basics of pro-
gram development are discussed. This chapter contains broad introductory
material that can be covered while AP* students become familiar with their
development environment.
Chapter 2 (Objects and Primitive Data) establishes the concept of objects
and how they can be used. Many predefined classes from the Java standard
library are explored and used. Enumerated types, primitive types, operators,
and expressions are also explored.
Chapter 3 (Program Statements) covers most of the fundamental state-
ments including conditionals, loops, and iterators. Some additional operators
are introduced at this point as well. Establishing key statements at this point
allows the classes of the next chapter to be fully functional and realistic.
Chapter 4 (Writing Classes) explores issues related to writing classes and
methods. Topics include instance data, visibility, scope, method parameters,
and return types. Method overloading is covered as well. Some of the more
involved topics are deferred to or revisited in Chapter 5. The key to Chapter
4 is the many fully implemented, realistic classes that are presented as exam-
ples of class design.
Chapter 5 (Enhancing Classes) covers additional issues related to class
design and revisits topics that need further exploration. Object references are
revisited and carefully explored, and their impact on parameter passing is
discussed. Exceptions, interfaces, and their effect on design are also covered.
Finally, guidelines on designing classes, as well as testing, are given.
Chapter 6 (Arrays) contains extensive coverage of arrays and array pro-
cessing. Topics include multidimensional arrays, searching, and sorting.
The ArrayList class is explored as well, and generic types are introduced
here.
x PR EFA C E

Chapter 7 (Inheritance) covers class derivations and associated concepts


such as class hierarchies, overriding, and polymorphism. Emphasis is put on
the proper use of inheritance and its role in software design.
Chapter 8 (Recursion) covers the concept, implementation, and proper use
of recursion. Several examples from various domains are used to demon-
strate how recursive techniques make certain types of processing elegant.
Recursive sorting algorithms are also covered.
Chapter 9 (Linear Data Structures) introduces the idea of a collection and
its underlying data structure. Abstraction is revisited in this context and the
linked list, queue, and stack data structures are explored.
Chapter 10 (Non-linear Data Structures) further explores dynamic data
structures, including trees and heaps. Sets and maps are also introduced and
hashtables are revisited.

Supplements
AP* students are welcome to visit www.pearsonhighered.com/cssupport
(author: Lewis/Loftus/Cocking) for the following resources:
■ Source Code to all program examples in the text.
■ Case Study section for most chapters linking the concepts covered in
that chapter with the official AP* case study.
The following supplements are available online for qualified AP* teachers
only, at www.pearsonhighered.com/irc. Teachers may obtain a code to access
the supplements below from their Pearson sales representative. If you need
help finding this material, contact your Pearson sales representative. You can
find your rep in the “Find your sales rep” section atwww.pearsonschool.com.
■ Lesson Plans with Pacing Guide.
■ Solutions to all end-of-chapter exercises and programming projects.
■ PowerPoint slides.
■ Test Bank with powerful test generator software, includes a wealth of
free response, multiple choice, and true/false questions.
■ Source Code to all program examples in the text.

AP* Correlation Guide


On the next page, we present the AP* Computer Science correlation guide as
given by the College Board. The column on the right shows the sections of
this book where each topic is covered.
P REFAC E xi

AP* Computer Science Topics Sections Where Taught


I. OBJECT-ORIENTED PROGRAM DESIGN
The overall goal for designing a piece of software (a computer program) is to correctly solve the given
problem. At the same time, this goal should encompass specifying and designing a program that is
understandable, can be adapted to changing circumstances, and has the potential to be reused in
whole or in part. The design process needs to be based on a thorough understanding of the problem
to be solved.
A. Program design
1. Read and understand a problem Sections 1.3, 3.0, 3.7
description, purpose, and goals.
2. Apply data abstraction and encapsulation. Sections 2.1, 4.1, 7.7
3. Read and understand class specifications Sections 4.5, 7.0
and relationships among the classes
(“is-a,” “has-a” relationships).
4. Understand and implement a given class Sections 7.0, 7.2
hierarchy.
5. Identify reusable components from existing Sections 2.0, 7.4
code using classes and class libraries.
B. Class design
1. Design and implement a class. Sections 4.0–4.4, 5.0, 5.1, 5.4
2. Choose appropriate data representation Sections 3.7, 5.4
and algorithms.
3. Apply functional decomposition. Sections 4.2, 4.4
4. Extend a given class using inheritance. Sections 7.0, 7.1, 7.3, 7.4

II. PROGRAM IMPLEMENTATION


The overall goals for program implementation parallel those of program design. Classes that fill com-
mon needs should be built so that they can be reused easily in other programs. Object-oriented
design is an important part of program implementation.
A. Implementing techniques
1. Methodology
a. Object-oriented development Section 2.0
b. Top-down development Section 3.0
c. Encapsulation and information hiding Section 4.1
d. Procedural abstraction Section 4.2
B. Programming constructs
1. Primitive types vs. objects Sections 2.0, 2.1, 2.4
2. Declaration
a. Constant declarations Section 2.3
b. Variable declarations Section 2.3
c. Class declarations Section 4.1
d. Interface declarations Section 5.3
e. Method declarations Section 4.2
f. Parameter declarations Section 4.2
3. Console output (System.out.print/println) Section 2.1
4. Control
a. Methods Section 4.2
b. Sequential Section 3.1
c. Conditional Section 3.2
d. Iteration Sections 3.5, 3.6
e. Understand and evaluate recursive methods Sections 8.0–8.2
xii PR EFA C E

AP* Computer Science Topics Sections Where Taught


C. Java library classes (included in the A-level AP* Java Subset)
Object Section 7.2
Comparable Section 5.3
Integer Section 2.7
Double Section 2.7
String Section 2.7
Math Section 2.8
Random Section 2.8
ArrayList Section 6.7
III. PROGRAM ANALYSIS
The analysis of programs includes examining and testing programs to determine whether they cor-
rectly meet their specifications. It also includes the analysis of programs or algorithms in order to
understand their time and space requirements when applied to different data sets.
A. Testing
1. Test classes and libraries in isolation Section 5.4
2. Identify boundary cases and generate Section 5.4
appropriate test data
3. Perform integration testing Section 5.4
B. Debugging
1. Categorize errors: compile-time, run-time, logic Section 1.4
2. Identify and correct errors Sections 1.4, 5.4
3. Techniques: use a debugger, add extra output Sections 1.4, 5.4
statements, hand-trace code
C. Understand and modify existing code Learned throughout the text
D. Extend existing code using inheritance Sections 7.0, 7.1, 7.3, 7.4
E. Understand error handling
1. Understand runtime exceptions Section 5.2
F. Reason about programs
1. Pre- and post-conditions Section 4.2
2. Assertions Section 4.2
G. Analysis of algorithms
1. Informal comparisons of running times Sections 6.2, 6.4
2. Exact calculation of statement execution Sections 6.2, 6.4
counts
H. Numerical representations and limits
1. Representations of numbers in different bases Section 1.0, Appendix E
2. Limitations of finite representations Sections 2.4, 3.3
(e.g., integer bounds, imprecision of floating-point
representations, and round-off error)
IV. STANDARD DATA STRUCTURES
Data structures are used to represent information within a program. Abstraction is an important
theme in the development and application of data structures.
A. Simple data types (int, boolean, double) Section 2.4
B. Classes Sections 2.0, 4.1
P REFAC E xiii

AP* Computer Science Topics Sections Where Taught


C. Lists Sections 6.7, 9.0–9.1
D. Arrays Sections 6.0, 6.1

V. STANDARD ALGORITHMS

Standard algorithms serve as examples of good solutions to standard problems. Many are inter-
twined with standard data structures. These algorithms provide examples for analysis of program effi-
ciency.
A. Operations on data structures previously listed
1. Traversals Sections 6.0, 6.1, 6.7
2. Insertions Sections 6.0, 6.1, 6.7
3. Deletions Sections 6.0, 6.1, 6.7
B. Searching
1. Sequential Section 6.2
2. Binary Section 6.2
C. Sorting
1. Selection Section 6.3
2. Insertion Section 6.3
3. Mergesort Section 8.3

VI. COMPUTING IN CONTEXT

An awareness of the ethical and social implications of computing systems is necessary for the study
of computer science. These topics need not be covered in detail but should be considered through-
out the course.
A. System reliability Appendix F
B. Privacy Appendix F
C. Legal issues and intellectual property Appendix F
D. Social and ethical ramifications of computer use Appendix F

Acknowledgments
We are most grateful to the AP* teachers and AP* students from around the
world who have provided their feedback on the previous edition of this book.
We are pleased to see the depth of the faculty’s concern for their AP* students
and the AP* students’ thirst for knowledge. Your comments and questions
are always welcome.
Michael Hirsch and Stephanie Sellinger, our editors at Addison-Wesley,
went above and beyond the call of duty to ensure that the book met the high-
est quality standards. Their support and enthusiasm are greatly appreciated.
We are also grateful to Andrea Sheehan and Courtney Marsh with Pearson
School for making sure that AP* teachers understand the pedagogical advan-
tages of this text. The devotion that the Addison-Wesley and Pearson folks
show to their books is evident in the high-quality results.
xiv PR EFA C E

The production team for this edition is a group of gifted and hard-working
people—miracle workers all. Thanks go to Heather McNally, Joyce
Cosentino Wells (for the wonderful cover), and Rose Kernan and the rest of
the Nesbitt Graphics group. The quality of the book is due largely to their
personal attention, and it is greatly appreciated.
Special thanks also go to the reviewers of this text over the last few edi-
tions, as well as the many other instructors and friends who have provided
valuable feedback.
They include Neil Ascione—Wayne Valley High School, NJ; Brian Ellis—
Manheim Township School District, PA; Kathy Gilbert—Cary-Grove High
School, IL; Gregory King—Dublin Coffman High School, OH; Richard
Lamb—Cranbrook High School, MI; Deepa Muralidhar—Northview High
School, GA; Kim Murphy—Weber High School, UT; G. Lynne Ryan—North
Crowley High School, TXJenka Guevara, American School Foundation,
Mexico City; Leigh Ann Sudol, Fox Lane High School/New York University,
NY; Kathleen Weaver, Hillcrest High School, Dallas, TX; John E. Hanna,
Teaneck High School, NJ; Brian G. Scarbeau, Lake Highland Preparatory
School, FL; Frances Caruso Wolanczyk, Fieldston School, NY; Mark
Hanington, Punahou School, Honolulu, HI; Rose M. Hoffman, Catholic
Memorial High School, Waukesha, WI; Kathleen Larson, Kingston High
School, Kingston, NY; Bob Beck, Villanova University; Paul Gormley,
Villanova University; Cathy Helwig, Villanova University; Dan Joyce,
Villanova University; Najib Nadi, Villanova University; Beth Taddei,
Villanova University; Barbara Zimmerman, Villanova University; John
Simms, Marquette University; Marian Manyo, Marquette University.
Most importantly, we thank our families for their support during the busy
process of writing, not to mention the other times.
Feature Walkthrough
Key Concepts. Throughout the
2.1 Computer Processing 63
text, the Key Concept boxes high-
disk. When you instruct the computer to execute your program, a
light fundamental ideas and
KEY C ON C EPT
copy of the program is brought in from secondary memory and
stored in main memory. The CPU reads the individual program
The CPU reads the program important guidelines. These con-
instructions from main memory,
instructions from main memory. The CPU then executes the instruc-
tions one at a time until the program ends. The data that the instruc-
executing them one at a time
until the program ends. cepts are summarized at the end
tions use, such as two numbers that will be added together, are also
stored in main memory.
of each chapter.
The process of executing a program is fundamental to the operation of a
computer. All computer systems basically work in the same way.

Listings. All programming exam-


66 C H A P TE R 2 Data and Expressions
ples are presented in clearly
labeled listings, followed by the
L I S T I N G 2 . 2
program output, a sample run, or
screen shot display as appropri- //********************************************************************
// Roses.java Author: Lewis/Loftus
//
ate. The code is colored to visu- // Demonstrates the use of escape sequences.
//********************************************************************

ally distinguish comments and public class Roses


{
reserved words. //-----------------------------------------------------------------
// Prints a poem (of sorts) on multiple lines.
//-----------------------------------------------------------------
public static void main (String[] args)
{
System.out.println ("Roses are red,\n\tViolets are blue,\n" +
"Sugar is sweet,\n\tBut I have \"commitment issues\",\n\t" +
"So I'd rather just be friends\n\tAt this point in our " +
"relationship.");
}
}

O U T P U T

Roses are red,


Violets are blue,
Sugar is sweet,
But I have "commitment issues",
So I'd rather just be friends
At this point in our relationship.

xv
xvi F EAT U R E WALKTHRO UG H

Syntax Diagrams. At appropriate


Local Variable Declaration points in the text, syntactic ele-
Type Variable Declarator
ments of the Java language are
final
,
discussed in special highlighted
sections with diagrams that
Variable Declarator
clearly identify the valid forms for
Identifier a statement or construct.
= Expression
Array Initializer

A variable declaration consists of a Type followed by a list of


variables. Each variable can be initialized in the declaration to the
value of the specified Expression. If the final modifier precedes the
declaration, the identifiers are declared as named constants whose

Graphics Track. All processing


that involves graphics and graphi- 2.7
GRAPHICS TRACK

Graphics
cal user interfaces is discussed in K EY C ON C EPT
Graphics play a crucial role in computer systems. Throughout
this book we explore various aspects of graphics and discuss
one or two sections at the end of Graphical data is represented by
dividing it into many small pieces how they are accomplished. In fact, the last one or two sec-
called pixels. tions of each chapter are devoted to graphics topics. We refer
each chapter that we collectively to this as the Graphics Track through the book. These sections
can be skipped without losing continuity through the rest of the text, incor-
refer to as the Graphics Track. This porated into the regular flow of the chapters, or explored as a group.
A picture, like all other information stored on a computer, must be digi-
material can be skipped without tized by breaking the information into pieces and representing those pieces as
numbers. In the case of pictures, we break the picture into pixels (picture ele-
loss of continuity, or focused on ments). A pixel is a tiny region that represents a very small piece of the pic-
ture. The complete picture is stored by storing the color of each individual
specifically as desired. The mate- pixel.

rial in any Graphics Track section A digitized picture can be reproduced when needed by reassembling its
pixels. The more pixels used to represent a picture, the more realistic it looks
relates to the main topics of the when it is reproduced. The number of pixels used to represent a picture is
called the picture resolution. The number of pixels that can be displayed by
chapter in which it is found. a monitor is called the monitor resolution. A black and white picture can be
stored by representing each pixel using a single bit. If the bit is 0, that pixel
Graphics Track sections are indi- is white; if the bit is 1, it is black. Figure 2.8 shows a black and white picture
that has been stored digitally and an enlargement of a portion of that picture,
cated by a light blue border on which shows the individual pixels.
Graphics play a crucial role in computer systems. Throughout this book
the edge of the page. we explore various aspects of graphics and discuss how they are accom-
plished. In fact, the last one or two sections of each chapter are devoted to
graphics topics. We refer to this as the Graphics Track through the book.
F EAT U RE WALK T H RO U G H xvii

AP* Case Study. The case study


270 CHAP TE R 2 Data and Expressions
sections apply concepts from
the text to the AP* Case Study
AP* Case Study
that students need to study for
To work with the AP* Case Study section for this chapter, go to
www.aw.com/cssupport and look under author: Lewis/Loftus/Cocking. the AP* Exam. The case study
sections can be found at
www.aw.com/cssupport under
author: Lewis/Loftus/Cocking.

Summary of Key Concepts. The


276 C H A P TE R 2 Data and Expressions
Key Concepts presented through-
out a chapter are summarized at
Summary of Key Concepts
the end of the chapter.
■ The information we manage in a Java program is either primitive data
or objects.
■ An abstraction hides details. A good abstraction hides the right details
at the right time.
■ A variable is a name for a memory location used to hold a value.
■ A variable can store only one value of its declared type.
■ Java is a strongly typed language. Each variable has a specific type,
and we cannot assign a value of one type to a variable of another
type.
■ Constants are like variables, but they have the same value throughout
the program.
■ Java has two kinds of numeric values: integers and floating point. The
primitive type int is an integer data type and double is a floating
point data type.
■ Expressions are combinations of one or more operands and the opera-
tors used to perform a calculation.
■ Java has rules that govern the order in which operators will be evalu-
ated in an expression. These rules are called operator precedence rules.
■ Avoid narrowing conversions because they can lose information.

Self-Review Questions and


Self-Review Questions
2.1 What are the primary concepts that support object-oriented pro- Answers. These short-answer
gramming?
2.2 Why is an object an example of abstraction?
questions review the fundamental
2.3 What is primitive data? How are primitive data types different ideas and terms established in the
from objects?
2.4 What is a string literal? chapter. They are designed to
2.5 What is the difference between the print and println methods?
allow students to assess their own
basic grasp of the material. The
answers to these questions can be
Answers to Self-Review Questions
found at the end of the problem
2.1 The main elements that support object-oriented programming are sets.
objects, classes, encapsulation, and inheritance. An object is
defined by a class, which contains methods that define the opera-
tions on those objects (the services that they perform). Objects
store and manage their own data. Inheritance is a technique in
which one class can be created from another.
2.2 An object is abstract because the details of the object are hidden
from, and largely unimportant to, the user of the object. Hidden
details help us manage the complexity of software.
xviii F EAT U R E WALKTHRO UG H

Exercises. The multiple choice,


Short Answer
7.1 Draw an inheritance hierarchy containing classes that represent true/false, and short answer exercises
different types of clocks. Show the variables and method names
for two of these classes. at the end of every chapter are
7.2 Show another diagram for the hierarchy in Exercise 7.1. Explain
why it may be better or worse than the original.
designed to develop and test the stu-
7.3 Draw a class hierarchy for types of teachers at a high school. dents’ knowledge of that chapter’s
Show what characteristics would be represented in the various
classes of the hierarchy. Explain how polymorphism could play a material. These exercises generally do
role in assigning courses to each teacher.
not require the use of a computer.

Programming Projects. These problems Programming Projects


require the design and implementation 8.1 Design and implement a recursive version of the PalindromeTester
program from (Listing 3.9) Chapter 3.
of Java programs. They vary widely in 8.2 Design and implement a program for finding the greatest common
divisor of two positive numbers using Euclid’s algorithm. The
level of difficulty. greatest common divisor is the largest number that divides both
numbers without producing a remainder. An iterative version of
this method was part of the Rational class presented in Chapter 4.
In a class called DivisorCalc, define a static method called gcd
that accepts two integers, num1 and num2. Create a driver to test
your implementation. The recursive algorithm is defined as follows:
a. gcd (num1, num2) is num2 if num2 <= num1 and num2
divides num1
b. gcd (num1, num2) is gcd (num2, num1) if num1 < num2
c. gcd (num1, num2) is gcd (num2, num1%num2) otherwise
8.3 Modify the Maze class (Listing 8.2) so that it prints out the path of
the final solution as it is discovered, without storing it.
8.4 Design and implement a program that solves a 3D maze.

AP*-Style Questions. These questions


AP*-Style Multiple Choice
3.1 Consider the following output. are modeled after the multiple choice
10 9 8 7 6 5 4 3 2 1
Which of the following loops will produce this output?
and free response questions on the AP*
(A) for (int i = 0; i < 10; i--) Exam. They are designed to help
System.out.print(i + " ");
(B) for (int i = 10; i >= 0; i--) students apply material from each
System.out.print(i + " ");
chapter to the types of questions they
(C) for (int i = 0; i <= 10; i++)
System.out.print((10 – i) + " "); will encounter on the AP* Exam.
(D) for (int i = 0; i < 10; i++)
System.out.print((10 – i) + " ");
(E) for (int i = 10; i > 0; i--)
System.out.print((10 – i) + " ");

AP*-Style Free Response


5.1 Consider the following incomplete declaration of a Name class.

public class Name something missing


{
private String first;
private String last;

public Name(String firstName, String lastName)


{
first = firstName;
last = lastName;
}
Contents

Preface vii

AP* Correlation Guide xi

Chapter 1 Computer Systems 1


1.0 Introduction 2
Basic Computer Processing 2
Software Categories 3
Digital Computers 5
Binary Numbers 6
1.1 Hardware Components 9
Computer Architecture 9
Input/Output Devices 11
Main Memory and Secondary Memory 11
The Central Processing Unit 15
1.2 Networks 16
Network Connections 17
Local-area Networks and Wide-area Networks 18
The Internet 19
The World Wide Web 20
Uniform Resource Locators 22
The Internet vs. The World Wide Web 22
1.3 Programming 22
Problem Solving 23
The Java Programming Language 23
A Java Program 24
Comments 26
Identifiers and Reserved Words 27
White Space 30
1.4 Programming Languages 31
Programming Language Levels 32
Compilers and Interpreters 34
Syntax and Semantics 36
Errors 37
Language Evolution 38

xix
xx CONTENTS

1.5 Graphics 38
Coordinate Systems 38
Representing Color 40

Chapter 2 Objects and Primitive Data 51


2.0 An Introduction to objects 52

2.1 Using Objects 54


The print and println Methods 55
Abstraction 56

2.2 String Literals 57


String Concatenation 57
Escape Sequences 60

2.3 Variables and Assignment 60


Variables 61
The Assignment Statement 63
Constants 65

2.4 Primitive Data Types 65


Integers and Floating Points 66
Booleans 67
Characters 67

2.5 Arithmetic Expressions 68


Operator Precedence 69
Data Conversion 72

2.6 Enumerated Types 73

2.7 Creating Objects 74


The String Class 77
Wrapper Classes 79
Autoboxing 81

2.8 Class Libraries and Packages 82


The Import Declaration 83
The Random Class 85
The Math Class 86

2.9 Interactive Programs 89


The Scanner Class 89

2.10 Formatting Output 93


The NumberFormat Class 93
The DecimalFormat Class 93
The Printf Method 95
CONTENTS xxi

2.11 An Introduction to Applets 97


Executing Applets Using the Web 99

2.12 Drawing Shapes 100


The Graphics Class 100
The Color Class 102

Chapter 3 Program Statements 117


3.0 Program Development 118

3.1 Control Flow 120

3.2 The if Statement 121


Equality and Relational Operators 123
The if-else Statement 124
Using Block Statements 125
Nested if Statements 128

3.3 Boolean Expressions Revisited 130


Logical Operators 130
Comparing Characters and Strings 132
Comparing Floating Point Values 134

3.4 More Operators 134


Increment and Decrement Operators 135
Assignment Operators 135

3.5 The While Statement 136


Infinite Loops 140
Nested Loops 143
3.6 Iterators 146
Reading Text Files 147
3.7 The For Statement 150
Iterators and for Loops 155
Comparing Loops 156
3.8 Program Development Revisited 157
3.9 Drawing Using Conditionals and Loops 161

Chapter 4 Writing Classes 181


4.0 Objects Revisited 182
Classes 183

4.1 Anatomy of a Class 184


Instance Data 187
Encapsulation and Visibility Modifiers 189
xxii CONTENTS

4.2 Anatomy of a Method 192


The Return Statement 197
Parameters 199
Preconditions and Postconditions 200
Constructors 201
Local Data 202
Accessors and Mutators 202

4.3 Method Overloading 203

4.4 Method Decomposition 204

4.5 Object Relationships 211


Association 211
Association Between Objects of the Same Class 211
Aggregation 213

4.6 Applet Methods 220

4.7 Graphical Objects 221

Chapter 5 Enhancing Classes 241


5.0 References Revisited 242
The Null Reference 242
The This Reference 243
Aliases 243
Passing Objects as Parameters 249

5.1 The Static Modifier 253


Static Variables 253
Static Methods 253

5.2 Exceptions 256


Exception Messages 257
Throwing Exceptions 258

5.3 Interfaces 259


The Comparable Interface 264
The List Interface 266
The Iterator and ListIterator Interfaces 266

5.4 Identifying Classes and Objects 268


Designing Classes 269
Testing and Debugging 271

5.5 Nested Classes 273


Inner Classes 273

5.6 Dialog Boxes 274


CONTENTS xxiii

5.7 Graphical User Interfaces 276


Essential GUI Elements 276
Creating GUIs 277
GUI Applications 279

Chapter 6 Arrays 295


6.0 Arrays 296
Array Indexing 296
Declaring and Using Arrays 297
Initializer Lists 303
Arrays as Parameters 305

6.1 Arrays of Objects 305


Arrays of String Objects 305
Command-line Arguments 307
Filling Arrays of Objects 309

6.2 Searching 313


Comparing Searches 317

6.3 Sorting 319


Selection Sort 319
Insertion Sort 322
Sorting an Array of Objects 323
6.4 Comparing Sorts 326
6.5 Hashing 328
6.6 Two-dimensional Arrays 330
6.7 The ArrayList Class 333
Specifying an ArrayList Element Type 334
Using a ListIterator 336
ArrayList Efficiency 336

6.8 Polygons and Polylines 338


The Polygon Class 341
6.9 Other Button Components 341
Check Boxes 342
Radio Buttons 345

Chapter 7 Inheritance 363


7.0 Creating Subclasses 364
Derived Classes 364
The Super Reference 368
Multiple Inheritance 370
xxiv CONTENTS

7.1 Overriding Methods 371


7.2 Class Hierarchies 372
The Object Class 374
Abstract Classes 378

7.3 Indirect Use of Class Members 384

7.4 Designing for Inheritance 387

7.5 Polymorphism 388


References and Class Hierarchies 389
Polymorphism and Inheritance 390

7.6 Interfaces 399


Polymorphism with Interfaces 399

7.7 Designing for Polymorphism 401

7.8 Inheritance and GUIs 402


Applets 402
The Component Class Hierarchy 403

7.9 Mouse Events 405


Extending Event Adapter Classes 412

Chapter 8 Recursion 429


8.0 Recursive Thinking 430
Infinite Recursion 430
Recursion in Math 431

8.1 Recursive Programming 432


Recursion vs. Iteration 434
Direct vs. Indirect Recursion 435

8.2 Using Recursion 435


Solving a Maze 436
The Towers of Hanoi 440

8.3 Recursion in Sorting 444


Merge Sort 444
Quick Sort 450

8.4 Recursion in Graphics 451


Tiled Pictures 451
Fractals 454
Random documents with unrelated
content Scribd suggests to you:
back
back
back
back
back
back
back
back
back
back
back
back
back
back
back
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

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

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookname.com

You might also like