Java Programming 8th Edition Joyce Farrell Download PDF
Java Programming 8th Edition Joyce Farrell Download PDF
com
https://ebookgate.com/product/java-
programming-8th-edition-joyce-farrell/
https://ebookgate.com/product/java-programming-6th-edition-joyce-
farrell/
https://ebookgate.com/product/programming-logic-and-design-
comprehensive-8th-edition-joyce-farrell/
https://ebookgate.com/product/programming-logic-and-design-
comprehensive-7th-edition-joyce-farrell/
https://ebookgate.com/product/computer-programming-for-teens-1st-
edition-mary-e-farrell/
Programming in Java 2nd edition Edition Choudhary
https://ebookgate.com/product/programming-in-java-2nd-edition-
edition-choudhary/
https://ebookgate.com/product/jxta-java-p2p-programming-1st-
edition-daniel-brookshier/
https://ebookgate.com/product/java-network-programming-third-
edition-elliotte-rusty-harold/
https://ebookgate.com/product/a-guide-to-programming-in-java-
java-2-platform-standard-edition-5-beth-brown/
https://ebookgate.com/product/functional-programming-in-java-
harnessing-the-power-of-java-8-lambda-expressions-1st-edition-
venkat-subramaniam/
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: permissionrequest@cengage.com.
©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.
CHAPTER 1 Creating Java Programs
The string “First Java application” appears within parentheses because the string is an
argument to a method, and arguments to methods always appear within parentheses.
Arguments are pieces of information that are sent into a method. The act of sending
arguments to a method is called passing arguments to the method. As an analogy, consider
placing a catalog order with a company that sells sporting goods. Processing a catalog order is
a method that consists of a set of standard procedures—recording the order, checking the
availability of the item, pulling the item from the warehouse, and so on. Each catalog order
also requires a set of data items, such as which item number you are ordering and the
quantity of the item desired; these data items can be considered the arguments to the
order-processing method. If you order two of item 5432 from a catalog, you expect different
results than if you order 1,000 of item 9008. Likewise, if you pass the argument “Happy
Holidays” to a Java display method, you expect different results than if you pass the argument
“First Java application”.
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
When you call a method, you always use parentheses following the method name. In this
book, you will learn about many methods that require arguments between their parentheses,
and many others for which you leave the parentheses empty. The println() method can be
used with no arguments when you want to output a blank line. Later in this chapter, you will
learn about a method named showMessageDialog() that requires two arguments. Other
methods require more.
Within the statement System.out.println("First Java application");, out is an object
that is a property of the System class that refers to the standard output device for a system,
normally the monitor. The out object itself is an instance of the PrintStream class, which
contains several methods, including println(). Technically, you could create the out object
and write the instructions within the println()method yourself, but it would be time
consuming, and the creators of Java assumed you frequently would want to display output on
a screen. Therefore, the System and PrintStream classes, the out object, and the println()
method were created as a convenience to the programmer.
Within the statement System.out.println("First Java application");, System is a class.
Therefore, System defines attributes for System objects, just as the Dog class defines the
attributes for Dog objects. One of the System attributes is out. (You can probably guess that
another attribute is in and that it represents an input device.)
The dots (periods) in System.out.println() are used to separate the names of the
components in the statement. You will use this format repeatedly in your Java programs.
Java is case sensitive; the class named System is a completely different class from one named
system, SYSTEM, or even sYsTeM, and out is a different object from one named Out or OUT. You
must pay close attention to using correct uppercase and lowercase values when you write Java
programs.
So, the statement that displays the string “First Java application” contains a class, an object
reference, a method call, a method argument, and a statement-ending semicolon, but the
statement cannot stand alone; it is embedded within a class, as shown in Figure 1-4.
A Java identifier cannot be a reserved keyword, such as public or class. (See Table 1-1
for a list of reserved keywords.)
A Java identifier cannot be one of the following values: true, false, or null. These are not
keywords (they are primitive values), but they are reserved and cannot be used.
16 Java is based on Unicode, which is an international system of character representation. The term letter
indicates English-language letters as well as characters from Arabic, Greek, and other alphabets. You can
learn more about Unicode in Appendix B.
Although const and goto are reserved as keywords, they are not used in Java programs, and they have no
function. Both words are used in other languages and were reserved in case developers of future versions of
Java wanted to implement them.
It is a Java standard, although not a requirement, to begin class identifiers with an uppercase
letter and employ other uppercase letters as needed to improve readability. (By contrast,
method identifiers, like println(), conventionally begin with a lowercase letter.) The style
that joins words in which each word begins with an uppercase letter is called Pascal casing,
or sometimes upper camel casing. You should follow established conventions for Java so
your programs will be easy for other programmers to interpret and follow. This book uses
established Java programming conventions.
Table 1-2 lists some valid and conventional class names that you could use when writing
programs in Java. Table 1-3 provides some examples of class names that could be used in Java
(if you use these class names, the class will compile) but that are unconventional and not
recommended. Table 1-4 provides some class name examples that are illegal.
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
Table 1-3 Legal but unconventional and nonrecommended class names in Java
In Figure 1-4 (and again in Figure 1-6), the line public class First is the class header; it
contains the keyword class, which identifies First as a class. The reserved word public is an
access specifier. An access specifier defines the circumstances under which a class can be
accessed and the other classes that have the right to use a class. Public access is the most
liberal type of access; you will learn about public access and other types of access in the
chapter “Using Methods, Classes, and Objects.”
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
18 This line is
public class First
the class
header. {
public static void main(String[] args)
Everything {
between the System.out.println("First Java application");
curly braces is }
the class body. }
After the class header, you enclose the contents of a class within curly braces ({ and }); any data
items and methods between the curly braces make up the class body. A class body can be
composed of any number of data items and methods. In Figure 1-4 (and again in Figure 1-6),
the class First contains only one method within its curly braces. The name of the method is
main(), and the main() method, like the println() method, includes its own set of
parentheses. The main() method in the First class contains only one statement—the
statement that uses the println() method. The main() method does not contain any other
methods, but it calls the println() method.
Indent Style
In general, whitespace is optional in Java. Whitespace is any combination of nonprinting
characters. You use whitespace to organize your program code and make it easier to read.
You can insert whitespace between words or lines in your program code by typing spaces,
tabs, or blank lines because the compiler ignores these extra spaces. However, you cannot use
whitespace within an identifier or keyword, or surrounding the dots in any class-object-
method combination.
For every opening curly brace ({) in a Java program, there must be a corresponding closing
curly brace (}), but the placement of the opening and closing curly braces is not important to
the compiler. For example, the following class executes in exactly the same way as the one
shown in Figure 1-4. The only difference is the layout of the braces—the line breaks occur in
different locations.
public class First{
public static void main(String[] args){
System.out.println("First Java application");
}
}
The indent style shown in the preceding example, in which opening braces do not stand alone
on separate lines, is known as the K & R style and is named for Kernighan and Ritchie, who
wrote the first book on the C programming language. The indent style shown in Figure 1-4
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.
Another random document with
no related content on Scribd:
Home-making has not kept pace with our great industrial
advancement. The average home-maker of today is less thoroughly
prepared for her business in life than the woman of a generation ago.
It would seem that she considers the home-making profession of
much less importance than such occupations as curling feathers and
making shirtwaists. The latter has a commercial value, the former
has not; and we have learned to weigh things by their money value.
Then, again, competition has become the one incentive to work. Tie
badly the million little knots in the willow plume and the next girl in
the line gets the job. Feed the baby with poor milk, let the air in the
room become polluted, ignorantly buy and ignorantly cook, and no
one takes the work from you. Why worry over the way it is done?
There are many reasons why the woman of a generation or two ago
was a better home-maker than the woman of today. The home duties
today often are only part of the daily work of a woman’s life. The
housekeeper today is (in millions of cases) a wage earner as well. She
cannot be as single-minded as the old-fashioned mother whose only
thought was the home. Schools, newspapers, settlements, the trend
of the times, all fill the mind with outside interests. These things are
important, but they have a tendency to crowd out domestic
responsibilities and make women restless under the homely tasks.
Suffrage we will have, and we must interest and educate women until
we do have it; but, at the same time, the dishes have to be washed
clean, the beds have to be aired and made well, and the babies have
to eat nourishing food, or we’ll have an anaemic, poor race to govern
when we get the suffrage.
Is it the fault of the home-maker of today if weakness instead of
strength is the inheritance of her children, and will it be the fault of
the home-maker of tomorrow if she bears and rears a weak race? If
household administration is to take its place in the front rank with
the other professions of the day, educators as well as women must
wake up and realize that the whole housekeeping question is
dependent upon scientific management, efficiency, skilled labor, and
effective tools.
There are those who say that this training should be taught at
home, and in many cases our school children, whether foreign or
American, do come from homes where the mothers are good
housekeepers according to their light; but the last generation cannot
teach the coming one everything. As Samuel Merwin says in a recent
book, “the accumulated experience of the ages is the grandmothers,
and yet she is authority no longer; since her day science has stepped
in. To her mind the gulf between herself and her daughter is nothing
but the old gulf between age and youth. She is wrong. It is a million
miles wide and if the mother keeps to the old way she risks the life of
her child.”
Again, home-making must be made interesting. The man regards
his business as a pleasure. He plays it as he plays a game, and he
plays to win. And so housekeeping has become a “game, not a duty.”
In a natural, enjoyable way our girls should be taught to play the
game of household administration. Home duties are not mere duties
any longer; the old way of “doing up the housework” made every act
an end in itself. Now every act is simply a means to an end; every
move is important,—the way the dishes are washed, the beds made,
the cooking done, may win or lose the game. In the child’s mind must
be a perfect plan; to work out that plan correctly will bring health,
order and happiness as the prize.
The world must stop trying to make progress by walking backward.
We must make room for a vaster scheme of household economics
than the last generation ever dreamed of. The home must be made to
catch up with the factory, the store and the office, and we know that
in comparison with these industries home-making has lagged
behind. Now—suddenly—we realize that feeble-minded children are
becoming more numerous, that malnutrition in school children is
becoming so great that the highest standard of study is impossible
and that street life is taking the place of home life. We wake up and
ask what we can do to make the home-maker realize that she is
responsible for these things.
But is she?
Educators who admit that life and health are absolutely dependent
on the home have failed to find room in the educational scheme to
provide this home knowledge. There were in the elementary schools
in New York city last year 388,000 girls. Only 43,500 of them were
in cooking classes. That means that 344,500 girls in this one year
never had a suggestion given them that home-making was a
profession worth studying. Only seventh and eighth grade girls are
permitted to have cooking lessons, and that means that during the
entire grammar school course a few fortunate girls received nine full
days of domestic science instruction. I say a few, for out of 560
elementary schools only 170 are equipped for cooking; and for these
170 schools, there are only 135 domestic science teachers—some
cooking rooms are closed altogether and others running on half time.
A girl is fortunate if she happens not to be in one of the 390 schools
where no instruction in domestic science is given, and still more
fortunate if she stays in one of the few selected schools until she
reaches the seventh grade. There she first learns that home-making
is worth studying. But 20,000 left school last year before this grade
was reached.
Our public school children may be cash girls, or sales women, or
factory hands. These things may or may not be; but one thing is
certain, and that is that every girl must live in a home and take her
part in home responsibilities.
A MODEL FLAT
The little children of the neighborhood come in to play before lesson time.
The New York board of education would be the first to admit that
it is the home more than anything else that gives, to children health
or feebleness, life or death, happiness or wretchedness and yet they
and we calmly let this neglect go on.
The school lunch committee made an investigation a short time
ago to ascertain whether malnutrition was as great an evil as we
feared. Two thousand and fifty-one children were thoroughly
examined. Half of these from an Irish neighborhood, half from an
Italian. They were selected at random from the four lower grades.
Two hundred and eighty-three or 13 per cent were found to be
suffering from pronounced malnutrition. Their homes were visited.
With the exception of eighteen tea and coffee was a part of the daily
diet. Sixty families had no prepared luncheon or dinner at home. One
hundred and fifty-seven were supplying the wrong or insufficient
food and it was found to be more ignorance than poverty that was the
cause of this condition.
If we take 13 per cent of 388,000 children we have 29,846 poorly
nourished girls who are not even taught that the heavy, dull, sick
feeling is due to the wrong kind of food. How can we place other
knowledge ahead of this? When we watch this large, half fed army of
children marching on to take up a woman’s battle with life it does
seem as if we had been asleep to our responsibilities.
We must establish an adequate twentieth century theory of
household economics and then we must put this within the reach of
every girl in our public schools.
My desk is covered always with pamphlets entitled The Profession
of Home-making, Food Values, Freehand Cooking on Scientific
Principles, and so on, but does this knowledge reach the people?
Does it reach the 388,000 school girls? Recently I heard an hour’s
talk by a member of the Board of Health on how we ought to know
good milk from bad, how careful we should be about canned
vegetables, and the horrors of buying tainted meat: but when I asked
how the common people could know these facts I could get no
satisfaction other than that the way to know whether the milk was
good or not was to examine the barns where the cows were milked or
have the milk tested; but the people I know are ignorant as to how to
wash milk bottles, or why it is wrong to leave the milk uncovered, or
why the nipple from the milk bottle can’t be played with, fall on the
floor and then be used. This representative from the Board of Health
told startling facts about candies and ice cream, sold on push carts,
but the audience at this lecture were land owners along the Hudson
River, and I doubt if one of them had ever seen an East Side push
cart, and I know that not one was ever tempted to buy. Why can’t
these facts reach the thousands of children who do buy dyed ice
cream and varnished candy, and whose fathers sell these very things?
A COOKING LESSON
Whither, whither, pretty child? The world is not yet open. Oh, see how quiet is
all around! ’Tis before daybreak, the streets are mute, whither, whither, do you
hurry? ’Tis now good to sleep, and do you see, the flowers are still dreaming; every
bird’s nest is still silent? Whither pray are you driven now? Whither do you hurry,
tell me, and what to do?
To earn a living.
Whither, whither, pretty child walking so late at night? Alone through the
darkness and cold? And everything is at rest, the world is silent. Whither does the
wind carry you? You will yet lose your way. Scarcely has day smiled on you, how
can the night help you? For it is mute and deaf and blind. Whither, whither, with
easy mind?
To earn a living.[5]
Thus, ten year before vice commissions began to probe into the
connection between white slavery and low pay, wrote Morris
Rosenfeld, the Yiddish poet. In March the fiftieth anniversary of his
birth was celebrated in Carnegie Hall by a great gathering of the
Jewish East Side, under the auspices of the Jewish Daily Forwards,
to which he is a contributor.
Morris Rosenfeld, as a boy a fisherman on the shores of a Polish
lake, early an emigrant from home, and until his health broke down a
few years ago a worker in the sweatshops of London and New York,
expresses in verse the cry of suffering from persecuted and broken
Jew and from exploited and broken worker.
He is no pitiful East Sider struggling for expression, “found” by a
Harvard scholar. He is a poet offering no halting rhymes for which
apologies are necessary. Yiddish literature has many poets of real
genius, but the major part of Rosenfeld’s verse alone, in his Songs
from the Ghetto, has been presented to us in English prose, in the
translation of Leo Wiener, instructor in Slavonic literature in
Harvard.
Through the medium of a language in which, in the expression of
Mr. Wiener, German, Polish, Russian and English—the tongues of all
countries through which the Jew has passed—contend with Hebrew
for the possession of each word, Rosenfeld expresses his meaning
with the note of inevitableness and the adaptation of form to thought
that is seen only in the work of a great poet.
MORRIS ROSENFELD
I have a little boy, a fine little fellow is he! When I see him it appears to me the
whole world is mine.
Only rarely, rarely I see him, my pretty little son, when he is awake; I find him
always asleep, I see him only at night.
My work drives me out early and brings me home late; oh, my own flesh is a
stranger to me; oh, strange to me the glances of my child!
I come home in anguish and shrouded in darkness—my pale wife tells how nicely
the child plays.
Is it not allowed to rest even one day in the week and to be at least one day free
from the angry growl of the boss, his gloomy mien, his terrible looks; to forget the
shop and the cries of the foreman; to forget slavery, to forget woe? You wish to
forget yourself and be rested? Never mind, you will soon go to your rest!
Soon the trees and flowers will have withered; the last bird is already ending his
song; soon there will be cemeteries all around! Oh, how I should like to smell a
flower and feel, before the grass is dead, the breath of zephyr in the green fields!
You wish to be in the fields where it is airy and green? Never mind you will be
carried there soon enough!
The brook is silvery and glistens beautifully; the waves are covered with a
heavenly grace. Oh, how good it is to bathe there! How I should enjoy leaping into
it! My body is weakened from the dreadful work,—how they both would refresh
me! Oh, you wish to make your ablution in the brooks? Be not frightened, you will
soon receive your ablution!
The sweatshop is dark and smoky and small. How can my white blouse be clean
there? In the dirty shop cleanliness is unknown to me. How a pure white shirt
adorns a man! How proper for a noble body it is, in order to be free to work
humanely and be clean withal! You wish now to dress yourself in white? They will
dress you, and dress you quickly enough!
The woods are breezy, in the woods it is cool. How good to dream there quietly!
The little birds sing pleasantly; but in the shop there is noise, and the air is
suffocating! Oh, you wish to be cool?
Of what avail is a forest to you? It will not be long before you will be cold.
’Tis good to have a dear companion. In adversity he gives hope, in misery—
courage. A dear companion sweetens your being, and he gives you a zest for life.
And I am orphaned alone like a stone, there are no companions, I am all by myself
—you will soon have companions without end; they swarm already and are waiting
for you!
I see there a pale operator all absorbed in his work. Ever since I remember him,
he has been sewing and using up his strength.
Months fly, and years pass away, and the pale faced one still bends over his work
and struggles with the unfeeling machine.
I stand and look at his face; his face is besmutted and covered with sweat. I feel
that it is not bodily strength that works in him but the incitement of the spirit.
And the tears fall in succession from day break until fall of night and water the
clothes and enter into the seams.
Pray how long will the weak one drive the bloody wheel? Who can tell his end?
Who knows the terrible secret?
Hard, very hard to answer that! But one thing is certain: when the work will have
killed him another will be sitting in his place and sewing.
I feel no strength, it is all used up; the iron falls from my hand, and yet the tear,
the silent tear, the tear, the tear boils more and more.
My head whirls, my heart breaks. I ask in woe: “Oh, tell me, my friend in
adversity and pain, O tear, why not dry up in seething.”
“Are you perhaps a messenger and announce that other tears are coming? I
should like to know it; say, when will the great woe be ended?”
I should have asked more of the turbulent tear; but suddenly there began to flow
more tears, tears without measure, and I at once understood that the river of tears
is very deep.
Not only the flowers are mine, nay, even the boards of the coffin are mine!
And not only the boards of the coffin—you shrouds, you, too, are mine! He has it
all through my work, my poor work—oh, all and all is mine!
Then the dead one passed away in the air with cries:
“You will pay for it yet! And he clenched his fist and threatened the world.”
The poet’s love for nature, the human longing of the worker
imprisoned in the city for the country, which he has known but
which is now beyond his reach, is expressed in the nightingale’s
challenge to the laborer:
“Summer is here, summer is here! I shall not sing to you eternally, for finally my
hour too will strike—a dark crow will occupy my branch, the holy song will cease.
How long must I sing to you from the tree of the golden dream of freedom and
love? Rise and let me not urge you any longer! The heaven will not remain
eternally blue! Summer is here, summer is here! Now one can pass a merry time,
for just like you who are fading at your machine, everything will in the end wither
and be carried away.”
The machines in the shop roar so wildly that often I forget in the roar that I am; I
am lost in the terrible tumult, my ego disappears, I am a machine. I work and work
and work without end. I am busy and busy and busy at all time. For what and for
when? I know not, I ask not! How should a machine ever come to think?
There are no feelings, no thoughts, no reason; the bitter bloody work kills the
noblest, the most beautiful and best, the richest, the deepest, the highest, which life
possesses. The seconds, minutes and hours fly; the nights like the days pass as
swiftly as sails; I drive the machine just as if I wished to catch them; I chase
without avail, I chase without end.
The clock in the workshop does not rest; it keeps on pointing and ticking and
waking in succession. A man once told me the meaning of its pointing and waking
—that there was a reason in it; as if through a dream I remember it all; the clock
awakens life and sense in me, and something else—I forget what; ask me not, I
know not, I know not, I am a machine!
And at times, when I hear the clock, I understand quite differently its pointing,
its language; it seems to me as if the unrest[7] egged me on so that I should work
more, more, much more. In its sound I hear only the angry words of the boss; in
the two hands I see his gloomy look. The clock, I shudder—it seems to me it drives
me and calls me machine, and cries out to me “sew”!
Only when the wild tumult subsides, and the master is away for the midday
hour, day begins to dawn in my head, and a pain passes through my heart; I feel
my wound, and bitter tears and boiling tears wet my meager meal, my bread; it
chokes me, I can eat no more, I cannot! O, horrible toil! O, bitter necessity.
The shop at the midday hour appears to me like a bloody battlefield where all are
at rest; about me I see lying the dead, and the blood that has been spilled cries
from the earth. A minute later—the tocsin is sounded, the dead arise, the battle is
renewed. The corpses fight for strangers, for strangers, and they battle and fall and
disappear into night.
I look at the battlefield in bitter anger, in terror, with a feeling of revenge, with a
hellish pain. The clock now I hear it aright. It is calling: “An end to slavery, an end
shall it be”! It vivifies my reason, my feelings and shows how the hours fly;
miserable I shall be as long as I am silent, lost, as long as I remain what I am.
The man that sleeps in me begins to waken—the slave that wakens in me is put
to sleep. Now the right hour has come, an end to misery, an end let it be! But
suddenly—the whistle, the boss, an alarm! I lose my reason, forget where I am;
there is a tumult, the battle. Oh, my ego is lost! I know not, I care not, I am a
machine!
But even if he can for a time forget the toil and trouble of the world
in a personal joy, his first love is with the workers and with them he
asks to have his Resting Place—
Seek me not ’mid blooming meadows,
Not there my spirit you can trace,
Where workers toil like spectral shadows,
’Tis there you’ll find my resting place.
CHRISTINA MERRIMAN