Java Programming 8th Edition Joyce Farrell download
Java Programming 8th Edition Joyce Farrell download
download
https://ebookgate.com/product/java-programming-8th-edition-joyce-
farrell/
https://ebookgate.com/product/java-programming-6th-edition-joyce-
farrell/
ebookgate.com
https://ebookgate.com/product/programming-logic-and-design-
comprehensive-8th-edition-joyce-farrell/
ebookgate.com
https://ebookgate.com/product/programming-logic-and-design-
comprehensive-7th-edition-joyce-farrell/
ebookgate.com
https://ebookgate.com/product/computer-programming-for-teens-1st-
edition-mary-e-farrell/
ebookgate.com
Programming in Java 2nd edition Edition Choudhary
https://ebookgate.com/product/programming-in-java-2nd-edition-edition-
choudhary/
ebookgate.com
https://ebookgate.com/product/jxta-java-p2p-programming-1st-edition-
daniel-brookshier/
ebookgate.com
https://ebookgate.com/product/java-network-programming-third-edition-
elliotte-rusty-harold/
ebookgate.com
https://ebookgate.com/product/a-guide-to-programming-in-java-
java-2-platform-standard-edition-5-beth-brown/
ebookgate.com
https://ebookgate.com/product/functional-programming-in-java-
harnessing-the-power-of-java-8-lambda-expressions-1st-edition-venkat-
subramaniam/
ebookgate.com
TM
JAVA PROGRAMMING
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
EIGHTH EDITION
TM
JAVA PROGRAMMING
JOYCE FARRELL
Australia • Brazil • Japan • Korea • Mexico • Singapore • Spain • United Kingdom • United States
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
This is an electronic version of the print textbook. Due to electronic rights restrictions, some third party content may be suppressed. Editorial
review has deemed that any suppressed content does not materially affect the overall learning experience. The publisher reserves the right to
remove content from this title at any time if subsequent rights restrictions require it. For valuable information on pricing, previous
editions, changes to current editions, and alternate formats, please visit www.cengage.com/highered to search by
ISBN#, author, title, or keyword for materials in your areas of interest.
Important Notice: Media content referenced within the product description or the product text may not be available in the eBook version.
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Java Programming, © 2016, 2014, 2012 Cengage Learning
Eighth Edition WCN: 02-200-203
Joyce Farrell
ALL RIGHTS RESERVED. No part of this work covered by the copyright
Product Director: herein may be reproduced, transmitted, stored, or used in any form or
Kathleen McMahon by any means graphic, electronic, or mechanical, including but not
Senior Content Developer: limited to photocopying, recording, scanning, digitizing, taping, Web
Alyssa Pratt distribution, information networks, or information storage and
retrieval systems, except as permitted under Section 107 or 108 of the
Development Editor: Dan Seiter
1976 United States Copyright Act, without the prior written
Marketing Manager: Eric LaScola permission of the publisher.
Manufacturing Planner:
Julio Esperas
For product information and technology assistance, contact us at
Art Director: Jack Pendleton Cengage Learning Customer & Sales Support, 1-800-354-9706
Production Management,
For permission to use material from this text or product,
Copyediting, Composition,
Proofreading, and Indexing: submit all requests online at www.cengage.com/permissions.
Integra Software Services Pvt. Ltd. Further permissions questions can be emailed to
Cover Photo: [email protected].
©Maram/Shutterstock.com
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Brief Contents
v
Preface . . . . . . . . . . . . . . . . . . . . . . xxi
CHAPTER 1 Creating Java Programs . . . . . . . . . . . . . . . . 1
CHAPTER 2 Using Data . . . . . . . . . . . . . . . . . . . . . 53
CHAPTER 3 Using Methods, Classes, and Objects . . . . . . . 119
CHAPTER 4 More Object Concepts . . . . . . . . . . . . . . . 183
CHAPTER 5 Making Decisions . . . . . . . . . . . . . . . . . 245
CHAPTER 6 Looping . . . . . . . . . . . . . . . . . . . . . 301
CHAPTER 7 Characters, Strings, and the StringBuilder . . . 353
CHAPTER 8 Arrays . . . . . . . . . . . . . . . . . . . . . . 393
CHAPTER 9 Advanced Array Concepts . . . . . . . . . . . . . 439
CHAPTER 10 Introduction to Inheritance . . . . . . . . . . . . . 491
CHAPTER 11 Advanced Inheritance Concepts . . . . . . . . . . 537
CHAPTER 12 Exception Handling . . . . . . . . . . . . . . . . 593
CHAPTER 13 File Input and Output . . . . . . . . . . . . . . . 665
CHAPTER 14 Introduction to Swing Components . . . . . . . . 729
CHAPTER 15 Advanced GUI Topics . . . . . . . . . . . . . . . 791
CHAPTER 16 Graphics . . . . . . . . . . . . . . . . . . . . . 861
APPENDIX A Working with the Java Platform . . . . . . . . . . . 919
APPENDIX B Data Representation . . . . . . . . . . . . . . . 925
APPENDIX C Formatting Output . . . . . . . . . . . . . . . . 931
APPENDIX D Generating Random Numbers . . . . . . . . . . . 941
APPENDIX E Javadoc . . . . . . . . . . . . . . . . . . . . . 949
Glossary . . . . . . . . . . . . . . . . . . . . 957
Index . . . . . . . . . . . . . . . . . . . . . . 979
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Contents
vi
Preface . . . . . . . . . . . . . . . . . . xxi
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Chapter Summary . . . . . . . . . . . . . . . . . . . . . . 45
Review Questions . . . . . . . . . . . . . . . . . . . . . . 46
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . 48
Programming Exercises . . . . . . . . . . . . . . . . . . 48
Debugging Exercises . . . . . . . . . . . . . . . . . . . 50 vii
Game Zone . . . . . . . . . . . . . . . . . . . . . . . . 50
Case Problems . . . . . . . . . . . . . . . . . . . . . . 51
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CONTENTS
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPT ER 4 More Object Concepts . . . . . . . . . . . 183
Understanding Blocks and Scope . . . . . . . . . . . . . . 184
Overloading a Method . . . . . . . . . . . . . . . . . . . 192
Automatic Type Promotion in Method Calls . . . . . . . . . 194
Learning About Ambiguity . . . . . . . . . . . . . . . . . 199 ix
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CONTENTS
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Altering a Definite Loop’s Control Variable . . . . . . . . . . 307
Writing an Indefinite while Loop . . . . . . . . . . . . . 308
Validating Data . . . . . . . . . . . . . . . . . . . . . 310
Using Shortcut Arithmetic Operators . . . . . . . . . . . . . 314
Creating a for Loop . . . . . . . . . . . . . . . . . . . 319 xi
Unconventional for Loops . . . . . . . . . . . . . . . . 320
Learning How and When to Use a do…while Loop . . . . . . 325
Learning About Nested Loops . . . . . . . . . . . . . . . . 328
Improving Loop Performance . . . . . . . . . . . . . . . . 333
Avoiding Unnecessary Operations . . . . . . . . . . . . . 333
Considering the Order of Evaluation of Short-Circuit
Operators . . . . . . . . . . . . . . . . . . . . . . 334
Comparing to Zero . . . . . . . . . . . . . . . . . . . 334
Employing Loop Fusion . . . . . . . . . . . . . . . . . . 336
Using Prefix Incrementing Rather than Postfix
Incrementing . . . . . . . . . . . . . . . . . . . . . 337
A Final Note on Improving Loop Performance . . . . . . . . 338
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 342
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 342
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 344
Review Questions . . . . . . . . . . . . . . . . . . . . . 344
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 347
Programming Exercises . . . . . . . . . . . . . . . . . 347
Debugging Exercises . . . . . . . . . . . . . . . . . . 350
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 350
Case Problems . . . . . . . . . . . . . . . . . . . . . 352
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CONTENTS
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPT ER 9 Advanced Array Concepts . . . . . . . . . 439
Sorting Array Elements Using the Bubble Sort Algorithm . . . . 440
Using the Bubble Sort Algorithm . . . . . . . . . . . . . . 440
Improving Bubble Sort Efficiency . . . . . . . . . . . . . 442
Sorting Arrays of Objects . . . . . . . . . . . . . . . . . 443 xiii
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CONTENTS
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CONTENTS
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Using the JCheckBox, ButtonGroup, and JComboBox
Classes . . . . . . . . . . . . . . . . . . . . . . . . 767
The JCheckBox Class . . . . . . . . . . . . . . . . . 767
The ButtonGroup Class . . . . . . . . . . . . . . . . 771
The JComboBox Class . . . . . . . . . . . . . . . . . 772 xvii
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 780
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 780
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 781
Review Questions . . . . . . . . . . . . . . . . . . . . . 783
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 785
Programming Exercises . . . . . . . . . . . . . . . . . 785
Debugging Exercises . . . . . . . . . . . . . . . . . . 787
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 787
Case Problems . . . . . . . . . . . . . . . . . . . . . 788
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CONTENTS
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Programming Exercises . . . . . . . . . . . . . . . . . 915
Debugging Exercises . . . . . . . . . . . . . . . . . . 916
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 916
Case Problems . . . . . . . . . . . . . . . . . . . . . 918
xix
APPENDIX A Working with the Java Platform . . . . . . . 919
Learning about the Java SE Development Kit . . . . . . . . . 920
Configuring Windows to Use the JDK . . . . . . . . . . . . . 920
Finding the Command Prompt . . . . . . . . . . . . . . . 921
Command Prompt Anatomy . . . . . . . . . . . . . . . . 921
Changing Directories . . . . . . . . . . . . . . . . . . 921
Setting the class and classpath Variables . . . . . . . 922
Changing a File’s Name . . . . . . . . . . . . . . . . . 922
Compiling and Executing a Java Program . . . . . . . . . . . 923
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 923
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CONTENTS
Glossary . . . . . . . . . . . . . . . . . 957
Index . . . . . . . . . . . . . . . . . . . 979
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Preface
xxi
Java Programming, Eighth Edition, provides the beginning programmer with a guide to
developing applications using the Java programming language. Java is popular among
professional programmers because it can be used to build visually interesting graphical user
interface (GUI) and Web-based applications. Java also provides an excellent environment for
the beginning programmer—a student can quickly build useful programs while learning the
basics of structured and object-oriented programming techniques.
This textbook assumes that you have little or no programming experience. It provides a solid
background in good object-oriented programming techniques and introduces terminology
using clear, familiar language. The programming examples are business examples; they do not
assume a mathematical background beyond high-school business math. In addition, the
examples illustrate only one or two major points; they do not contain so many features that
you become lost following irrelevant and extraneous details. Complete, working programs
appear frequently in each chapter; these examples help students make the transition from the
theoretical to the practical. The code presented in each chapter can also be downloaded from
the publisher’s Web site, so students can easily run the programs and experiment with
changes to them.
The student using Java Programming, Eighth Edition, builds applications from the bottom up
rather than starting with existing objects. This facilitates a deeper understanding of the
concepts used in object-oriented programming and engenders appreciation for the existing
objects students use as their knowledge of the language advances. When students complete
this book, they will know how to modify and create simple Java programs, and they will have
the tools to create more complex examples. They also will have a fundamental knowledge of
object-oriented programming, which will serve them well in advanced Java courses or in
studying other object-oriented languages such as C++, C#, and Visual Basic.
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
PREFACE Features
Chapters 10, 11, and 12 thoroughly cover inheritance and exception handling. Inheritance is
the object-oriented concept that allows you to develop new objects quickly by adapting the
features of existing objects; exception handling is the object-oriented approach to handling
errors. Both are important concepts in object-oriented design. Chapter 13 provides
information on handling files so you can permanently store and retrieve program output.
xxii
Chapters 14, 15, and 16 introduce GUI Swing components (Java’s visually pleasing,
user-friendly widgets), their layout managers, and graphics.
Features
The following features are new for the Eighth Edition:
JAVA 8E: All programs have been tested using Java 8e, the newest edition of Java.
WINDOWS 8.1: All programs have been tested in Windows 8.1, and all screen shots have
been taken in this new environment.
DATE AND TIME CLASSES: This edition provides thorough coverage of the java.time
package, which is new in Java 8e.
ON-SCREEN KEYBOARD: This edition provides instructions for displaying and using an
on-screen keyboard with either a touch screen or a standard screen.
MODERNIZED GRAPHICS OUTPUT: The chapter on graphics (Chapter 16) has been
completely rewritten to focus on Swing component graphics production using the
paintComponent() method.
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Features
EMPHASIS ON STUDENT RESEARCH: The student frequently is directed to the Java Web
site to investigate classes and methods. Computer languages evolve, and programming
professionals must understand how to find the latest language improvements. This book
encourages independent research.
FIGURES: Each chapter contains many figures. Code figures are most frequently 25 lines
xxiii
or fewer, illustrating one concept at a time. Frequent screen shots show exactly how
program output appears. Callouts appear where needed to emphasize a point.
COLOR: The code figures in each chapter contain all Java keywords in blue. This helps
students identify keywords more easily, distinguishing them from programmer-selected
names.
FILES: More than 200 student files can be downloaded from the publisher’s Web site. Most
files contain the code presented in the figures in each chapter; students can run the code for
themselves, view the output, and make changes to the code to observe the effects. Other
files include debugging exercises that help students improve their programming skills.
TWO TRUTHS & A LIE: A short quiz reviews each chapter section, with answers provided.
This quiz contains three statements based on the preceding section of text—two
statements are true and one is false. Over the years, students have requested answers to
problems, but we have hesitated to distribute them in case instructors want to use
problems as assignments or test questions. These true–false quizzes provide students with
immediate feedback as they read, without “giving away” answers to the multiple-choice
questions and programming exercises.
DON’T DO IT: This section at the end of each chapter summarizes common mistakes and
pitfalls that plague new programmers while learning the current topic.
KEY TERMS: Each chapter includes a list of newly introduced vocabulary, shown in the
order of appearance in the text. The list of key terms provides a short review of the major
concepts in the chapter.
SUMMARIES: Following each chapter is a summary that recaps the programming
concepts and techniques covered in the chapter. This feature provides a concise means for
students to check their understanding of the main points in each chapter.
REVIEW QUESTIONS: Each chapter includes 20 multiple-choice questions that serve as a
review of chapter topics.
GAME ZONE: Each chapter provides one or more exercises in which students can create
interactive games using the programming techniques learned up to that point; 70 game
programs are suggested in the book. The games are fun to create and play; writing them
motivates students to master the necessary programming techniques. Students might
exchange completed game programs with each other, suggesting improvements and
discovering alternate ways to accomplish tasks.
CASES: Each chapter contains two running case problems. These cases represent projects
that continue to grow throughout a semester using concepts learned in each new chapter.
Two cases allow instructors to assign different cases in alternate semesters or to divide
students in a class into two case teams.
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
PREFACE Instructor Resources
GLOSSARY: This edition contains an alphabetized list of all key terms identified in the
book, along with their definitions.
APPENDICES: This edition includes useful appendices on working with the Java platform,
data representation, formatting output, generating random numbers, and creating Javadoc
comments.
xxiv
QUALITY: Every program example, exercise, and game solution was tested by the author
and then tested again by a quality assurance team using Java Standard Edition (SE) 8, the
most recent version available.
CourseMate
The more you study, the better the results. Make the most of your study time by accessing
everything you need to succeed in one place. Read your textbook, take notes, review
flashcards, watch videos, and take practice quizzes online. CourseMate goes beyond the book
to deliver what you need! Learn more at www.cengage.com/coursemate.
The Java Programming CourseMate includes:
Debugging Exercises: Four error-filled programs accompany each chapter. By
debugging these programs, students can gain expertise in program logic in general and
the Java programming language in particular.
Video Lessons: Each chapter is accompanied by at least three video lessons that help to
explain important chapter concepts. These videos were created and narrated by the
author.
Interactive Study Aids: An interactive eBook, quizzes, flashcards, and more!
Instructors may add CourseMate to the textbook package, or students may purchase
CourseMate directly at www.CengageBrain.com.
Instructor Resources
The following teaching tools are available for download at our Instructor Companion Site.
Simply search for this text at sso.cengage.com. An instructor login is required.
Electronic Instructor’s Manual: The Instructor’s Manual that accompanies this
textbook contains additional instructional material to assist in class preparation,
including items such as Overviews, Chapter Objectives, Teaching Tips, Quick
Quizzes, Class Discussion Topics, Additional Projects, Additional Resources, and Key
Terms. A sample syllabus is also available. Additional exercises in the Instructor’s
Manual include:
Tough Questions: Two or more fairly difficult questions that an applicant
might encounter in a technical job interview accompany each chapter. These
questions are often open-ended; some involve coding and others might involve
research.
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Acknowledgments
Acknowledgments
I would like to thank all of the people who helped to make this book a reality, including Dan
Seiter, Development Editor; Alyssa Pratt, Senior Content Developer; Carmel Isaac, Content
Project Manager; and Chris Scriver and Danielle Shaw, quality assurance testers. I am lucky to
work with these professionals who are dedicated to producing high-quality instructional
materials.
I am also grateful to the reviewers who provided comments and encouragement during this
book’s development, including Bernice Cunningham, Wayne County Community College
District; Bev Eckel, Iowa Western Community College; John Russo, Wentworth Institute of
Technology; Leslie Spivey, Edison Community College; and Angeline Surber, Mesa
Community College.
Thanks, too, to my husband, Geoff, for his constant support and encouragement. Finally, this
book is dedicated to the newest Farrell, coming March 2015. As this book goes to production,
I don’t know your name or even your gender, but I do know that I love you.
Joyce Farrell
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Read This Before
xxvi
You Begin
The following information will help you as you prepare to use this textbook.
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Features
This text focuses on helping students become better programmers and understand
Java program development through a variety of key features. In addition to Chapter
Objectives, Summaries, and Key Terms, these useful features will help students
regardless of their learning styles. xxvii
NOTES provide
additional information—
for example, another
location in the book that
expands on a topic, or a
common error to watch
out for.
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Assessment
I found the author’s explanation of
difficult topics to be very clear and
thorough. PROGRAMMING EXERCISES provide
opportunities to practice concepts. These xxix
—Leslie Spivey,
exercises increase in difficulty and allow
Edison Community College
students to explore each major
programming concept presented in the
chapter. Additional programming
exercises are available in the Instructor's
Resource Kit.
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
ASSESSMENT
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 1
Creating Java
Programs
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 1 Creating Java Programs
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Learning Programming Terminology
After the program statements are written, high-level language programmers use a computer
program called a compiler or interpreter to translate their language statements into machine
language. A compiler translates an entire program before carrying out any statements, or
executing them, whereas an interpreter translates one program statement at a time,
executing a statement as soon as it is translated.
3
Whether you use a compiler or interpreter often depends on the programming language you use. For
example, C++ is a compiled language, and Visual Basic is an interpreted language. Each type of translator
has its supporters; programs written in compiled languages execute more quickly, whereas programs
written in interpreted languages can be easier to develop and debug. Java uses the best of both technolo-
gies: a compiler to translate your programming statements and an interpreter to read the compiled code line
by line when the program executes (also called at run time).
Compilers and interpreters issue one or more error messages each time they encounter an
invalid program statement—that is, a statement containing a syntax error, or misuse of the
language. Examples of syntax errors include misspelling a keyword or omitting a word that a
statement requires. When a syntax error is detected, the programmer can correct the error
and attempt another translation. Repairing all syntax errors is the first part of the process
of debugging a program—freeing the program of all flaws or errors, also known as bugs.
Figure 1-1 illustrates the steps a programmer takes while developing an executable program.
You will learn more about debugging Java programs later in this chapter.
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 1 Creating Java Programs
4
Write program language statements
that correspond to the logic
Debugging process
Use translating software (a compiler or
interpreter) that translates programming
language statements to machine language
Debugging process
Can all statements No Examine list of
be successfully
syntax errors
translated?
Yes
Examine
program output
No
As Figure 1-1 shows, you might write a program with correct syntax that still contains logic
errors. A logic error is a bug that allows a program to run, but that causes it to operate
incorrectly. Correct logic requires that all the right commands be issued in the appropriate
order. Examples of logic errors include multiplying two values when you meant to divide
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Learning Programming Terminology
them or producing output prior to obtaining the appropriate input. When you develop a
program of any significant size, you should plan its logic before you write any program
statements.
Correcting logic errors is much more difficult than correcting syntax errors. Syntax errors are
discovered by the language translator when you compile a program, but a program can be free 5
of syntax errors and execute while still retaining logic errors. Often you can identify logic
errors only when you examine a program’s output. For example, if you know an employee’s
paycheck should contain the value $4,000, but when you examine a payroll program’s output
you see that it holds $40, then a logic error has occurred. Perhaps an incorrect calculation was
performed, or maybe the hours worked value was output by mistake instead of the net pay
value. When output is incorrect, the programmer must carefully examine all the statements
within the program, revise or move the offending statements, and translate and test the
program again.
Just because a program produces correct output does not mean it is free from logic errors. For example,
suppose that a program should multiply two values entered by the user, that the user enters two 2s, and the
output is 4. The program might actually be adding the values by mistake. The programmer would discover
the logic error only by entering different values, such as 5 and 7, and examining the result.
Programmers call some logic errors semantic errors. For example, if you misspell a programming
language word, you commit a syntax error, but if you use a correct word in the wrong context, you commit a
semantic error.
In each “Two Truths & a Lie” section, two of the numbered statements are true, and one
is false. Identify the false statement and explain why it is false.
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 1 Creating Java Programs
Procedural Programming
Procedural programming is a style of programming in which operations are executed one
after another in sequence. In procedural applications, you create names for computer
memory locations that can hold values—for example, numbers and text—in electronic
form. The named computer memory locations are called variables because they hold values
that might vary. For example, a payroll program might contain a variable named rateOfPay.
The memory location referenced by the name rateOfPay might contain different values
(a different value for every employee of the company) at different times. During the execution
of the payroll program, each value stored under the name rateOfPay might have many
operations performed on it—for example, the value might be read from an input device,
be multiplied by another variable representing hours worked, and be printed on paper.
For convenience, the individual operations used in a computer program are often grouped
into logical units called procedures. For example, a series of four or five comparisons and
calculations that together determine a person’s federal withholding tax value might be
grouped as a procedure named calculateFederalWithholding. A procedural program
defines the variable memory locations and then calls a series of procedures to input,
manipulate, and output the values stored in those locations. When a program calls a
procedure, the current logic is temporarily abandoned so that the procedure’s commands can
execute. A single procedural program often contains hundreds of variables and procedure
calls. Procedures are also called modules, methods, functions, and subroutines. Users of
different programming languages tend to use different terms. As you will learn later in this
chapter, Java programmers most frequently use the term method.
Object-Oriented Programming
Object-oriented programming is an extension of procedural programming in which you take
a slightly different approach to writing computer programs. Writing object-oriented
programs involves:
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Comparing Procedural and Object-Oriented Programming Concepts
Originally, object-oriented programming was used most frequently for two major types of
applications:
Computer simulations, which attempt to mimic real-world activities so that their
processes can be improved or so that users can better understand how the real-world
processes operate
7
Graphical user interfaces, or GUIs (pronounced “gooeys”), which allow users to interact
with a program in a graphical environment
Thinking about objects in these two types of applications makes sense. For example, a city
might want to develop a program that simulates traffic patterns to help prevent traffic tie-ups.
Programmers would create classes for objects such as cars and pedestrians that contain their
own data and rules for behavior. For example, each car has a speed and a method for changing
that speed. The specific instances of cars could be set in motion to create a simulation of a real
city at rush hour.
Creating a GUI environment for users is also a natural use for object orientation. It is easy to
think of the components a user manipulates on a computer screen, such as buttons and scroll
bars, as similar to real-world objects. Each GUI object contains data—for example, a button
on a screen has a specific size and color. Each object also contains behaviors—for example,
each button can be clicked and reacts in a specific way when clicked. Some people consider
the term object-oriented programming to be synonymous with GUI programming, but object-
oriented programming means more. Although many GUI programs are object oriented, not
all object-oriented programs use GUI objects. Modern businesses use object-oriented design
techniques when developing all sorts of business applications, whether they are GUI
applications or not. In the first 13 chapters of this book, you will learn object-oriented
techniques that are appropriate for any program type; in the last chapters, you will apply what
you have learned about those techniques specifically to GUI applications.
Understanding object-oriented programming requires grasping three basic concepts:
Encapsulation as it applies to classes as objects
Inheritance
Polymorphism
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 1 Creating Java Programs
Name
Age
Ginger Bowser Roxy
Breed 6 2 1
Akita Retriever Beagle
Shot status Up to date Up to date Up to date
Figure 1-2 Dog class definition and some objects created from it
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Comparing Procedural and Object-Oriented Programming Concepts
Besides defining properties, classes define methods their objects can use. A method is a
self-contained block of program code that carries out some action, similar to a procedure in a
procedural program. An Automobile, for example, might have methods for moving forward,
moving backward, and determining the status of its gas tank. Similarly, a Dog might have
methods for walking, eating, and determining its name, and a program’s GUI components
might have methods for maximizing and minimizing them as well as determining their size. 9
In other words, if objects are similar to nouns, then methods are similar to verbs.
In object-oriented classes, attributes and methods are encapsulated into objects.
Encapsulation refers to two closely related object-oriented notions:
Encapsulation is the enclosure of data and methods within an object. Encapsulation allows
you to treat all of an object’s methods and data as a single entity. Just as an actual dog
contains all of its attributes and abilities, so would a program’s Dog object.
Encapsulation also refers to the concealment of an object’s data and methods from outside
sources. Concealing data is sometimes called information hiding, and concealing how
methods work is implementation hiding; you will learn more about both terms in the
chapter “Using Methods, Classes, and Objects.” Encapsulation lets you hide specific object
attributes and methods from outside sources and provides the security that keeps data and
methods safe from inadvertent changes.
If an object’s methods are well written, the user can be unaware of the low-level details of how
the methods are executed, and the user must simply understand the interface or interaction
between the method and the object. For example, if you can fill your Automobile with
gasoline, it is because you understand the interface between the gas pump nozzle and the
vehicle’s gas tank opening. You don’t need to understand how the pump works mechanically
or where the gas tank is located inside your vehicle. If you can read your speedometer, it does
not matter how the displayed figure is calculated. As a matter of fact, if someone produces a
superior, more accurate speed-determining device and inserts it in your Automobile, you
don’t have to know or care how it operates, as long as your interface remains the same.
The same principles apply to well-constructed classes used in object-oriented programs—
programs that use classes only need to work with interfaces.
Inheritance helps you understand real-world objects. For example, the first time you
encounter a convertible, you already understand how the ignition, brakes, door locks, and
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 1 Creating Java Programs
other systems work because you realize that a convertible is a type of automobile, so you need
to be concerned only with the attributes and methods that are “new” with a convertible. The
advantages in programming are the same—you can build new classes based on existing classes
and concentrate on the specialized features you are adding.
A final important concept in object-oriented terminology is polymorphism. Literally,
10
polymorphism means “many forms”—it describes the feature of languages that allows the
same word or symbol to be interpreted correctly in different situations based on the context.
For example, although the classes Automobile, Sailboat, and Airplane all inherit from
Vehicle, turn and stop methods work differently for instances of those classes. The
advantages of polymorphism will become more apparent when you begin to create GUI
applications containing features such as windows, buttons, and menu bars. In a GUI application,
it is convenient to remember one method name, such as setColor or setHeight, and have it
work correctly no matter what type of object you are modifying.
When you see a plus sign (+) between two numbers, you understand they are being added.
When you see it carved in a tree between two names, you understand that the names are
linked romantically. Because the symbol has diverse meanings based on context, it is
polymorphic. Chapters 10 and 11 provide more information about inheritance and
polymorphism and how they are implemented in Java.
polymorphism describes the ability to use one term to cause multiple actions.
the attributes and methods of existing classes, but with more specific features;
The false statement is #3. Inheritance is the ability to create classes that share
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Features of the Java Programming Language
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 1 Creating Java Programs
Source code is
stored on a disk in
12 a file with a name
ending in .java
Java Compiler
Compiler creates
bytecode that
is stored on a
disk in a file with
a name ending in
Java Virtual Machine .class
Java Interpreter
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Analyzing a Java Application that Produces Console Output
1. Java was developed to be architecturally neutral, which means that anyone can 13
build an application without extensive study.
2. After you write a Java program, the compiler converts the source code into a binary
program of bytecode.
3. Java programs that are embedded in a Web page are called applets, while stand-
alone programs are called Java applications.
means that you can use Java to write a program that will run on any platform.
The false statement is #1. Java was developed to be architecturally neutral, which
In program code in figures in this book, Java keywords as well as true, false, and null are blue, and all
other program elements are black. A complete list of Java keywords is shown later in this chapter.
The code for every complete program shown in this book is available in a set of student files you can
download so that you can execute the programs on your own computer.
Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Other documents randomly have
different content
BOOK V
Who is there that by energy of mind
Could build a poem worthy of our theme’s
Majesty and of these discoveries?
Or who has such a mastery of words
As to devise praises proportionate
To his deserts, who to us has bequeathed
Such prizes, earned by his own intellect?
No man, I think, formed of a mortal body.
For if we are to speak as the acknowledged
Majesty of our theme demands, a god
Was he, most noble Memmius, a god,
Who first found out that discipline of life
Which now is called philosophy, and whose skill
From such great billows and a gloom so dark
Delivered life, and steered it into a calm
So peaceful and beneath so bright a light.
For compare the divine discoveries
Of others in old times. ’Tis told that Ceres
First revealed corn to men, Liber the juice
Of grape-born wine; though life without these things
Might well have been sustained; and even now
’Tis said there are some people that live so.
But to live happily was not possible
Without a serene mind. Therefore more justly
Is this man deemed by us a god, from whom
Came those sweet solaces of life, which now
Already through great nations spread abroad
Have power to soothe men’s minds. Should you suppose
Moreover that the deeds of Hercules
Surpass his, then yet further will you drift
Out of true reason’s course. For what harm now
Would those great gaping jaws of Nemea’s lion
Do to us, and the bristly Arcadian boar?
What could the bull of Crete, or Lerna’s pest
The Hydra fenced around with venomous snakes,
And threefold Gerion’s triple-breasted might,
Or those brazen-plumed birds inhabiting
Stymphalian swamps, what injury so great
Could they inflict upon us, or the steeds
Of Thracian Diomede, with fire-breathing nostrils
Ranging Bistonia’s wilds and Ismarus?
Also the serpent, guardian of the bright
Gold-gleaming apples of the Hesperides,
Fierce and grim-glancing, with huge body coiled
Round the tree’s stem, how were it possible
He could molest us by the Atlantic shore
And those lone seas, where none of us sets foot,
And no barbarian ventures to draw near?
And all those other monsters which likewise
Have been destroyed, if they had not been vanquished,
What harm, pray, could they do, though now alive?
None, I presume: for the earth even now abounds
With wild beasts to repletion, and is filled
With shuddering terror throughout its woods, great mountains
And deep forests, regions which we have power
For the most part to avoid. But if the heart
Has not been purged, what tumults then, what dangers
Must needs invade us in our own despite!
What fierce anxieties, offspring of desire,
Rend the distracted man, what mastering fears!
Pride also, sordid avarice, and violence,
Of what calamities are not they the cause!
Luxury too, and slothfulness! He therefore
Who could subdue all these, and banish them
Out of our minds by force of words, not arms,
Is it not right we should deem such a man
Worthy to be numbered among the gods?
The more that he was wont in beautiful
And godlike speech to utter many truths
About the immortal gods themselves, and set
The whole nature of things in clear words forth.
I, in his footsteps treading, follow out
His reasonings and expound in my discourse
By what law all things are created, how
They are compelled to abide within that law,
Without power to annul the immutable
Decrees of time; and first above all else
The mind’s nature was found to be composed
Of a body that had birth, without the power
To endure through a long period unscathed:
For it was found to be mere images
That are wont to deceive the mind in sleep,
Whenever we appear to behold one
Whom life has abandoned. Now, for what remains,
The order of my argument has brought me
To the point where I must show both how the world
Is composed of a body which must die,
Also that it was born; and in what way
Matter once congregating and uniting
Established earth sky sea, the stars, the sun,
And the moon’s globe: also what living creatures
Rose from the earth, and which were those that never
At any time were born: next in what way
Mankind began to employ varied speech
One with another by giving names to things:
Then for what causes that fear of the gods
Entered their breasts, and now through the whole world
Gives sanctity to shrines, lakes and groves,
Altars and images of gods. Moreover
I will make plain by what force and control
Nature pilots the courses of the sun
And the wanderings of the moon, lest we perchance
Deem that they traverse of their own free will
Their yearly orbits between heaven and earth,
Obsequiously furthering the increase
Of crops and living things, or should suppose
Th t th ll d b th d ’d i
That they roll onwards by the gods’ design.
For those who have learnt rightly that the gods
Lead a life free from care, if yet they wonder
By what means all things can be carried on,
Such above all as are perceived to happen
In the ethereal regions overhead,
They are borne back again into their old
Religious fears, and adopt pitiless lords,
Whom in their misery they believe to be
Almighty; for they are ignorant of what can
And what cannot exist; in fine they know not
Upon what principle each thing has its powers
Limited, and its deep-set boundary stone.
ebookgate.com