SlideShare a Scribd company logo
1 of 54
bj4_fm.fm Page iv Saturday, November 7, 2009 12:01 PM
• Students achieve concept
mastery in a rich,
structured environment
that’s available 24/7
From multiple study paths, to self-assessment, to a wealth of
interactive
visual and audio resources, WileyPLUS gives you everything
you need to
personalize the teaching and learning experience.
With WileyPLUS:
» F i n d o u t h ow t o M a k e I t Yo u r S »
This online teaching and learning environment
integrates the entire digital textbook with the
most effective instructor and student resources
to fit every learning style.
• Instructors personalize and manage
their course more effectively with
assessment, assignments, grade
tracking, and more
• manage time better
• study smarter
• save money
www.wileyplus.com
WP5_FM_8x10.indd 1 8/7/09 11:36 AM
Make It YourS!
aLL The heLP, reSoUrceS, and PerSonaL SUPPorT
yoU and yoUr STUdenTS need!
technical Support 24/7
FaQs, online chat,
and phone support
www.wileyplus.com/suppor t
Student support from an
experienced student user
ask your local representative
for details!
Your WileyPLUS
account Manager
training and implementation support
www.wileyplus.com/accountmanager
Collaborate with your colleagues,
find a mentor, attend virtual and live
events, and view resources
www.WhereFacultyconnect.com
Pre-loaded, ready-to-use
assignments and presentations
www.wiley.com/college/quickstar t
2-Minute tutorials and all
of the resources you & your
students need to get started
www.wileyplus.com/firstday
WP5_FM_8x10.indd 2 8/7/09 11:36 AM
th
edition
4
Big
Java
bj4_fm.fm Page iii Saturday, November 7, 2009 12:01 PM
bj4_fm.fm Page iv Saturday, November 7, 2009 12:01 PM
th
edition
4
Big
Java
Cay Horstmann
SAN JOSE STATE UNIVERSITY
JOHN WILEY & SONS, INC.
bj4_fm.fm Page v Saturday, November 7, 2009 12:01 PM
VICE PRESIDENT AND EXECUTIVE PUBLISHER Donald
Fowley
EXECUTIVE EDITOR Beth Lang Golub
EDITORIAL ASSISTANT Michael Berlin
PRODUCTION SERVICES MANAGER Dorothy Sinclair
PRODUCTION EDITOR Janet Foxman
EXECUTIVE MARKETING MANAGER Christopher Ruel
CREATIVE DIRECTOR Harry Nolan
SENIOR DESIGNER Madelyn Lesure
PHOTO EDITOR Lisa Gee
MEDIA EDITOR Lauren Sapira
PRODUCTION SERVICES Cindy Johnson
COVER DESIGNER Howard Grossman
COVER ILLUSTRATION Susan Cyr
This book was set in Stempel Garamond by Publishing Services,
and printed and bound by RRD Jefferson
City. The cover was printed by RRD Jefferson City.
This book is printed on acid-free paper.
∞
Copyright © 2010, 2008, 2006, 2002 John Wiley & Sons, Inc.
All rights reserved. No part of this publication
may be reproduced, stored in a retrieval system or transmitted
in any form or by any means, electronic,
mechanical, photocopying, recording, scanning or otherwise,
except as permitted under Sections 107 or 108
of the 1976 United States Copyright Act, without either the
prior written permission of the Publisher, or
authorization through payment of the appropriate per-copy fee
to the Copyright Clearance Center, Inc.,
222 Rosewood Drive, Danvers, MA 01923, website
www.copyright.com.
Requests to the Publisher for per-
mission should be addressed to the Permissions Department,
John Wiley & Sons, Inc., 111 River Street,
Hoboken, NJ 07030-5774, (201) 748-6011, fax (201) 748-6008,
website
www.wiley.com/go/permissions.
Evaluation copies are provided to qualified academics and
professionals for review purposes only, for use in
their courses during the next academic year. These copies are
licensed and may not be sold or transferred to
a third party. Upon completion of the review period, please
return the evaluation copy to Wiley. Return
instructions and a free of charge return shipping label are
available at
www.wiley.com/go/returnlabel.
Outside
of the United States, please contact your local representative.
Library of Congress Cataloging-in-Publication Data:
Horstmann, Cay S., 1959–
Big Java : compatible with Java 5, 6 and 7 / Cay Horstmann. --
4th ed.
p. cm.
Includes index.
ISBN 978-0-470-50948-7 (pbk. : alk. paper)
1. Java (Computer program language) I. Title.
QA76.73.J38H674 2010
005.13'3--dc22
2009042604
ISBN 978-0-470-50948-7
Printed in the United States of America
10 9 8 7 6 5 4 3 2 1
bj4_fm.fm Page vi Saturday, November 7, 2009 12:01 PM
PREFACE
vii
This book is an introductory text in computer science, focusing
on the principles of
programming and software engineering. Here are its key
features:
•
Teach objects gradually.
In Chapter 2, students learn how to use objects and classes from
the standard
library. Chapter 3 shows the mechanics of implementing classes
from a given
specification
. Students then use simple objects as they master branches,
loops, and
arrays. Object-oriented design starts in Chapter 8. This gradual
approach allows
students to use objects throughout their study of the core
algorithmic topics,
without teaching bad habits that must be un-learned later.
•
Reinforce sound engineering practices.
A focus on test-driven development encourages students to test
their programs
systematically. A multitude of useful tips on software quality
and common errors
encourage the development of good programming habits.
•
Help students with guidance and worked examples.
Beginning programmers often ask “How do I start? Now what
do I do?” Of
course, an activity as complex as programming cannot be
reduced to cookbook-
style instructions. However, step-by-step guidance is immensely
helpful for
building confidence and providing an outline for the task at
hand. The book con-
tains a large number of “How To” guides for common tasks,
with pointers to
additional worked examples on the Web.
•
Focus on the essentials while being technically accurate.
An encyclopedic coverage is not helpful for a beginning
programmer, but neither
is the opposite—reducing the material to a list of simplistic
bullet points that give
an illusion of knowledge. In this book, the essentials of each
subject are presented
in digestible chunks, with separate notes that go deeper into
good practices or lan-
guage features when the reader is ready for the additional
information.
•
Use standard Java.
The book teaches the standard Java language —not a specialized
“training
wheels” environment. The Java language, library, and tools are
presented at a
depth that is sufficient to solve real-world programming
problems. The final
chapters of the book cover advanced techniques such as
multithreading, database
storage, XML, and web programming.
•
Provide an optional graphics track.
Graphical shapes are splendid examples of objects. Many
students enjoy writing
programs that create drawings or use graphical user interfaces.
If desired, these
topics can be integrated into the course by using the materials at
the end of
Chapters 2, 3, 9, and 10.
bj4_fm.fm Page vii Saturday, November 7, 2009 12:01 PM
viii
Preface
This is the fourth edition of
Big Java,
and the book has once again been carefully
revised and updated. The new and improved features include:
• The How To sections have been updated and expanded, and
four new ones have
been added. Fifteen new Worked Examples (on the companion
web site and in
WileyPLUS) walk students through the steps required for
solving complex and
interesting problems.
• The treatment of algorithm design, planning, and the use of
pseudocode has been
enhanced. Students learn to use pseudocode to define the
solution algorithm in
Chapter 1.
• Chapters have been revised to focus each section on a specific
learning objective.
These learning objectives also organize the chapter summary to
help students
assess their progress.
• Syntax diagrams now call out features of typical example code
to draw student
attention to the key elements of the syntax. Additional
annotations point out
special cases, common errors, and good practice associated with
the syntax.
• New example tables clearly present a variety of typical and
special cases in a
compact format. Each example is accompanied by a brief note
explaining the
usage shown and the values that result from it.
• The gradual introduction of objects has been further improved
by providing
additional examples and insights in the early chapters.
• Features introduced in Java 7 are covered as Special Topics so
that students can
prepare for them. In this edition, we use Java 5 or 6 for the
main discussion.
• The test bank has been greatly expanded and improved. (See
page xi.)
• A new set of lab assignments enables students to practice
solving complex
problems one step at a time.
• The LabRat code evaluation feature, enhanced for this edition,
gives students
instant feedback on their programming assignments. (See page
xvi.)
New in This Edition
More Help for Beginning Programmers
Annotated Examples
Updated for Java 7
More Opportunities for Practice
bj4_fm.fm Page viii Saturday, November 7, 2009 12:01 PM
Preface
ix
The book can be naturally grouped into four parts, as illustrated
by Figure 1. The
organization of chapters offers the same flexibility as the
previous edition; depen-
dencies among the chapters are also shown in the figure.
Part A: Fundamentals
(Chapters 1–7)
Chapter 1 contains a brief introduction to computer science and
Java programming.
Chapter 2 shows how to manipulate objects of predefined
classes. In Chapter 3,
you will build your own simple classes from given
specifications.
Fundamental data types, branches, loops, and arrays are covered
in Chapters 4–7.
Part B: Object-Oriented Design (
Chapters 8–12)
Chapter 8 takes up the subject of class design in a systematic
fashion, and it intro-
duces a very simple subset of the UML notation.
The discussion of polymorphis m and inheritance is split into
two chapters. Chap-
ter 9 covers interfaces and polymorphism, whereas Chapter 10
covers inheritance.
Introducing interfaces before inheritance pays off in an
important way: Students
immediately see polymorphism before getting bogged down
with technical details
such as superclass construction.
Exception handling and basic file input/output are covered in
Chapter 11. The
exception hierarchy gives a useful example for inheritance.
Chapter 12 contains an introduction to object-oriented design,
including two
significant case studies.
Part C: Data Structures and Algorithms
(Chapters 13–17)
Chapters 13 through 17 contain an introduction to algorithms
and data structures,
covering recursion, sorting and searching, linked lists, binary
trees, and hash tables.
These topics may be outside the scope of a one-semester course,
but can be covered
as desired after Chapter 7 (see Figure 1).
Recursion is introduced from an object-oriented point of view:
An object that
solves a problem recursively constructs another object of the
same class that solves
a simpler problem. The idea of having the other object do the
simpler job is more
intuitive than having a function call itself.
Each data structure is presented in the context of the standard
Java collections
library. You will learn the essential abstractions of the standard
library (such as
iterators, sets, and maps) as well as the performance
characteristics of the various
collections. However, a detailed discussion of the
implementation of advanced data
structures is beyond the scope of this book.
Chapter 17 introduces Java generics. This chapter is suitable for
advanced stu-
dents who want to implement their own generic classes and
methods.
Part D: Advanced Topics
(Chapters 18–24)
Chapters 18 through 24 cover advanced Java programming
techniques that defi-
nitely go beyond a first course in Java. Although, as already
mentioned, a compre-
hensive coverage of the Java library would span many volumes,
many instructors
prefer that a textbook should give students additional reference
material valuable
beyond their first course. Some institutions also teach a second-
semester course that
A Tour of the Book
bj4_fm.fm Page ix Saturday, November 7, 2009 12:01 PM
x
Preface
Figure 1
Chapter Dependencies
4. Fundamental
Data Types
5. Decisions
9. Interfaces and
Polymorphism
10. Inheritance
11. Input/Output
and Exception
Handling
19. Streams and
Binary I/O
20.
Multithreading
12. Object-
Oriented Design
22. Relational
Databases
13. Recursion
14. Sorting
and Searching
15. Intro to
Data Structures
16. Advanced
Data Structures
21. Internet
Networking
23. XML
24. Web
Applications
7. Arrrays and
Array Lists
6. Iteration
8. Designing
Classes
17. Generic
Programming
3. Implementing
Classes
1. Introduction
2. Using Objects
Fundamentals
Object-Oriented Design
Data Structures & Algorithms
Advanced Topics
18. Graphical
User Interfaces
bj4_fm.fm Page x Saturday, November 7, 2009 12:01 PM
Preface
xi
covers more practical programming aspects such as database
and network program-
ming, rather than the more traditional in-depth material on data
structures and algo-
rithms. This book can be used in a two-semester course to give
students an
introduction to programming fundamentals and broad coverage
of applications.
Alternatively, the material in the final chapters can be useful
for student projects.
The advanced topics include graphical user-interface design,
advanced file han-
dling, multithreading, and those technologies that are of
particular interest to
server-side programming: networking, databases, XML, and web
applications. The
Internet has made it possible to deploy many useful applications
on servers, often
accessed by nothing more than a browser. This server-centric
approach to applica-
tion development was in part made possible by the Java
language and libraries, and
today, much of the industrial use of Java is in server-side
programming.
Appendices
Appendix A lists character escape sequences and the Basic
Latin and Latin-1 subsets
of Unicode. Appendices B and C summarize Java reserved
words and operators.
Appendix D documents all of the library methods and classes
used in this book.
Additional appendices contain quick references on Java syntax,
HTML, Java
tools, binary numbers, and UML.
Appendix L contains a style guide for use with this book. Many
instructors find
it highly beneficial to require a consistent style for all
assignments. If this style
guide conflicts with instructor sentiment or local customs,
however, it is available in
electronic form so that it can be modified.
Web Resources
This book is complemented by a complete suite of online
resources and a robust
WileyPLUS course.
Go to
www.wiley.com/college/horstmann
to visit the online companion site, which
includes
• Source code for all examples in the book.
• Worked Examples that apply the problem-solving steps in the
book to other
realistic examples.
• Laboratory exercises (and solutions for instructors only).
• Lecture presentation slides (in HTML and PowerPoint
formats).
•
Solution
s to all review and programming exercises (for instructors
only).
• A test bank that focuses on skills, not just terminology (for
instructors only).
WileyPLUS
is an online teaching and learning environment that integrates
the
digital textbook with instructor and student resources. See page
xvi for details.
• Worked Example How Many Days Have You Been Alive?
• Worked Example Working with Pictures
• Lab Exercises
Animation Variable Initialization and Assignment
Animation Parameter Passing
Animation Object References
Practice Quiz
Code Completion Exercises
Media Resources
www.wiley.com/
college/
horstmann
Web resources are summarized at
chapter end for easy reference.
bj4_fm.fm Page xi Saturday, November 7, 2009 12:01 PM
xii
Walkthrough
The pedagogical elements in this book work together to make
the book accessible
to beginners as well as those learning Java as a second
language.
A Walkthrough of the Learning Aids
2.3 The Assignment Operator 39
You can change the value of a variable with the assignment
operator (=). For exam-
ple, consider the variable declaration
int width = 10;
If you want to change the value of the variable, simply assign
the new value:
width = 20;
The assignment replaces the original value of the variable (see
Figure 1).
It is an error to use a variable that has never had a value
assigned to it. For exam-
ple, the following assignment statement has an error:
int height;
width = height; // ERROR—uninitialized variable height
The compiler will complain about an “uninitialized variable”
when you use a vari-
able that has never been assigned a value. (See Figure 2.)
2.3 The Assignment Operator
Use the assignment
operator (=) to
change the value
of a variable. 1
2
Figure 1
Assigning a New
Value to a Variable
width = 10
width = 20
1
2
Figure 2
An Uninitialized
Variable
Syntax 2.2 Assignment
height =
No value has been assigned.
variableName = value;Syntax
Example
double width = 20;
.
.
width = 30;
.
.
.
width = width + 10;
The value of this variable is changed.
The same name
can occur on both sides.
See Figure 3.
The new value of the variable
This is a variable declaration.
This is an assignment statement.
Annotations explain
required components
and point to more information
on common errors or best practices
associated with the syntax.
Throughout each chapter,
margin notes show where
new concepts are introduced
and provide an outline of key ideas.
Annotated syntax boxes
provide a quick, visual overview
of new language constructs.
Explain the flow of execution in a loop.
• A while statement executes a block of code repeatedly. A
condition controls for how
long the loop is executed.
• An off-by-one error is a common error when programming
loops. Think through
simple test cases to avoid this type of error.
Use for loops to implement counting loops.
• You use a for loop when a variable runs from a starting to an
ending value with a
constant increment or decrement.
• Make a choice between symmetric and asymmetric loop
bounds.
• Count the number of iterations to check that your for loop is
correct.
Implement loops that process a data set until a sentinel value is
encountered.
• Sometimes, the termination condition of a loop can only be
evaluated in the middle
of a loop. You can introduce a Boolean variable to control such
a loop.
Use nested loops to implement multiple levels of iterations.
• When the body of a loop contains another loop, the loops are
nested. A typical use
of nested loops is printing a table with rows and columns.
Summary of Learning Objectives
Each section corresponds to a
learning objective, summarized at
chapter end, giving students
a roadmap for assessing what they
know and what they need to review.
bj4_fm.fm Page xii Saturday, November 7, 2009 12:01 PM
Walkthrough
xiii
180 Decisions
Table 1 Relational Operator Examples
tnemmoCeulaVnoisserpxE
eurt4 =< 3 3 is less than 4; <= tests for “less than or equal”.
3 =< 4 Error The “less than or equal” operator is <=, not =<,
with the “less than” symbol first.
eslaf4 > 3 > is the opposite of <=.
eslaf4 < 4 The left-hand side must be strictly smaller than
the right-hand side.
eurt4 =< 4 Both sides are equal; <= tests for “less than or
equal”.
eurt2 - 5 == 3 == tests for equality.
eurt1 - 5 =! 3 != tests for inequality. It is true that 3 is not 5 –
1.
3 = 6 / 2 Error Use == to test for equality.
1.0 / 3.0 == 0.333333333 false Although the values are very
close to one
another, they are not exactly equal. See
Common Error 4.3.
"10" > 5 Error You cannot compare a string to a number.
"Tomato".substring(0, 3).equals("Tom") true Always use the
equals method to check whether
two strings have the same contents.
"Tomato".substring(0, 3) == ("Tom") false Never use == to
compare strings; it only checks
whether the strings are stored in the same
location. See Common Error 5.2 on page 180.
"Tom".equalsIgnoreCase("TOM") true Use the
equalsIgnoreCase method if you don’t want to
distinguish between uppercase and lowercase letters.
We simply want to know which car is the better buy. That is the
desired output.
Step 2 Break down the problem into smaller tasks.
For each car, we need to know the total cost of driving it. Let’s
do this computation sepa-
rately for each car. Once we have the total cost for each car, we
can decide which car is the
better deal.
The total cost for each car is purchase price + operating cost.
We assume a constant usage and gas price for ten years, so the
operating cost depends on the
cost of driving the car for one year.
The operating cost is 10 x annual fuel cost.
The annual fuel cost is price per gallon x annual fuel consumed.
The annual fuel consumed is annual miles driven / fuel
efficiency. For example, if you drive the car
for 15,000 miles and the fuel efficiency is 15 miles/gallon, the
car consumes 1,000 gallons.
Step 3 Describe each subtask in pseudocode.
In your description, arrange the steps so that any intermediate
values are computed before
they are needed in other computations. For example, list the
step
total cost = purchase price + operating cost
after you have computed operating cost.
Here is the algorithm for deciding which car to buy.
For each car, compute the total cost as follows:
annual fuel consumed = annual miles driven / fuel efficiency
annual fuel cost = price per gallon x annual fuel consumed
operating cost = 10 x annual fuel cost
total cost = purchase price + operating cost
If total cost1 < total cost2
Choose car1.
Else
Choose car2.
HOW TO 1.1 Developing and Describing an Algorithm
This is the first of many “How To” sections in this book that
give you step-by-step proce-
dures for carrying out important tasks in developing computer
programs.
Before you are ready to write a program in Java, you need to
develop an algorithm—a
method for arriving at a solution for a particular problem.
Describe the algorithm in
pseudocode: a sequence of precise steps formulated in English.
For example, consider this problem: You have the choice of
buying two cars. One is more
fuel efficient than the other, but also more expensive. You know
the price and fuel efficiency
(in miles per gallon, mpg) of both cars. You plan to keep the car
for ten years. Assume a price
of $4 per gallon of gas and usage of 15,000 miles per year. You
will pay cash for the car and
not worry about financing costs. Which car is the better deal?
Step 1 Determine the inputs and outputs.
In our sample problem, we have these inputs:
• purchase price1 and fuel efficiency1, the price and fuel
efficiency (in mpg) of the first car.
• purchase price2 and fuel efficiency2, the price and fuel
efficiency of the second car.
How To guides give step-by-step
guidance for common programming
tasks, emphasizing planning and
testing. They answer the beginner’s
question, “Now what do I do?” and
integrate key concepts into a
problem-solving sequence.
Example tables support beginners
with multiple, concrete examples.
These tables point out common
errors and present another quick
reference to the section’s topic.
Worked Examples apply the steps in
the How To to a different example,
illustrating how they can be used to
plan, implement, and test a solution
to another programming problem.
Credit Card Processing
This Worked Example uses a loop to remove spaces from a
credit
card number.
Worked
Example 6.1
Writing an Algorithm for Tiling a Floor
This Worked Example shows how to develop an algorithm for
laying tile in
an alternating pattern of colors.
Worked
Example 1.1
bj4_fm.fm Page xiii Saturday, November 7, 2009 12:01 PM
xiv
Walkthrough
Now consider the seemingly analogous code with Rectangle
objects (see
Figure 21).
Rectangle box = new Rectangle(5, 10, 20, 30);
Rectangle box2 = box;
box2.translate(15, 25);
Since box and box2 refer to the same rectangle after step , both
variables refer to
the moved rectangle after the call to the translate method.
You need not worry too much about the difference between
objects and object
references. Much of the time, you will have the correct intuition
when you think of
“the object box” rather than the technically more accurate “the
object reference
stored in box”. The difference between objects and object
references only becomes
apparent when you have multiple variables that refer to the
same object.
25. What is the effect of the assignment String greeting2 =
greeting?
26. After calling greeting2.toUpperCase(), what are the contents
of greeting and
greeting2?
Figure 21 Copying Object References
box =
box2 =
x =
Rectangle
y =
width =
height =
5
10
20
g
30
box =
box2 =
x =
Rectangle
y =
width =
height =
20
35
20
g
30
box =
x =
Rectangle
y =
width =
height =
5
10
20
g
30
1
2
3
1
2
3A N I M A T I O N
Object References
2
S E L F C H E C K
6.2 for Loops 205
ch06/invest2/Investment.java
1 /**
2 A class to monitor the growth of an investment that
3 accumulates interest at a fixed annual rate.
4 */
5 public class Investment
6 {
7 private double balance;
8 private double rate;
9 private int years;
10
11 /**
12 Constructs an Investment object from a starting balance and
13 interest rate.
14 @param aBalance the starting balance
15 @param aRate the interest rate in percent
16 */
17 public Investment(double aBalance, double aRate)
18 {
19 balance = aBalance;
20 rate = aRate;
21 years = 0;
22 }
23
24 /**
25 Keeps accumulating interest until a target balance has
26 been reached.
27 @param targetBalance the desired balance
28 */
Program listings are carefully
designed for easy reading,
going well beyond simple
color coding. Methods are set
off by a subtle outline.
4. What is the difference between the following two statements?
final double CM_PER_INCH = 2.54;
and
public static final double CM_PER_INCH = 2.54;
5. What is wrong with the following statement sequence?
double diameter = . . .;
double circumference = 3.14 * diameter;
S E L F C H E C K
Figure 4 Execution of a for Loop
for (int i = 1; i <= numberOfYears; i++)
{
double interest = balance * rate / 100;
balance = balance + interest;
}
Initialize counter1
for (int i = 1; i <= numberOfYears; i++)
{
double interest = balance * rate / 100;
balance = balance + interest;
}
Check condition2
for (int i = 1; i <= numberOfYears; i++)
{
double interest = balance * rate / 100;
balance = balance + interest;
}
Execute loop body3
for (int i = 1; i <= numberOfYears; i++)
{
double interest = balance * rate / 100;
balance = balance + interest;
}
Update counter4
for (int i = 1; i <= numberOfYears; i++)
{
double interest = balance * rate / 100;
balance = balance + interest;
}
Check condition again5
i = 1
i = 1
i = 1
i = 2
i = 2
Progressive figures trace code
segments to help students visualize
the program flow. Color is used
consistently to make variables and
other elements easily recognizable.
Self-check exercises at the
end of each section are designed
to make students think through
the new material—and can
spark discussion in lecture.
Students can view animations
of key concepts on the Web.
bj4_fm.fm Page xiv Saturday, November 7, 2009 12:01 PM
Walkthrough
xv
Length and Size
Unfortunately, the Java syntax for determining
the number of elements in an array, an array list,
and a string is not at all consistent. It is a com-
mon error to confuse these. You just have to
remember the correct syntax for every data type.
Common Error 7.3
Data Type Number of Elements
Array a.length
Array list a.size()
String a.length()
;
Do Not Use Magic Numbers
A magic number is a numeric constant that appears in your code
without explanation. For
example, consider the following scary example that actually
occurs in the Java library source:
h = 31 * h + ch;
Why 31? The number of days in January? One less than the
number of bits in an integer?
Actually, this code computes a “hash code” from a string—a
number that is derived from the
characters in such a way that different strings are likely to yield
different hash codes. The
value 31 turns out to scramble the character values nicely.
A better solution is to use a named constant:
final int HASH_MULTIPLIER = 31;
h = HASH_MULTIPLIER * h + ch;
You should never use magic numbers in your code. Any number
that is not completely self-
explanatory should be declared as a named constant. Even the
most reasonable cosmic con-
stant is going to change one day. You think there are 365 days
in a year? Your customers on
Mars are going to be pretty unhappy about your silly prejudice.
Make a constant
final int DAYS_PER_YEAR = 365;
By the way, the device
final int …
Project Report Phase 1
Deadline:Thursday 25/02/2021 @ 23:59
[Total Mark for this project is 5]
Business Computer Languages
IT401
College of Computing and Informatics
pg. 4I. Project Description:
This project is about Find the Roots of a Quadratic Equation.
The standard form of a quadratic equation is:
ax2 + bx + c = 0, where
a, b and c are real numbers and
a != 0
The term b2-4ac is known as the discriminant of a quadratic
equation. It tells the nature of the roots.
1. If the discriminant is greater than 0, the roots are real and
different.
2. If the discriminant is equal to 0, the roots are real and equal.
3. If the discriminant is less than 0, the equation has no real
root.
II. Project Phase 1 questions:
In the first phase of this project, you are requested to
1. Write an algorithm for a quadratic equation solver.
2. Implement the class Main with the main method. Declare the
variables and compute the discriminant.
3. After computing the discriminant value, insert the following
code after completing the missing instructions. Don’t forget to
add comments.
if (discriminant > 0) {
}
else if (discriminant == 0) {
}
else {
}
Example:
If a, b, and c are set to 3, 1 and 2 respectively, the equation has
no real root.
III. Marking Criteria
Criteria
Marks
The program is bugs-free
/5
The source code is well documented (commented) and program
uses standard Java naming conventions
/5
Question 1
/10
Question 2
/10
Question 3
/10
Output screenshots provided in the report
/10
Total
/50
Final Grade
/5
Answer
1. Brief description
Provide a brief description of your program in this section.
2. Algorithm
Provide the algorithm for the quadratic equation solver
3. Program code
Put the code of your program in this section. Do not forget to
document (comment) your code.
4. Screenshots
Put the different screenshots with a brief description in this
section.
5. Difficulties Faced
Provide a brief description of difficulties and challenges faced
during this phase of the project.
Bj4 fm.fm  page iv  saturday, november 7, 2009  1201 pm

More Related Content

What's hot

Virtual classroom business models
Virtual classroom business modelsVirtual classroom business models
Virtual classroom business modelsTerry Vyas
 
Video Conferencing in BUSCIT
Video Conferencing in BUSCITVideo Conferencing in BUSCIT
Video Conferencing in BUSCITVideoguy
 
Model Technology Enhanced Classrooms
Model Technology Enhanced ClassroomsModel Technology Enhanced Classrooms
Model Technology Enhanced ClassroomsBCcampus
 
University of the Highlands and Islands, Business and Leisure, Video-conferen...
University of the Highlands and Islands, Business and Leisure, Video-conferen...University of the Highlands and Islands, Business and Leisure, Video-conferen...
University of the Highlands and Islands, Business and Leisure, Video-conferen...Rob Macpherson
 
02 introduction information
02 introduction information02 introduction information
02 introduction informationJerry Arnold
 
Educational technology world_wide_web1
Educational technology world_wide_web1Educational technology world_wide_web1
Educational technology world_wide_web1Lyn Len Mercado
 
Intc 3610 syllabus spring 2011
Intc 3610 syllabus spring 2011Intc 3610 syllabus spring 2011
Intc 3610 syllabus spring 2011dharvey100
 
541 video enhanced lesson
541 video enhanced lesson541 video enhanced lesson
541 video enhanced lessontdsparks3
 
Lessons Learned: Implementation of a Virtual Classroom
Lessons Learned: Implementation of a Virtual ClassroomLessons Learned: Implementation of a Virtual Classroom
Lessons Learned: Implementation of a Virtual Classroomahornton
 
Best Practices For Delivering Virtual Classroom Training
Best Practices For Delivering Virtual Classroom TrainingBest Practices For Delivering Virtual Classroom Training
Best Practices For Delivering Virtual Classroom TrainingFareeza Marican
 
1:1 Laptop Programs
1:1 Laptop Programs1:1 Laptop Programs
1:1 Laptop Programsvblackston
 
Anna Levick, New College Pontefract alternative approaches to assessing & p...
Anna Levick, New College Pontefract   alternative approaches to assessing & p...Anna Levick, New College Pontefract   alternative approaches to assessing & p...
Anna Levick, New College Pontefract alternative approaches to assessing & p...JISC Regional Support Centre
 
Can You Hear Us? (mid year report)
Can You Hear Us? (mid year report)Can You Hear Us? (mid year report)
Can You Hear Us? (mid year report)michael chalk
 
Forum powerpoint vuc3
Forum powerpoint vuc3Forum powerpoint vuc3
Forum powerpoint vuc3bobkeith
 
Virtual Classroom
Virtual ClassroomVirtual Classroom
Virtual Classroomtech4101
 
ATLIS 2016 - Collaborating with Developers to Create New Tools
ATLIS 2016 - Collaborating with Developers to Create New ToolsATLIS 2016 - Collaborating with Developers to Create New Tools
ATLIS 2016 - Collaborating with Developers to Create New ToolsSwift Education Systems
 
CE_2423_Photoshop_Seabo
CE_2423_Photoshop_SeaboCE_2423_Photoshop_Seabo
CE_2423_Photoshop_SeaboBancroft
 
Virtual classroom
Virtual classroomVirtual classroom
Virtual classroomkhalid adam
 

What's hot (20)

Virtual classroom business models
Virtual classroom business modelsVirtual classroom business models
Virtual classroom business models
 
Video Conferencing in BUSCIT
Video Conferencing in BUSCITVideo Conferencing in BUSCIT
Video Conferencing in BUSCIT
 
VIRTUAL CLASSROOM
VIRTUAL CLASSROOMVIRTUAL CLASSROOM
VIRTUAL CLASSROOM
 
Model Technology Enhanced Classrooms
Model Technology Enhanced ClassroomsModel Technology Enhanced Classrooms
Model Technology Enhanced Classrooms
 
University of the Highlands and Islands, Business and Leisure, Video-conferen...
University of the Highlands and Islands, Business and Leisure, Video-conferen...University of the Highlands and Islands, Business and Leisure, Video-conferen...
University of the Highlands and Islands, Business and Leisure, Video-conferen...
 
02 introduction information
02 introduction information02 introduction information
02 introduction information
 
Educational technology world_wide_web1
Educational technology world_wide_web1Educational technology world_wide_web1
Educational technology world_wide_web1
 
Intc 3610 syllabus spring 2011
Intc 3610 syllabus spring 2011Intc 3610 syllabus spring 2011
Intc 3610 syllabus spring 2011
 
541 video enhanced lesson
541 video enhanced lesson541 video enhanced lesson
541 video enhanced lesson
 
June7
June7June7
June7
 
Lessons Learned: Implementation of a Virtual Classroom
Lessons Learned: Implementation of a Virtual ClassroomLessons Learned: Implementation of a Virtual Classroom
Lessons Learned: Implementation of a Virtual Classroom
 
Best Practices For Delivering Virtual Classroom Training
Best Practices For Delivering Virtual Classroom TrainingBest Practices For Delivering Virtual Classroom Training
Best Practices For Delivering Virtual Classroom Training
 
1:1 Laptop Programs
1:1 Laptop Programs1:1 Laptop Programs
1:1 Laptop Programs
 
Anna Levick, New College Pontefract alternative approaches to assessing & p...
Anna Levick, New College Pontefract   alternative approaches to assessing & p...Anna Levick, New College Pontefract   alternative approaches to assessing & p...
Anna Levick, New College Pontefract alternative approaches to assessing & p...
 
Can You Hear Us? (mid year report)
Can You Hear Us? (mid year report)Can You Hear Us? (mid year report)
Can You Hear Us? (mid year report)
 
Forum powerpoint vuc3
Forum powerpoint vuc3Forum powerpoint vuc3
Forum powerpoint vuc3
 
Virtual Classroom
Virtual ClassroomVirtual Classroom
Virtual Classroom
 
ATLIS 2016 - Collaborating with Developers to Create New Tools
ATLIS 2016 - Collaborating with Developers to Create New ToolsATLIS 2016 - Collaborating with Developers to Create New Tools
ATLIS 2016 - Collaborating with Developers to Create New Tools
 
CE_2423_Photoshop_Seabo
CE_2423_Photoshop_SeaboCE_2423_Photoshop_Seabo
CE_2423_Photoshop_Seabo
 
Virtual classroom
Virtual classroomVirtual classroom
Virtual classroom
 

Similar to Bj4 fm.fm page iv saturday, november 7, 2009 1201 pm

Collaborative learning presentation
Collaborative learning presentationCollaborative learning presentation
Collaborative learning presentationShiKia Carter
 
Brightspace Michigan Connection Opening Session
Brightspace Michigan Connection Opening SessionBrightspace Michigan Connection Opening Session
Brightspace Michigan Connection Opening SessionD2L Barry
 
What is web lessons
What is web lessonsWhat is web lessons
What is web lessonsJennifer
 
What is web lessons
What is web lessonsWhat is web lessons
What is web lessonsJennifer
 
What is web lessons
What is web lessonsWhat is web lessons
What is web lessonsJennifer
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
History of call final report
History of call final reportHistory of call final report
History of call final reportj7045900
 
Ed tech 522 syllabus
Ed tech 522 syllabusEd tech 522 syllabus
Ed tech 522 syllabusloraevanouski
 
NASA Etoys In Space Usability Evaluation
NASA Etoys In Space Usability EvaluationNASA Etoys In Space Usability Evaluation
NASA Etoys In Space Usability EvaluationMike Lee
 
Prin itppt k_texler_v2_062609
Prin itppt k_texler_v2_062609Prin itppt k_texler_v2_062609
Prin itppt k_texler_v2_062609NAFCareerAcads
 
Faculty focus special report online course design 13 strategies for teaching ...
Faculty focus special report online course design 13 strategies for teaching ...Faculty focus special report online course design 13 strategies for teaching ...
Faculty focus special report online course design 13 strategies for teaching ...Dillard University Library
 
Click the link above to submit this assignment.Assignment .docx
Click the link above to submit this assignment.Assignment .docxClick the link above to submit this assignment.Assignment .docx
Click the link above to submit this assignment.Assignment .docxbartholomeocoombs
 
Student Survey Nov 2022
Student Survey Nov 2022Student Survey Nov 2022
Student Survey Nov 2022Peter Windle
 
Telecommunications Course Outline for Media Literacy
Telecommunications Course Outline for Media LiteracyTelecommunications Course Outline for Media Literacy
Telecommunications Course Outline for Media LiteracyJennifer McBrayer
 
10 Great Apps for the Classroom
10 Great Apps for the Classroom10 Great Apps for the Classroom
10 Great Apps for the ClassroomDChristly
 

Similar to Bj4 fm.fm page iv saturday, november 7, 2009 1201 pm (20)

Software Development Fundamentals Exam 98-361
Software Development Fundamentals Exam 98-361Software Development Fundamentals Exam 98-361
Software Development Fundamentals Exam 98-361
 
Collaborative learning presentation
Collaborative learning presentationCollaborative learning presentation
Collaborative learning presentation
 
Brightspace Michigan Connection Opening Session
Brightspace Michigan Connection Opening SessionBrightspace Michigan Connection Opening Session
Brightspace Michigan Connection Opening Session
 
What is web lessons
What is web lessonsWhat is web lessons
What is web lessons
 
What is web lessons
What is web lessonsWhat is web lessons
What is web lessons
 
What is web lessons
What is web lessonsWhat is web lessons
What is web lessons
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
E learning website
E  learning websiteE  learning website
E learning website
 
Open Campus Online Course Syllabus_16week
Open Campus Online Course Syllabus_16weekOpen Campus Online Course Syllabus_16week
Open Campus Online Course Syllabus_16week
 
History of call final report
History of call final reportHistory of call final report
History of call final report
 
Ed tech 522 syllabus
Ed tech 522 syllabusEd tech 522 syllabus
Ed tech 522 syllabus
 
NASA Etoys In Space Usability Evaluation
NASA Etoys In Space Usability EvaluationNASA Etoys In Space Usability Evaluation
NASA Etoys In Space Usability Evaluation
 
Prin itppt k_texler_v2_062609
Prin itppt k_texler_v2_062609Prin itppt k_texler_v2_062609
Prin itppt k_texler_v2_062609
 
Faculty focus special report online course design 13 strategies for teaching ...
Faculty focus special report online course design 13 strategies for teaching ...Faculty focus special report online course design 13 strategies for teaching ...
Faculty focus special report online course design 13 strategies for teaching ...
 
Click the link above to submit this assignment.Assignment .docx
Click the link above to submit this assignment.Assignment .docxClick the link above to submit this assignment.Assignment .docx
Click the link above to submit this assignment.Assignment .docx
 
Student Survey Nov 2022
Student Survey Nov 2022Student Survey Nov 2022
Student Survey Nov 2022
 
Telecommunications Course Outline for Media Literacy
Telecommunications Course Outline for Media LiteracyTelecommunications Course Outline for Media Literacy
Telecommunications Course Outline for Media Literacy
 
Media Usability Studies Syllabus
Media Usability Studies Syllabus Media Usability Studies Syllabus
Media Usability Studies Syllabus
 
10 Great Apps for the Classroom
10 Great Apps for the Classroom10 Great Apps for the Classroom
10 Great Apps for the Classroom
 
VIRTUAL CLASSROOM
VIRTUAL CLASSROOMVIRTUAL CLASSROOM
VIRTUAL CLASSROOM
 

More from honey690131

PaperSelect one of the quality topics in healthcare from th.docx
PaperSelect one of the quality topics in healthcare from th.docxPaperSelect one of the quality topics in healthcare from th.docx
PaperSelect one of the quality topics in healthcare from th.docxhoney690131
 
Part 1 - Microsoft AccessView GlossaryUse Access to create a.docx
Part 1 - Microsoft AccessView GlossaryUse Access to create a.docxPart 1 - Microsoft AccessView GlossaryUse Access to create a.docx
Part 1 - Microsoft AccessView GlossaryUse Access to create a.docxhoney690131
 
Part 1 - Microsoft Access 2019Use Access to create a database to.docx
Part 1 - Microsoft Access 2019Use Access to create a database to.docxPart 1 - Microsoft Access 2019Use Access to create a database to.docx
Part 1 - Microsoft Access 2019Use Access to create a database to.docxhoney690131
 
ParkinsonsPathophysiology, progression of disease, complication.docx
ParkinsonsPathophysiology, progression of disease, complication.docxParkinsonsPathophysiology, progression of disease, complication.docx
ParkinsonsPathophysiology, progression of disease, complication.docxhoney690131
 
Parenting Practices among DepressedMothers in the Child Welf.docx
Parenting Practices among DepressedMothers in the Child Welf.docxParenting Practices among DepressedMothers in the Child Welf.docx
Parenting Practices among DepressedMothers in the Child Welf.docxhoney690131
 
Parental InfluencesMerging science and business, selective bre.docx
Parental InfluencesMerging science and business, selective bre.docxParental InfluencesMerging science and business, selective bre.docx
Parental InfluencesMerging science and business, selective bre.docxhoney690131
 
Paragraph Structure with Use of Text(P) Topic Sentence-(I).docx
Paragraph Structure with Use of Text(P) Topic Sentence-(I).docxParagraph Structure with Use of Text(P) Topic Sentence-(I).docx
Paragraph Structure with Use of Text(P) Topic Sentence-(I).docxhoney690131
 
Paper should explain the difficulties on the Use of government trave.docx
Paper should explain the difficulties on the Use of government trave.docxPaper should explain the difficulties on the Use of government trave.docx
Paper should explain the difficulties on the Use of government trave.docxhoney690131
 
paper should be between 750 – 1500 words. APA formatting is required.docx
paper should be between 750 – 1500 words. APA formatting is required.docxpaper should be between 750 – 1500 words. APA formatting is required.docx
paper should be between 750 – 1500 words. APA formatting is required.docxhoney690131
 
Paper Requirements 4 pages (including title page, 2 pages .docx
Paper Requirements 4 pages (including title page, 2 pages .docxPaper Requirements 4 pages (including title page, 2 pages .docx
Paper Requirements 4 pages (including title page, 2 pages .docxhoney690131
 
Paper RequirementsRequired topic headings for your paper shou.docx
Paper RequirementsRequired topic headings for your paper shou.docxPaper RequirementsRequired topic headings for your paper shou.docx
Paper RequirementsRequired topic headings for your paper shou.docxhoney690131
 
Paper must be double spaced, with 12 point font and include section .docx
Paper must be double spaced, with 12 point font and include section .docxPaper must be double spaced, with 12 point font and include section .docx
Paper must be double spaced, with 12 point font and include section .docxhoney690131
 
Paper OrganizationStart with a title page and organize your pa.docx
Paper OrganizationStart with a title page and organize your pa.docxPaper OrganizationStart with a title page and organize your pa.docx
Paper OrganizationStart with a title page and organize your pa.docxhoney690131
 
Paper on topic  Date visualization A critical evaluation of its ar.docx
Paper on topic  Date visualization A critical evaluation of its ar.docxPaper on topic  Date visualization A critical evaluation of its ar.docx
Paper on topic  Date visualization A critical evaluation of its ar.docxhoney690131
 
PAPER EXPECTATIONSFollow the instructions.Make your ideas .docx
PAPER EXPECTATIONSFollow the instructions.Make your ideas .docxPAPER EXPECTATIONSFollow the instructions.Make your ideas .docx
PAPER EXPECTATIONSFollow the instructions.Make your ideas .docxhoney690131
 
Paper Instructions 5) Paper should be 5-7 pages (excluding title pag.docx
Paper Instructions 5) Paper should be 5-7 pages (excluding title pag.docxPaper Instructions 5) Paper should be 5-7 pages (excluding title pag.docx
Paper Instructions 5) Paper should be 5-7 pages (excluding title pag.docxhoney690131
 
Paper format and information4-5 pages in length.Papers mu.docx
Paper format and information4-5 pages in length.Papers mu.docxPaper format and information4-5 pages in length.Papers mu.docx
Paper format and information4-5 pages in length.Papers mu.docxhoney690131
 
Paper in Health care quality management strategies - recent arti.docx
Paper in Health care quality management strategies - recent arti.docxPaper in Health care quality management strategies - recent arti.docx
Paper in Health care quality management strategies - recent arti.docxhoney690131
 
Paper 2 Assignment POT 2002.Assignment Write a 1000 wor.docx
Paper 2 Assignment POT 2002.Assignment Write a 1000 wor.docxPaper 2 Assignment POT 2002.Assignment Write a 1000 wor.docx
Paper 2 Assignment POT 2002.Assignment Write a 1000 wor.docxhoney690131
 
Paper detailsUnit 4 Discussion Prompt1. What is the .docx
Paper detailsUnit 4 Discussion Prompt1. What is the .docxPaper detailsUnit 4 Discussion Prompt1. What is the .docx
Paper detailsUnit 4 Discussion Prompt1. What is the .docxhoney690131
 

More from honey690131 (20)

PaperSelect one of the quality topics in healthcare from th.docx
PaperSelect one of the quality topics in healthcare from th.docxPaperSelect one of the quality topics in healthcare from th.docx
PaperSelect one of the quality topics in healthcare from th.docx
 
Part 1 - Microsoft AccessView GlossaryUse Access to create a.docx
Part 1 - Microsoft AccessView GlossaryUse Access to create a.docxPart 1 - Microsoft AccessView GlossaryUse Access to create a.docx
Part 1 - Microsoft AccessView GlossaryUse Access to create a.docx
 
Part 1 - Microsoft Access 2019Use Access to create a database to.docx
Part 1 - Microsoft Access 2019Use Access to create a database to.docxPart 1 - Microsoft Access 2019Use Access to create a database to.docx
Part 1 - Microsoft Access 2019Use Access to create a database to.docx
 
ParkinsonsPathophysiology, progression of disease, complication.docx
ParkinsonsPathophysiology, progression of disease, complication.docxParkinsonsPathophysiology, progression of disease, complication.docx
ParkinsonsPathophysiology, progression of disease, complication.docx
 
Parenting Practices among DepressedMothers in the Child Welf.docx
Parenting Practices among DepressedMothers in the Child Welf.docxParenting Practices among DepressedMothers in the Child Welf.docx
Parenting Practices among DepressedMothers in the Child Welf.docx
 
Parental InfluencesMerging science and business, selective bre.docx
Parental InfluencesMerging science and business, selective bre.docxParental InfluencesMerging science and business, selective bre.docx
Parental InfluencesMerging science and business, selective bre.docx
 
Paragraph Structure with Use of Text(P) Topic Sentence-(I).docx
Paragraph Structure with Use of Text(P) Topic Sentence-(I).docxParagraph Structure with Use of Text(P) Topic Sentence-(I).docx
Paragraph Structure with Use of Text(P) Topic Sentence-(I).docx
 
Paper should explain the difficulties on the Use of government trave.docx
Paper should explain the difficulties on the Use of government trave.docxPaper should explain the difficulties on the Use of government trave.docx
Paper should explain the difficulties on the Use of government trave.docx
 
paper should be between 750 – 1500 words. APA formatting is required.docx
paper should be between 750 – 1500 words. APA formatting is required.docxpaper should be between 750 – 1500 words. APA formatting is required.docx
paper should be between 750 – 1500 words. APA formatting is required.docx
 
Paper Requirements 4 pages (including title page, 2 pages .docx
Paper Requirements 4 pages (including title page, 2 pages .docxPaper Requirements 4 pages (including title page, 2 pages .docx
Paper Requirements 4 pages (including title page, 2 pages .docx
 
Paper RequirementsRequired topic headings for your paper shou.docx
Paper RequirementsRequired topic headings for your paper shou.docxPaper RequirementsRequired topic headings for your paper shou.docx
Paper RequirementsRequired topic headings for your paper shou.docx
 
Paper must be double spaced, with 12 point font and include section .docx
Paper must be double spaced, with 12 point font and include section .docxPaper must be double spaced, with 12 point font and include section .docx
Paper must be double spaced, with 12 point font and include section .docx
 
Paper OrganizationStart with a title page and organize your pa.docx
Paper OrganizationStart with a title page and organize your pa.docxPaper OrganizationStart with a title page and organize your pa.docx
Paper OrganizationStart with a title page and organize your pa.docx
 
Paper on topic  Date visualization A critical evaluation of its ar.docx
Paper on topic  Date visualization A critical evaluation of its ar.docxPaper on topic  Date visualization A critical evaluation of its ar.docx
Paper on topic  Date visualization A critical evaluation of its ar.docx
 
PAPER EXPECTATIONSFollow the instructions.Make your ideas .docx
PAPER EXPECTATIONSFollow the instructions.Make your ideas .docxPAPER EXPECTATIONSFollow the instructions.Make your ideas .docx
PAPER EXPECTATIONSFollow the instructions.Make your ideas .docx
 
Paper Instructions 5) Paper should be 5-7 pages (excluding title pag.docx
Paper Instructions 5) Paper should be 5-7 pages (excluding title pag.docxPaper Instructions 5) Paper should be 5-7 pages (excluding title pag.docx
Paper Instructions 5) Paper should be 5-7 pages (excluding title pag.docx
 
Paper format and information4-5 pages in length.Papers mu.docx
Paper format and information4-5 pages in length.Papers mu.docxPaper format and information4-5 pages in length.Papers mu.docx
Paper format and information4-5 pages in length.Papers mu.docx
 
Paper in Health care quality management strategies - recent arti.docx
Paper in Health care quality management strategies - recent arti.docxPaper in Health care quality management strategies - recent arti.docx
Paper in Health care quality management strategies - recent arti.docx
 
Paper 2 Assignment POT 2002.Assignment Write a 1000 wor.docx
Paper 2 Assignment POT 2002.Assignment Write a 1000 wor.docxPaper 2 Assignment POT 2002.Assignment Write a 1000 wor.docx
Paper 2 Assignment POT 2002.Assignment Write a 1000 wor.docx
 
Paper detailsUnit 4 Discussion Prompt1. What is the .docx
Paper detailsUnit 4 Discussion Prompt1. What is the .docxPaper detailsUnit 4 Discussion Prompt1. What is the .docx
Paper detailsUnit 4 Discussion Prompt1. What is the .docx
 

Recently uploaded

9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 

Recently uploaded (20)

9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 

Bj4 fm.fm page iv saturday, november 7, 2009 1201 pm

  • 1. bj4_fm.fm Page iv Saturday, November 7, 2009 12:01 PM • Students achieve concept mastery in a rich, structured environment that’s available 24/7 From multiple study paths, to self-assessment, to a wealth of interactive visual and audio resources, WileyPLUS gives you everything you need to personalize the teaching and learning experience. With WileyPLUS: » F i n d o u t h ow t o M a k e I t Yo u r S » This online teaching and learning environment integrates the entire digital textbook with the most effective instructor and student resources to fit every learning style. • Instructors personalize and manage their course more effectively with assessment, assignments, grade
  • 2. tracking, and more • manage time better • study smarter • save money www.wileyplus.com WP5_FM_8x10.indd 1 8/7/09 11:36 AM Make It YourS! aLL The heLP, reSoUrceS, and PerSonaL SUPPorT yoU and yoUr STUdenTS need! technical Support 24/7 FaQs, online chat, and phone support www.wileyplus.com/suppor t Student support from an experienced student user ask your local representative for details! Your WileyPLUS account Manager training and implementation support www.wileyplus.com/accountmanager
  • 3. Collaborate with your colleagues, find a mentor, attend virtual and live events, and view resources www.WhereFacultyconnect.com Pre-loaded, ready-to-use assignments and presentations www.wiley.com/college/quickstar t 2-Minute tutorials and all of the resources you & your students need to get started www.wileyplus.com/firstday WP5_FM_8x10.indd 2 8/7/09 11:36 AM th edition 4 Big Java bj4_fm.fm Page iii Saturday, November 7, 2009 12:01 PM
  • 4. bj4_fm.fm Page iv Saturday, November 7, 2009 12:01 PM th edition 4 Big Java Cay Horstmann SAN JOSE STATE UNIVERSITY JOHN WILEY & SONS, INC. bj4_fm.fm Page v Saturday, November 7, 2009 12:01 PM VICE PRESIDENT AND EXECUTIVE PUBLISHER Donald Fowley EXECUTIVE EDITOR Beth Lang Golub EDITORIAL ASSISTANT Michael Berlin PRODUCTION SERVICES MANAGER Dorothy Sinclair PRODUCTION EDITOR Janet Foxman EXECUTIVE MARKETING MANAGER Christopher Ruel
  • 5. CREATIVE DIRECTOR Harry Nolan SENIOR DESIGNER Madelyn Lesure PHOTO EDITOR Lisa Gee MEDIA EDITOR Lauren Sapira PRODUCTION SERVICES Cindy Johnson COVER DESIGNER Howard Grossman COVER ILLUSTRATION Susan Cyr This book was set in Stempel Garamond by Publishing Services, and printed and bound by RRD Jefferson City. The cover was printed by RRD Jefferson City. This book is printed on acid-free paper. ∞ Copyright © 2010, 2008, 2006, 2002 John Wiley & Sons, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, Inc., 222 Rosewood Drive, Danvers, MA 01923, website www.copyright.com. Requests to the Publisher for per-
  • 6. mission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030-5774, (201) 748-6011, fax (201) 748-6008, website www.wiley.com/go/permissions. Evaluation copies are provided to qualified academics and professionals for review purposes only, for use in their courses during the next academic year. These copies are licensed and may not be sold or transferred to a third party. Upon completion of the review period, please return the evaluation copy to Wiley. Return instructions and a free of charge return shipping label are available at www.wiley.com/go/returnlabel. Outside of the United States, please contact your local representative. Library of Congress Cataloging-in-Publication Data: Horstmann, Cay S., 1959– Big Java : compatible with Java 5, 6 and 7 / Cay Horstmann. -- 4th ed. p. cm. Includes index. ISBN 978-0-470-50948-7 (pbk. : alk. paper) 1. Java (Computer program language) I. Title.
  • 7. QA76.73.J38H674 2010 005.13'3--dc22 2009042604 ISBN 978-0-470-50948-7 Printed in the United States of America 10 9 8 7 6 5 4 3 2 1 bj4_fm.fm Page vi Saturday, November 7, 2009 12:01 PM PREFACE vii This book is an introductory text in computer science, focusing on the principles of programming and software engineering. Here are its key features: • Teach objects gradually. In Chapter 2, students learn how to use objects and classes from the standard library. Chapter 3 shows the mechanics of implementing classes
  • 8. from a given specification . Students then use simple objects as they master branches, loops, and arrays. Object-oriented design starts in Chapter 8. This gradual approach allows students to use objects throughout their study of the core algorithmic topics, without teaching bad habits that must be un-learned later. • Reinforce sound engineering practices. A focus on test-driven development encourages students to test their programs systematically. A multitude of useful tips on software quality and common errors encourage the development of good programming habits. • Help students with guidance and worked examples. Beginning programmers often ask “How do I start? Now what do I do?” Of
  • 9. course, an activity as complex as programming cannot be reduced to cookbook- style instructions. However, step-by-step guidance is immensely helpful for building confidence and providing an outline for the task at hand. The book con- tains a large number of “How To” guides for common tasks, with pointers to additional worked examples on the Web. • Focus on the essentials while being technically accurate. An encyclopedic coverage is not helpful for a beginning programmer, but neither is the opposite—reducing the material to a list of simplistic bullet points that give an illusion of knowledge. In this book, the essentials of each subject are presented in digestible chunks, with separate notes that go deeper into good practices or lan- guage features when the reader is ready for the additional information. • Use standard Java. The book teaches the standard Java language —not a specialized
  • 10. “training wheels” environment. The Java language, library, and tools are presented at a depth that is sufficient to solve real-world programming problems. The final chapters of the book cover advanced techniques such as multithreading, database storage, XML, and web programming. • Provide an optional graphics track. Graphical shapes are splendid examples of objects. Many students enjoy writing programs that create drawings or use graphical user interfaces. If desired, these topics can be integrated into the course by using the materials at the end of Chapters 2, 3, 9, and 10. bj4_fm.fm Page vii Saturday, November 7, 2009 12:01 PM viii Preface
  • 11. This is the fourth edition of Big Java, and the book has once again been carefully revised and updated. The new and improved features include: • The How To sections have been updated and expanded, and four new ones have been added. Fifteen new Worked Examples (on the companion web site and in WileyPLUS) walk students through the steps required for solving complex and interesting problems. • The treatment of algorithm design, planning, and the use of pseudocode has been enhanced. Students learn to use pseudocode to define the solution algorithm in Chapter 1. • Chapters have been revised to focus each section on a specific learning objective. These learning objectives also organize the chapter summary to help students assess their progress. • Syntax diagrams now call out features of typical example code to draw student attention to the key elements of the syntax. Additional annotations point out special cases, common errors, and good practice associated with the syntax.
  • 12. • New example tables clearly present a variety of typical and special cases in a compact format. Each example is accompanied by a brief note explaining the usage shown and the values that result from it. • The gradual introduction of objects has been further improved by providing additional examples and insights in the early chapters. • Features introduced in Java 7 are covered as Special Topics so that students can prepare for them. In this edition, we use Java 5 or 6 for the main discussion. • The test bank has been greatly expanded and improved. (See page xi.) • A new set of lab assignments enables students to practice solving complex problems one step at a time. • The LabRat code evaluation feature, enhanced for this edition, gives students instant feedback on their programming assignments. (See page xvi.) New in This Edition More Help for Beginning Programmers Annotated Examples Updated for Java 7
  • 13. More Opportunities for Practice bj4_fm.fm Page viii Saturday, November 7, 2009 12:01 PM Preface ix The book can be naturally grouped into four parts, as illustrated by Figure 1. The organization of chapters offers the same flexibility as the previous edition; depen- dencies among the chapters are also shown in the figure. Part A: Fundamentals (Chapters 1–7) Chapter 1 contains a brief introduction to computer science and Java programming. Chapter 2 shows how to manipulate objects of predefined classes. In Chapter 3, you will build your own simple classes from given specifications. Fundamental data types, branches, loops, and arrays are covered in Chapters 4–7.
  • 14. Part B: Object-Oriented Design ( Chapters 8–12) Chapter 8 takes up the subject of class design in a systematic fashion, and it intro- duces a very simple subset of the UML notation. The discussion of polymorphis m and inheritance is split into two chapters. Chap- ter 9 covers interfaces and polymorphism, whereas Chapter 10 covers inheritance. Introducing interfaces before inheritance pays off in an important way: Students immediately see polymorphism before getting bogged down with technical details such as superclass construction. Exception handling and basic file input/output are covered in Chapter 11. The exception hierarchy gives a useful example for inheritance. Chapter 12 contains an introduction to object-oriented design, including two significant case studies. Part C: Data Structures and Algorithms (Chapters 13–17)
  • 15. Chapters 13 through 17 contain an introduction to algorithms and data structures, covering recursion, sorting and searching, linked lists, binary trees, and hash tables. These topics may be outside the scope of a one-semester course, but can be covered as desired after Chapter 7 (see Figure 1). Recursion is introduced from an object-oriented point of view: An object that solves a problem recursively constructs another object of the same class that solves a simpler problem. The idea of having the other object do the simpler job is more intuitive than having a function call itself. Each data structure is presented in the context of the standard Java collections library. You will learn the essential abstractions of the standard library (such as iterators, sets, and maps) as well as the performance characteristics of the various collections. However, a detailed discussion of the implementation of advanced data structures is beyond the scope of this book. Chapter 17 introduces Java generics. This chapter is suitable for advanced stu- dents who want to implement their own generic classes and methods. Part D: Advanced Topics
  • 16. (Chapters 18–24) Chapters 18 through 24 cover advanced Java programming techniques that defi- nitely go beyond a first course in Java. Although, as already mentioned, a compre- hensive coverage of the Java library would span many volumes, many instructors prefer that a textbook should give students additional reference material valuable beyond their first course. Some institutions also teach a second- semester course that A Tour of the Book bj4_fm.fm Page ix Saturday, November 7, 2009 12:01 PM x Preface Figure 1 Chapter Dependencies 4. Fundamental Data Types
  • 17. 5. Decisions 9. Interfaces and Polymorphism 10. Inheritance 11. Input/Output and Exception Handling 19. Streams and Binary I/O 20. Multithreading 12. Object- Oriented Design 22. Relational Databases 13. Recursion 14. Sorting and Searching 15. Intro to Data Structures 16. Advanced Data Structures 21. Internet
  • 18. Networking 23. XML 24. Web Applications 7. Arrrays and Array Lists 6. Iteration 8. Designing Classes 17. Generic Programming 3. Implementing Classes 1. Introduction 2. Using Objects Fundamentals Object-Oriented Design Data Structures & Algorithms Advanced Topics 18. Graphical User Interfaces
  • 19. bj4_fm.fm Page x Saturday, November 7, 2009 12:01 PM Preface xi covers more practical programming aspects such as database and network program- ming, rather than the more traditional in-depth material on data structures and algo- rithms. This book can be used in a two-semester course to give students an introduction to programming fundamentals and broad coverage of applications. Alternatively, the material in the final chapters can be useful for student projects. The advanced topics include graphical user-interface design, advanced file han- dling, multithreading, and those technologies that are of particular interest to server-side programming: networking, databases, XML, and web applications. The Internet has made it possible to deploy many useful applications on servers, often accessed by nothing more than a browser. This server-centric approach to applica- tion development was in part made possible by the Java language and libraries, and today, much of the industrial use of Java is in server-side
  • 20. programming. Appendices Appendix A lists character escape sequences and the Basic Latin and Latin-1 subsets of Unicode. Appendices B and C summarize Java reserved words and operators. Appendix D documents all of the library methods and classes used in this book. Additional appendices contain quick references on Java syntax, HTML, Java tools, binary numbers, and UML. Appendix L contains a style guide for use with this book. Many instructors find it highly beneficial to require a consistent style for all assignments. If this style guide conflicts with instructor sentiment or local customs, however, it is available in electronic form so that it can be modified. Web Resources This book is complemented by a complete suite of online resources and a robust WileyPLUS course. Go to
  • 21. www.wiley.com/college/horstmann to visit the online companion site, which includes • Source code for all examples in the book. • Worked Examples that apply the problem-solving steps in the book to other realistic examples. • Laboratory exercises (and solutions for instructors only). • Lecture presentation slides (in HTML and PowerPoint formats). • Solution s to all review and programming exercises (for instructors only). • A test bank that focuses on skills, not just terminology (for instructors only). WileyPLUS is an online teaching and learning environment that integrates the
  • 22. digital textbook with instructor and student resources. See page xvi for details. • Worked Example How Many Days Have You Been Alive? • Worked Example Working with Pictures • Lab Exercises Animation Variable Initialization and Assignment Animation Parameter Passing Animation Object References Practice Quiz Code Completion Exercises Media Resources www.wiley.com/ college/ horstmann Web resources are summarized at chapter end for easy reference. bj4_fm.fm Page xi Saturday, November 7, 2009 12:01 PM
  • 23. xii Walkthrough The pedagogical elements in this book work together to make the book accessible to beginners as well as those learning Java as a second language. A Walkthrough of the Learning Aids 2.3 The Assignment Operator 39 You can change the value of a variable with the assignment operator (=). For exam- ple, consider the variable declaration int width = 10;
  • 24. If you want to change the value of the variable, simply assign the new value: width = 20; The assignment replaces the original value of the variable (see Figure 1). It is an error to use a variable that has never had a value assigned to it. For exam- ple, the following assignment statement has an error: int height; width = height; // ERROR—uninitialized variable height The compiler will complain about an “uninitialized variable” when you use a vari- able that has never been assigned a value. (See Figure 2.) 2.3 The Assignment Operator Use the assignment operator (=) to change the value of a variable. 1 2
  • 25. Figure 1 Assigning a New Value to a Variable width = 10 width = 20 1 2 Figure 2 An Uninitialized Variable Syntax 2.2 Assignment height = No value has been assigned. variableName = value;Syntax Example
  • 26. double width = 20; . . width = 30; . . . width = width + 10; The value of this variable is changed. The same name can occur on both sides. See Figure 3. The new value of the variable This is a variable declaration. This is an assignment statement. Annotations explain required components
  • 27. and point to more information on common errors or best practices associated with the syntax. Throughout each chapter, margin notes show where new concepts are introduced and provide an outline of key ideas. Annotated syntax boxes provide a quick, visual overview of new language constructs. Explain the flow of execution in a loop. • A while statement executes a block of code repeatedly. A condition controls for how long the loop is executed. • An off-by-one error is a common error when programming loops. Think through simple test cases to avoid this type of error. Use for loops to implement counting loops.
  • 28. • You use a for loop when a variable runs from a starting to an ending value with a constant increment or decrement. • Make a choice between symmetric and asymmetric loop bounds. • Count the number of iterations to check that your for loop is correct. Implement loops that process a data set until a sentinel value is encountered. • Sometimes, the termination condition of a loop can only be evaluated in the middle of a loop. You can introduce a Boolean variable to control such a loop. Use nested loops to implement multiple levels of iterations. • When the body of a loop contains another loop, the loops are nested. A typical use of nested loops is printing a table with rows and columns. Summary of Learning Objectives
  • 29. Each section corresponds to a learning objective, summarized at chapter end, giving students a roadmap for assessing what they know and what they need to review. bj4_fm.fm Page xii Saturday, November 7, 2009 12:01 PM Walkthrough xiii 180 Decisions Table 1 Relational Operator Examples tnemmoCeulaVnoisserpxE
  • 30. eurt4 =< 3 3 is less than 4; <= tests for “less than or equal”. 3 =< 4 Error The “less than or equal” operator is <=, not =<, with the “less than” symbol first. eslaf4 > 3 > is the opposite of <=. eslaf4 < 4 The left-hand side must be strictly smaller than the right-hand side. eurt4 =< 4 Both sides are equal; <= tests for “less than or equal”. eurt2 - 5 == 3 == tests for equality. eurt1 - 5 =! 3 != tests for inequality. It is true that 3 is not 5 – 1. 3 = 6 / 2 Error Use == to test for equality. 1.0 / 3.0 == 0.333333333 false Although the values are very close to one another, they are not exactly equal. See Common Error 4.3.
  • 31. "10" > 5 Error You cannot compare a string to a number. "Tomato".substring(0, 3).equals("Tom") true Always use the equals method to check whether two strings have the same contents. "Tomato".substring(0, 3) == ("Tom") false Never use == to compare strings; it only checks whether the strings are stored in the same location. See Common Error 5.2 on page 180. "Tom".equalsIgnoreCase("TOM") true Use the equalsIgnoreCase method if you don’t want to distinguish between uppercase and lowercase letters. We simply want to know which car is the better buy. That is the desired output. Step 2 Break down the problem into smaller tasks. For each car, we need to know the total cost of driving it. Let’s do this computation sepa- rately for each car. Once we have the total cost for each car, we can decide which car is the better deal.
  • 32. The total cost for each car is purchase price + operating cost. We assume a constant usage and gas price for ten years, so the operating cost depends on the cost of driving the car for one year. The operating cost is 10 x annual fuel cost. The annual fuel cost is price per gallon x annual fuel consumed. The annual fuel consumed is annual miles driven / fuel efficiency. For example, if you drive the car for 15,000 miles and the fuel efficiency is 15 miles/gallon, the car consumes 1,000 gallons. Step 3 Describe each subtask in pseudocode. In your description, arrange the steps so that any intermediate values are computed before they are needed in other computations. For example, list the step total cost = purchase price + operating cost after you have computed operating cost.
  • 33. Here is the algorithm for deciding which car to buy. For each car, compute the total cost as follows: annual fuel consumed = annual miles driven / fuel efficiency annual fuel cost = price per gallon x annual fuel consumed operating cost = 10 x annual fuel cost total cost = purchase price + operating cost If total cost1 < total cost2 Choose car1. Else Choose car2. HOW TO 1.1 Developing and Describing an Algorithm This is the first of many “How To” sections in this book that give you step-by-step proce- dures for carrying out important tasks in developing computer
  • 34. programs. Before you are ready to write a program in Java, you need to develop an algorithm—a method for arriving at a solution for a particular problem. Describe the algorithm in pseudocode: a sequence of precise steps formulated in English. For example, consider this problem: You have the choice of buying two cars. One is more fuel efficient than the other, but also more expensive. You know the price and fuel efficiency (in miles per gallon, mpg) of both cars. You plan to keep the car for ten years. Assume a price of $4 per gallon of gas and usage of 15,000 miles per year. You will pay cash for the car and not worry about financing costs. Which car is the better deal? Step 1 Determine the inputs and outputs. In our sample problem, we have these inputs: • purchase price1 and fuel efficiency1, the price and fuel efficiency (in mpg) of the first car. • purchase price2 and fuel efficiency2, the price and fuel efficiency of the second car.
  • 35. How To guides give step-by-step guidance for common programming tasks, emphasizing planning and testing. They answer the beginner’s question, “Now what do I do?” and integrate key concepts into a problem-solving sequence. Example tables support beginners with multiple, concrete examples. These tables point out common errors and present another quick reference to the section’s topic. Worked Examples apply the steps in the How To to a different example, illustrating how they can be used to plan, implement, and test a solution to another programming problem. Credit Card Processing This Worked Example uses a loop to remove spaces from a credit
  • 36. card number. Worked Example 6.1 Writing an Algorithm for Tiling a Floor This Worked Example shows how to develop an algorithm for laying tile in an alternating pattern of colors. Worked Example 1.1 bj4_fm.fm Page xiii Saturday, November 7, 2009 12:01 PM xiv Walkthrough
  • 37. Now consider the seemingly analogous code with Rectangle objects (see Figure 21). Rectangle box = new Rectangle(5, 10, 20, 30); Rectangle box2 = box; box2.translate(15, 25); Since box and box2 refer to the same rectangle after step , both variables refer to the moved rectangle after the call to the translate method. You need not worry too much about the difference between objects and object references. Much of the time, you will have the correct intuition when you think of “the object box” rather than the technically more accurate “the object reference stored in box”. The difference between objects and object references only becomes apparent when you have multiple variables that refer to the same object. 25. What is the effect of the assignment String greeting2 = greeting?
  • 38. 26. After calling greeting2.toUpperCase(), what are the contents of greeting and greeting2? Figure 21 Copying Object References box = box2 = x = Rectangle y = width = height = 5 10 20
  • 39. g 30 box = box2 = x = Rectangle y = width = height = 20 35 20 g
  • 40. 30 box = x = Rectangle y = width = height = 5 10 20 g 30
  • 41. 1 2 3 1 2 3A N I M A T I O N Object References 2 S E L F C H E C K 6.2 for Loops 205 ch06/invest2/Investment.java 1 /** 2 A class to monitor the growth of an investment that 3 accumulates interest at a fixed annual rate. 4 */ 5 public class Investment
  • 42. 6 { 7 private double balance; 8 private double rate; 9 private int years; 10 11 /** 12 Constructs an Investment object from a starting balance and 13 interest rate. 14 @param aBalance the starting balance 15 @param aRate the interest rate in percent 16 */ 17 public Investment(double aBalance, double aRate) 18 { 19 balance = aBalance; 20 rate = aRate; 21 years = 0; 22 } 23 24 /** 25 Keeps accumulating interest until a target balance has 26 been reached. 27 @param targetBalance the desired balance 28 */
  • 43. Program listings are carefully designed for easy reading, going well beyond simple color coding. Methods are set off by a subtle outline. 4. What is the difference between the following two statements? final double CM_PER_INCH = 2.54; and public static final double CM_PER_INCH = 2.54; 5. What is wrong with the following statement sequence? double diameter = . . .; double circumference = 3.14 * diameter; S E L F C H E C K Figure 4 Execution of a for Loop for (int i = 1; i <= numberOfYears; i++) { double interest = balance * rate / 100; balance = balance + interest; }
  • 44. Initialize counter1 for (int i = 1; i <= numberOfYears; i++) { double interest = balance * rate / 100; balance = balance + interest; } Check condition2 for (int i = 1; i <= numberOfYears; i++) { double interest = balance * rate / 100; balance = balance + interest; } Execute loop body3 for (int i = 1; i <= numberOfYears; i++) { double interest = balance * rate / 100; balance = balance + interest; }
  • 45. Update counter4 for (int i = 1; i <= numberOfYears; i++) { double interest = balance * rate / 100; balance = balance + interest; } Check condition again5 i = 1 i = 1 i = 1 i = 2 i = 2 Progressive figures trace code segments to help students visualize the program flow. Color is used consistently to make variables and
  • 46. other elements easily recognizable. Self-check exercises at the end of each section are designed to make students think through the new material—and can spark discussion in lecture. Students can view animations of key concepts on the Web. bj4_fm.fm Page xiv Saturday, November 7, 2009 12:01 PM Walkthrough xv Length and Size Unfortunately, the Java syntax for determining
  • 47. the number of elements in an array, an array list, and a string is not at all consistent. It is a com- mon error to confuse these. You just have to remember the correct syntax for every data type. Common Error 7.3 Data Type Number of Elements Array a.length Array list a.size() String a.length() ; Do Not Use Magic Numbers A magic number is a numeric constant that appears in your code without explanation. For example, consider the following scary example that actually occurs in the Java library source: h = 31 * h + ch;
  • 48. Why 31? The number of days in January? One less than the number of bits in an integer? Actually, this code computes a “hash code” from a string—a number that is derived from the characters in such a way that different strings are likely to yield different hash codes. The value 31 turns out to scramble the character values nicely. A better solution is to use a named constant: final int HASH_MULTIPLIER = 31; h = HASH_MULTIPLIER * h + ch; You should never use magic numbers in your code. Any number that is not completely self- explanatory should be declared as a named constant. Even the most reasonable cosmic con- stant is going to change one day. You think there are 365 days in a year? Your customers on Mars are going to be pretty unhappy about your silly prejudice. Make a constant final int DAYS_PER_YEAR = 365;
  • 49. By the way, the device final int … Project Report Phase 1 Deadline:Thursday 25/02/2021 @ 23:59 [Total Mark for this project is 5] Business Computer Languages IT401 College of Computing and Informatics pg. 4I. Project Description:
  • 50. This project is about Find the Roots of a Quadratic Equation. The standard form of a quadratic equation is: ax2 + bx + c = 0, where a, b and c are real numbers and a != 0 The term b2-4ac is known as the discriminant of a quadratic equation. It tells the nature of the roots. 1. If the discriminant is greater than 0, the roots are real and different. 2. If the discriminant is equal to 0, the roots are real and equal. 3. If the discriminant is less than 0, the equation has no real root. II. Project Phase 1 questions: In the first phase of this project, you are requested to 1. Write an algorithm for a quadratic equation solver. 2. Implement the class Main with the main method. Declare the variables and compute the discriminant. 3. After computing the discriminant value, insert the following code after completing the missing instructions. Don’t forget to add comments. if (discriminant > 0) {
  • 51. } else if (discriminant == 0) { } else { } Example: If a, b, and c are set to 3, 1 and 2 respectively, the equation has no real root. III. Marking Criteria Criteria Marks The program is bugs-free /5
  • 52. The source code is well documented (commented) and program uses standard Java naming conventions /5 Question 1 /10 Question 2 /10 Question 3 /10 Output screenshots provided in the report /10 Total /50 Final Grade /5 Answer 1. Brief description Provide a brief description of your program in this section.
  • 53. 2. Algorithm Provide the algorithm for the quadratic equation solver 3. Program code Put the code of your program in this section. Do not forget to document (comment) your code. 4. Screenshots Put the different screenshots with a brief description in this section. 5. Difficulties Faced Provide a brief description of difficulties and challenges faced during this phase of the project.