100% found this document useful (4 votes)
965 views

Java Programming 8th Edition Joyce Farrell Download PDF

ebook

Uploaded by

aylbiraa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (4 votes)
965 views

Java Programming 8th Edition Joyce Farrell Download PDF

ebook

Uploaded by

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

Full download ebook at ebookgate.

com

Java Programming 8th Edition Joyce Farrell

https://ebookgate.com/product/java-
programming-8th-edition-joyce-farrell/

Download more ebook from https://ebookgate.com


More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Java Programming 6th Edition Joyce Farrell

https://ebookgate.com/product/java-programming-6th-edition-joyce-
farrell/

Programming Logic and Design Comprehensive 8th Edition


Joyce Farrell

https://ebookgate.com/product/programming-logic-and-design-
comprehensive-8th-edition-joyce-farrell/

Programming Logic and Design Comprehensive 7th Edition


Joyce Farrell

https://ebookgate.com/product/programming-logic-and-design-
comprehensive-7th-edition-joyce-farrell/

Computer Programming for Teens 1st Edition Mary E.


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/

JXTA Java P2P Programming 1st Edition Daniel Brookshier

https://ebookgate.com/product/jxta-java-p2p-programming-1st-
edition-daniel-brookshier/

Java Network Programming Third Edition Elliotte Rusty


Harold

https://ebookgate.com/product/java-network-programming-third-
edition-elliotte-rusty-harold/

A Guide To Programming in Java Java 2 Platform Standard


Edition 5 Beth Brown

https://ebookgate.com/product/a-guide-to-programming-in-java-
java-2-platform-standard-edition-5-beth-brown/

Functional Programming in Java Harnessing the Power Of


Java 8 Lambda Expressions 1st Edition Venkat
Subramaniam

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

Library of Congress Control Number: 2014956152


ISBN: 978-1-285-85691-9
Cengage Learning
20 Channel Center Street
Boston, MA 02210
USA

Cengage Learning is a leading provider of customized learning


solutions with office locations around the globe, including Singapore,
the United Kingdom, Australia, Mexico, Brazil, and Japan. Locate your
local office at www.cengage.com/global.

Cengage Learning products are represented in Canada by Nelson


Education, Ltd.

All images © 2016 Cengage Learning®. All rights reserved.


To learn more about Cengage Learning Solutions, visit
www.cengage.com.
Purchase any of our products at your local college store
or at our preferred online store www.cengagebrain.com.

Printed in the U nited States of America


Print N umber: 01 Print Year: 2015

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

CHAPT ER 1 Creating Java Programs . . . . . . . . . . . 1


Learning Programming Terminology . . . . . . . . . . . . . . 2
Comparing Procedural and Object-Oriented
Programming Concepts . . . . . . . . . . . . . . . . . . 6
Procedural Programming . . . . . . . . . . . . . . . . . . 6
Object-Oriented Programming . . . . . . . . . . . . . . . . 6
Understanding Classes, Objects, and Encapsulation . . . . . . 7
Understanding Inheritance and Polymorphism . . . . . . . . . 9
Features of the Java Programming Language . . . . . . . . . . 11
Java Program Types . . . . . . . . . . . . . . . . . . . . 12
Analyzing a Java Application that Produces Console Output . . . . 13
Understanding the Statement that Produces the Output . . . . . 14
Understanding the First Class . . . . . . . . . . . . . . . 15
Indent Style . . . . . . . . . . . . . . . . . . . . . . . 18
Understanding the main() Method . . . . . . . . . . . . . 19
Saving a Java Class . . . . . . . . . . . . . . . . . . . . 21
Compiling a Java Class and Correcting Syntax Errors . . . . . . . 23
Compiling a Java Class . . . . . . . . . . . . . . . . . . . 23
Correcting Syntax Errors . . . . . . . . . . . . . . . . . . 24
Running a Java Application and Correcting Logic Errors . . . . . . 29
Running a Java Application . . . . . . . . . . . . . . . . . 29
Modifying a Compiled Java Class . . . . . . . . . . . . . . 30
Correcting Logic Errors . . . . . . . . . . . . . . . . . . 31
Adding Comments to a Java Class . . . . . . . . . . . . . . . 32
Creating a Java Application that Produces GUI Output . . . . . . 35
Finding Help . . . . . . . . . . . . . . . . . . . . . . . . 38
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . . 39
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . . 41

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

CHAPT ER 2 Using Data . . . . . . . . . . . . . . . . . 53


Declaring and Using Constants and Variables . . . . . . . . . . 54
Declaring Variables . . . . . . . . . . . . . . . . . . . . 55
Declaring Named Constants . . . . . . . . . . . . . . . . 56
The Scope of Variables and Constants . . . . . . . . . . . . 58
Concatenating Strings to Variables and Constants . . . . . . . 58
Pitfall: Forgetting that a Variable Holds
One Value at a Time . . . . . . . . . . . . . . . . . . . 60
Learning About Integer Data Types . . . . . . . . . . . . . . 64
Using the boolean Data Type . . . . . . . . . . . . . . . . . 70
Learning About Floating-Point Data Types . . . . . . . . . . . . 71
Using the char Data Type . . . . . . . . . . . . . . . . . . 72
Using the Scanner Class to Accept Keyboard Input . . . . . . . 78
Pitfall: Using nextLine() Following One of the
Other Scanner Input Methods . . . . . . . . . . . . . . 81
Using the JOptionPane Class to Accept GUI Input . . . . . . . 87
Using Input Dialog Boxes . . . . . . . . . . . . . . . . . . 87
Using Confirm Dialog Boxes . . . . . . . . . . . . . . . . 91
Performing Arithmetic . . . . . . . . . . . . . . . . . . . . 93
Associativity and Precedence . . . . . . . . . . . . . . . . 95
Writing Arithmetic Statements Efficiently . . . . . . . . . . . 96
Pitfall: Not Understanding Imprecision
in Floating-Point Numbers . . . . . . . . . . . . . . . . 96
Understanding Type Conversion . . . . . . . . . . . . . . . 101
Automatic Type Conversion . . . . . . . . . . . . . . . . 101
Explicit Type Conversions . . . . . . . . . . . . . . . . 102
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 106
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 107

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

Chapter Summary . . . . . . . . . . . . . . . . . . . . . 111


Review Questions . . . . . . . . . . . . . . . . . . . . . 111
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 114
Programming Exercises . . . . . . . . . . . . . . . . . 114
viii Debugging Exercises . . . . . . . . . . . . . . . . . . 116
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 117
Case Problems . . . . . . . . . . . . . . . . . . . . . 118

CHAPT ER 3 Using Methods, Classes, and Objects . . . . 119


Understanding Method Calls and Placement . . . . . . . . . . 120
Understanding Method Construction . . . . . . . . . . . . . 123
Access Specifiers . . . . . . . . . . . . . . . . . . . . 123
Return Type . . . . . . . . . . . . . . . . . . . . . . 124
Method Name . . . . . . . . . . . . . . . . . . . . . 125
Parentheses . . . . . . . . . . . . . . . . . . . . . . 125
Adding Parameters to Methods . . . . . . . . . . . . . . . 129
Creating a Method that Receives a Single Parameter . . . . . 130
Creating a Method that Requires Multiple Parameters . . . . . 133
Creating Methods that Return Values . . . . . . . . . . . . . 136
Chaining Method Calls . . . . . . . . . . . . . . . . . . 138
Learning About Classes and Objects . . . . . . . . . . . . . 142
Creating a Class . . . . . . . . . . . . . . . . . . . . . 145
Creating Instance Methods in a Class . . . . . . . . . . . . 147
Organizing Classes . . . . . . . . . . . . . . . . . . . 150
Declaring Objects and Using their Methods . . . . . . . . . . 154
Understanding Data Hiding . . . . . . . . . . . . . . . . 156
An Introduction to Using Constructors . . . . . . . . . . . . 159
Understanding that Classes Are Data Types . . . . . . . . . . 163
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 168
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 168
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 170
Review Questions . . . . . . . . . . . . . . . . . . . . . 171
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 174
Programming Exercises . . . . . . . . . . . . . . . . . 174
Debugging Exercises . . . . . . . . . . . . . . . . . . 177
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 178
Case Problems . . . . . . . . . . . . . . . . . . . . . 179

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

Creating and Calling Constructors with Parameters . . . . . . . 200


Overloading Constructors . . . . . . . . . . . . . . . . 201
Learning About the this Reference . . . . . . . . . . . . . 205
Using the this Reference to Make Overloaded Constructors
More Efficient . . . . . . . . . . . . . . . . . . . . . 209
Using static Fields . . . . . . . . . . . . . . . . . . . 213
Using Constant Fields . . . . . . . . . . . . . . . . . . 215
Using Automatically Imported, Prewritten Constants
and Methods . . . . . . . . . . . . . . . . . . . . . . 220
The Math Class . . . . . . . . . . . . . . . . . . . . 221
Importing Classes that Are Not Imported Automatically . . . . 223
Using the LocalDate Class . . . . . . . . . . . . . . . 224
Understanding Composition and Nested Classes . . . . . . . . 230
Composition . . . . . . . . . . . . . . . . . . . . . . 230
Nested Classes . . . . . . . . . . . . . . . . . . . . . 232
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 234
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 234
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 236
Review Questions . . . . . . . . . . . . . . . . . . . . . 236
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 239
Programming Exercises . . . . . . . . . . . . . . . . . 239
Debugging Exercises . . . . . . . . . . . . . . . . . . 242
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 242
Case Problems . . . . . . . . . . . . . . . . . . . . . 243

CHAPT ER 5 Making Decisions . . . . . . . . . . . . . 245


Planning Decision-Making Logic . . . . . . . . . . . . . . . 246
The if and if…else Statements . . . . . . . . . . . . . . 248
The if Statement . . . . . . . . . . . . . . . . . . . . 248
Pitfall: Misplacing a Semicolon in an if Statement . . . . . . 249
Pitfall: Using the Assignment Operator Instead
of the Equivalency Operator . . . . . . . . . . . . . . 250

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

Pitfall: Attempting to Compare Objects


Using the Relational Operators . . . . . . . . . . . . . 251
The if…else Statement . . . . . . . . . . . . . . . . . 251
Using Multiple Statements in if and if…else Clauses . . . . 254
x Nesting if and if…else Statements . . . . . . . . . . . . 260
Using Logical AND and OR Operators . . . . . . . . . . . . 263
The AND Operator . . . . . . . . . . . . . . . . . . . . 263
The OR Operator . . . . . . . . . . . . . . . . . . . . 265
Short-Circuit Evaluation . . . . . . . . . . . . . . . . . . 266
Making Accurate and Efficient Decisions . . . . . . . . . . . 269
Making Accurate Range Checks . . . . . . . . . . . . . . 270
Making Efficient Range Checks . . . . . . . . . . . . . . 272
Using && and || Appropriately . . . . . . . . . . . . . . 273
Using the switch Statement . . . . . . . . . . . . . . . . 274
Using the Conditional and NOT Operators . . . . . . . . . . . 280
Using the NOT Operator . . . . . . . . . . . . . . . . . 281
Understanding Operator Precedence . . . . . . . . . . . . . 282
Adding Decisions and Constructors
to Instance Methods . . . . . . . . . . . . . . . . . . . 285
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 289
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 289
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 291
Review Questions . . . . . . . . . . . . . . . . . . . . . 291
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 294
Programming Exercises . . . . . . . . . . . . . . . . . 294
Debugging Exercises . . . . . . . . . . . . . . . . . . 297
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 297
Case Problems . . . . . . . . . . . . . . . . . . . . . 299

CHAPT ER 6 Looping . . . . . . . . . . . . . . . . . 301


Learning About the Loop Structure . . . . . . . . . . . . . . 302
Creating while Loops . . . . . . . . . . . . . . . . . . 303
Writing a Definite while Loop . . . . . . . . . . . . . . 303
Pitfall: Failing to Alter the Loop Control Variable
Within the Loop Body . . . . . . . . . . . . . . . . . 305
Pitfall: Unintentionally Creating a Loop with
an Empty Body . . . . . . . . . . . . . . . . . . . . 306

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

CHAPT ER 7 Characters, Strings, and


the StringBuilder . . . . . . . . . . . . 353
Understanding String Data Problems . . . . . . . . . . . . . 354
Using Character Class Methods . . . . . . . . . . . . . . 355
Declaring and Comparing String Objects . . . . . . . . . . 359
Comparing String Values . . . . . . . . . . . . . . . . 359
Empty and null Strings . . . . . . . . . . . . . . . . . 363
Using Other String Methods . . . . . . . . . . . . . . . 365
Converting String Objects to Numbers . . . . . . . . . . 369

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

Learning About the StringBuilder


and StringBuffer Classes . . . . . . . . . . . . . . 374
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 381
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 382
xii Chapter Summary . . . . . . . . . . . . . . . . . . . . . 382
Review Questions . . . . . . . . . . . . . . . . . . . . . 383
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 385
Programming Exercises . . . . . . . . . . . . . . . . . 385
Debugging Exercises . . . . . . . . . . . . . . . . . . 388
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 388
Case Problems . . . . . . . . . . . . . . . . . . . . . 391

CHAPT ER 8 Arrays . . . . . . . . . . . . . . . . . . 393


Declaring Arrays . . . . . . . . . . . . . . . . . . . . . 394
Initializing an Array . . . . . . . . . . . . . . . . . . . . 399
Using Variable Subscripts with an Array . . . . . . . . . . . . 402
Using the Enhanced for Loop . . . . . . . . . . . . . . 403
Using Part of an Array . . . . . . . . . . . . . . . . . . 404
Declaring and Using Arrays of Objects . . . . . . . . . . . . 406
Using the Enhanced for Loop with Objects . . . . . . . . . 408
Manipulating Arrays of Strings . . . . . . . . . . . . . 408
Searching an Array and Using Parallel Arrays . . . . . . . . . 414
Using Parallel Arrays . . . . . . . . . . . . . . . . . . . 415
Searching an Array for a Range Match . . . . . . . . . . . 418
Passing Arrays to and Returning Arrays from Methods . . . . . 422
Returning an Array from a Method . . . . . . . . . . . . . 426
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 428
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 428
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 429
Review Questions . . . . . . . . . . . . . . . . . . . . . 430
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 433
Programming Exercises . . . . . . . . . . . . . . . . . 433
Debugging Exercises . . . . . . . . . . . . . . . . . . 435
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 435
Case Problems . . . . . . . . . . . . . . . . . . . . . 438

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

Sorting Array Elements Using the Insertion Sort Algorithm . . . . 448


Using Two-Dimensional and Other Multidimensional Arrays . . . . 452
Passing a Two-Dimensional Array to a Method . . . . . . . . 454
Using the length Field with a Two-Dimensional Array . . . . 455
Understanding Ragged Arrays . . . . . . . . . . . . . . . 456
Using Other Multidimensional Arrays . . . . . . . . . . . . 456
Using the Arrays Class . . . . . . . . . . . . . . . . . . 459
Using the ArrayList Class . . . . . . . . . . . . . . . . 467
Creating Enumerations . . . . . . . . . . . . . . . . . . . 472
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 479
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 479
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 480
Review Questions . . . . . . . . . . . . . . . . . . . . . 481
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 484
Programming Exercises . . . . . . . . . . . . . . . . . 484
Debugging Exercises . . . . . . . . . . . . . . . . . . 486
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 487
Case Problems . . . . . . . . . . . . . . . . . . . . . 490

CHAPT ER 10 Introduction to Inheritance . . . . . . . . . 491


Learning About the Concept of Inheritance . . . . . . . . . . 492
Diagramming Inheritance Using the UML . . . . . . . . . . 492
Inheritance Terminology . . . . . . . . . . . . . . . . . 495
Extending Classes . . . . . . . . . . . . . . . . . . . . . 496
Overriding Superclass Methods . . . . . . . . . . . . . . . 502
Using the @Override Tag . . . . . . . . . . . . . . . . 504
Calling Constructors During Inheritance . . . . . . . . . . . . 507
Using Superclass Constructors that
Require Arguments . . . . . . . . . . . . . . . . . . 508
Accessing Superclass Methods . . . . . . . . . . . . . . . 513
Comparing this and super . . . . . . . . . . . . . . . 515
Employing Information Hiding . . . . . . . . . . . . . . . . 516

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

Methods You Cannot Override . . . . . . . . . . . . . . . . 518


A Subclass Cannot Override static Methods in
Its Superclass . . . . . . . . . . . . . . . . . . . . 518
A Subclass Cannot Override final Methods in
Its Superclass . . . . . . . . . . . . . . . . . . . . 522
xiv
A Subclass Cannot Override Methods
in a final Superclass . . . . . . . . . . . . . . . . 523
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 525
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 525
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 526
Review Questions . . . . . . . . . . . . . . . . . . . . . 527
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 530
Programming Exercises . . . . . . . . . . . . . . . . . 530
Debugging Exercises . . . . . . . . . . . . . . . . . . 533
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 534
Case Problems . . . . . . . . . . . . . . . . . . . . . 535

CHAPT ER 11 Advanced Inheritance Concepts . . . . . . . 537


Creating and Using Abstract Classes . . . . . . . . . . . . . 538
Using Dynamic Method Binding . . . . . . . . . . . . . . . 547
Using a Superclass as a Method Parameter Type . . . . . . 549
Creating Arrays of Subclass Objects . . . . . . . . . . . . . 551
Using the Object Class and Its Methods . . . . . . . . . . . 554
Using the toString() Method . . . . . . . . . . . . . 556
Using the equals() Method . . . . . . . . . . . . . . . 559
Using Inheritance to Achieve Good Software Design . . . . . . 564
Creating and Using Interfaces . . . . . . . . . . . . . . . . 565
Creating Interfaces to Store Related Constants . . . . . . . 570
Creating and Using Packages . . . . . . . . . . . . . . . . 574
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 580
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 580
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 581
Review Questions . . . . . . . . . . . . . . . . . . . . . 582
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 585
Programming Exercises . . . . . . . . . . . . . . . . . 585
Debugging Exercises . . . . . . . . . . . . . . . . . . 589
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 590
Case Problems . . . . . . . . . . . . . . . . . . . . . 590
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 12 Exception Handling . . . . . . . . . . . . 593
Learning About Exceptions . . . . . . . . . . . . . . . . . 594
Trying Code and Catching Exceptions . . . . . . . . . . . . 599
Using a try Block to Make Programs “Foolproof” . . . . . . 604
Declaring and Initializing Variables in try…catch Blocks . . . 606 xv

Throwing and Catching Multiple Exceptions . . . . . . . . . . 609


Using the finally Block . . . . . . . . . . . . . . . . . 615
Understanding the Advantages of Exception Handling . . . . . . 618
Specifying the Exceptions that a Method Can Throw . . . . . . 621
Tracing Exceptions Through the Call Stack . . . . . . . . . . 626
Creating Your Own Exception Classes . . . . . . . . . . . 630
Using Assertions . . . . . . . . . . . . . . . . . . . . . 634
Displaying the Virtual Keyboard . . . . . . . . . . . . . . . 650
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 653
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 654
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 655
Review Questions . . . . . . . . . . . . . . . . . . . . . 656
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 659
Programming Exercises . . . . . . . . . . . . . . . . . 659
Debugging Exercises . . . . . . . . . . . . . . . . . . 662
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 662
Case Problems . . . . . . . . . . . . . . . . . . . . . 663

CHAPT ER 13 File Input and Output . . . . . . . . . . . . 665


Understanding Computer Files . . . . . . . . . . . . . . . 666
Using the Path and Files Classes . . . . . . . . . . . . . 667
Creating a Path . . . . . . . . . . . . . . . . . . . . . 668
Retrieving Information About a Path . . . . . . . . . . . . 669
Converting a Relative Path to an Absolute One . . . . . . . . 670
Checking File Accessibility . . . . . . . . . . . . . . . . 671
Deleting a Path . . . . . . . . . . . . . . . . . . . . . 673
Determining File Attributes . . . . . . . . . . . . . . . . 674
File Organization, Streams, and Buffers . . . . . . . . . . . . 678
Using Java’s IO Classes . . . . . . . . . . . . . . . . . . 680
Writing to a File . . . . . . . . . . . . . . . . . . . . . 683
Reading from a File . . . . . . . . . . . . . . . . . . . 685

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

Creating and Using Sequential Data Files . . . . . . . . . . . 687


Learning About Random Access Files . . . . . . . . . . . . 693
Writing Records to a Random Access Data File . . . . . . . . 697
Reading Records from a Random Access Data File . . . . . . . 704
xvi Accessing a Random Access File Sequentially . . . . . . . . 704
Accessing a Random Access File Randomly . . . . . . . . . 705
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 719
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 719
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 720
Review Questions . . . . . . . . . . . . . . . . . . . . . 721
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 724
Programming Exercises . . . . . . . . . . . . . . . . . 724
Debugging Exercises . . . . . . . . . . . . . . . . . . 726
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 727
Case Problems . . . . . . . . . . . . . . . . . . . . . 727

CHAPT ER 14 Introduction to Swing Components . . . . . 729


Understanding Swing Components . . . . . . . . . . . . . 730
Using the JFrame Class . . . . . . . . . . . . . . . . . . 731
Customizing a JFrame’s Appearance . . . . . . . . . . . 734
Using the JLabel Class . . . . . . . . . . . . . . . . . . 738
Changing a JLabel’s Font . . . . . . . . . . . . . . . . 740
Using a Layout Manager . . . . . . . . . . . . . . . . . . 743
Extending the JFrame Class . . . . . . . . . . . . . . . . 746
Adding JTextFields, JButtons, and Tool Tips to a
JFrame . . . . . . . . . . . . . . . . . . . . . . . . 748
Adding JTextFields . . . . . . . . . . . . . . . . . . 748
Adding JButtons . . . . . . . . . . . . . . . . . . . 750
Using Tool Tips . . . . . . . . . . . . . . . . . . . . . 752
Learning About Event-Driven Programming . . . . . . . . . . 755
Preparing Your Class to Accept Event Messages . . . . . . . 756
Telling Your Class to Expect Events to Happen . . . . . . . 757
Telling Your Class How to Respond to Events . . . . . . . . 757
An Event-Driven Program . . . . . . . . . . . . . . . . . 757
Using Multiple Event Sources . . . . . . . . . . . . . . . 759
Using the setEnabled() Method . . . . . . . . . . . . 761
Understanding Swing Event Listeners . . . . . . . . . . . . 764

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

CHAPT ER 15 Advanced GUI Topics . . . . . . . . . . . 791


Understanding the Content Pane . . . . . . . . . . . . . . 792
Using Color . . . . . . . . . . . . . . . . . . . . . . . 795
Learning More About Layout Managers . . . . . . . . . . . . 797
Using BorderLayout . . . . . . . . . . . . . . . . . 798
Using FlowLayout . . . . . . . . . . . . . . . . . . . 800
Using GridLayout . . . . . . . . . . . . . . . . . . . 802
Using CardLayout . . . . . . . . . . . . . . . . . . . 803
Using Advanced Layout Managers . . . . . . . . . . . . . 805
Using the JPanel Class . . . . . . . . . . . . . . . . . . 813
Creating JScrollPanes . . . . . . . . . . . . . . . . . 821
A Closer Look at Events and Event Handling . . . . . . . . . . 824
An Event-Handling Example: KeyListener . . . . . . . . 827
Using AWTEvent Class Methods . . . . . . . . . . . . . . 830
Understanding x- and y-Coordinates . . . . . . . . . . . . 832
Handling Mouse Events . . . . . . . . . . . . . . . . . . 832
Using Menus . . . . . . . . . . . . . . . . . . . . . . . 837
Using Specialized Menu Items . . . . . . . . . . . . . . . 841
Using addSeparator() . . . . . . . . . . . . . . . . 843
Using setMnemonic() . . . . . . . . . . . . . . . . . 843
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 848
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 849

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

Chapter Summary . . . . . . . . . . . . . . . . . . . . . 850


Review Questions . . . . . . . . . . . . . . . . . . . . . 851
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 853
Programming Exercises . . . . . . . . . . . . . . . . . 853
xviii Debugging Exercises . . . . . . . . . . . . . . . . . . 855
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 855
Case Problems . . . . . . . . . . . . . . . . . . . . . 859

CHAPT ER 16 Graphics . . . . . . . . . . . . . . . . . 861


Learning About Rendering Methods . . . . . . . . . . . . . 862
Drawing Strings . . . . . . . . . . . . . . . . . . . . . . 865
Repainting . . . . . . . . . . . . . . . . . . . . . . . 867
Setting a Font . . . . . . . . . . . . . . . . . . . . . 869
Using Color . . . . . . . . . . . . . . . . . . . . . . 870
Drawing Lines and Shapes . . . . . . . . . . . . . . . . . 874
Drawing Lines . . . . . . . . . . . . . . . . . . . . . 874
Drawing Unfilled and Filled Rectangles . . . . . . . . . . . 875
Drawing Clear Rectangles . . . . . . . . . . . . . . . . 875
Drawing Rounded Rectangles . . . . . . . . . . . . . . . 876
Drawing Shadowed Rectangles . . . . . . . . . . . . . . 878
Drawing Ovals . . . . . . . . . . . . . . . . . . . . . 879
Drawing Arcs . . . . . . . . . . . . . . . . . . . . . . 880
Creating Polygons . . . . . . . . . . . . . . . . . . . . 881
Copying an Area . . . . . . . . . . . . . . . . . . . . 883
Using the paint() Method with JFrames . . . . . . . . . 883
Learning More About Fonts . . . . . . . . . . . . . . . . . 891
Discovering Screen Statistics . . . . . . . . . . . . . . . 893
Discovering Font Statistics . . . . . . . . . . . . . . . . 894
Drawing with Java 2D Graphics . . . . . . . . . . . . . . . 898
Specifying the Rendering Attributes . . . . . . . . . . . . 899
Setting a Drawing Stroke . . . . . . . . . . . . . . . . . 901
Creating Objects to Draw . . . . . . . . . . . . . . . . . 902
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 910
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 911
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 911
Review Questions . . . . . . . . . . . . . . . . . . . . . 912
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 915

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

APPENDIX B Data Representation . . . . . . . . . . . . 925


Understanding Numbering Systems . . . . . . . . . . . . . 926
Representing Numeric Values . . . . . . . . . . . . . . . . 927
Representing Character Values . . . . . . . . . . . . . . . 929
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 930

APPENDIX C Formatting Output . . . . . . . . . . . . . 931


Rounding Numbers . . . . . . . . . . . . . . . . . . . . 932
Using the printf() Method . . . . . . . . . . . . . . . . 933
Specifying a Number of Decimal Places to
Display with printf() . . . . . . . . . . . . . . . . 936
Specifying a Field Size with printf() . . . . . . . . . . . 937
Using the Optional Argument Index with printf() . . . . . 938
Using the DecimalFormat Class . . . . . . . . . . . . . 939
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 940

APPENDIX D Generating Random Numbers . . . . . . . . 941


Understanding Computer-Generated Random Numbers . . . . . 942
Using the Math.random() Method . . . . . . . . . . . . . 943
Using the Random Class . . . . . . . . . . . . . . . . . . 944
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 947

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

APPENDIX E Javadoc . . . . . . . . . . . . . . . . . 949


The Javadoc Documentation Generator . . . . . . . . . . . . 950
Javadoc Comment Types . . . . . . . . . . . . . . . . . . 950
Generating Javadoc Documentation . . . . . . . . . . . . . 952
xx Specifying Visibility of Javadoc Documentation . . . . . . . . 955
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 956

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.

Organization and Coverage


Java Programming, Eighth Edition, presents Java programming concepts, enforcing good
style, logical thinking, and the object-oriented paradigm. Objects are covered right from the
beginning, earlier than in many other textbooks. You create your first Java program in
Chapter 1. Chapters 2, 3, and 4 increase your understanding of how data, classes, objects,
and methods interact in an object-oriented environment.
Chapters 5 and 6 explore input and repetition structures, which are the backbone of
programming logic and essential to creating useful programs in any language. You learn the
special considerations of string and array manipulation in Chapters 7, 8, and 9.

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.

MODERNIZED OVERRIDING: The @Override tag is introduced.


EXPANDED COVERAGE OF THE EQUALS() METHOD: The book provides a thorough
explanation of the difference between overloading and overriding the equals() method.
PROGRAMMING EXERCISES: Each chapter contains several new programming exercises
not seen in previous editions. All exercises and their solutions from the previous edition
that were replaced in this edition are still available in the Instructor’s Resource Kit.
Additionally, Java Programming, Eighth Edition, includes the following features:
OBJECTIVES: Each chapter begins with a list of objectives so you know the topics that will
be presented in the chapter. In addition to providing a quick reference to topics covered,
this feature provides a useful study aid.
YOU DO IT: In each chapter, step-by-step exercises help students create multiple working
programs that emphasize the logic a programmer uses in choosing statements to include.
These sections provide a means for students to achieve success on their own—even those
in online or distance learning classes.
NOTES: These highlighted tips provide additional information—for example, an
alternative method of performing a procedure, another term for a concept, background
information on a technique, or a common error to avoid.

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

Up for Discussion: A few thought-provoking questions concerning programming in


general or Java in particular supplement each chapter. The questions can be used to
start classroom or online discussions, or to develop and encourage research, writing,
and language skills.
Programming Exercises and Solutions: Each chapter is accompanied by several
xxv
programming exercises to supplement those offered in the text. Instructors can use
these exercises as additional or alternate assignments, or as the basis for lectures.
Test Bank: Cengage Learning Testing Powered by Cognero is a flexible, online system
that allows you to:
Author, edit, and manage test bank content from multiple Cengage Learning
solutions.
Create multiple test versions in an instant.
Deliver tests from your LMS, your classroom, or anywhere you want.
PowerPoint Presentations: This text provides PowerPoint slides to accompany each
chapter. Slides may be used to guide classroom presentations, to make available to
students for chapter review, or to print as classroom handouts. Files are provided for every
figure in the text. Instructors may use the files to customize PowerPoint slides, illustrate
quizzes, or create handouts.
Solutions: Solutions to “You Do It” exercises and all end-of-chapter exercises are
available. Annotated solutions are provided for some of the multiple-choice Review
Questions. For example, if students are likely to debate answer choices or not understand
the choice deemed to be the correct one, a rationale is provided.

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.

To the User of the Data Files


To complete the steps and projects in this book, you need data files that have been created
specifically for this book. Your instructor will provide the data files to you. You also can
obtain the files electronically from www.CengageBrain.com. Find the ISBN of your title on the
back cover of your book, then enter the ISBN in the search box at the top of the Cengage
Brain home page. You can find the data files on the product page that opens. Note that
you can use a computer in your school lab or your own computer to complete the exercises
in this book.

Using Your Own Computer


To use your own computer to complete the steps and exercises, you need the following:
Software: Java SE 8, available from www.oracle.com/technetwork/java/index.html. Although
almost all of the examples in this book will work with earlier versions of Java, this book was
created using Java 8. The book clearly points out the few cases when an example is based on
Java 7 and will not work with earlier versions of Java. You also need a text editor, such as
Notepad. A few exercises ask you to use a browser for research.
Hardware: If you are using Windows 8, the Java Web site suggests at least 128 MB of
memory and at least 181 MB of disk space. For other operating system requirements, see
http://java.com/en/download/help.

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

YOU DO IT sections walk


students through program
development step by step.

NOTES provide
additional information—
for example, another
location in the book that
expands on a topic, or a
common error to watch
out for.

The author does an awesome


job: the examples, problems,
VIDEO LESSONS help
and material are very easy to
explain important chapter
understand!
concepts. Videos are part
—Bernice Cunningham, of the text’s enhanced
Wayne County Community
CourseMate site.
College District
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

TWO TRUTHS & A LIE quizzes appear


after each chapter section, with
answers provided. The quiz contains
three statements based on the preceding
xxviii section of text—two statements are
true and one is false. Answers give
immediate feedback without “giving away”
answers to the multiple-choice questions
and programming problems later in
the chapter. Students also have the option
to take these quizzes electronically
through the enhanced CourseMate site.

DON'T DO IT sections at the end


of each chapter list advice for
avoiding common programming errors.

THE DON’T DO IT ICON illustrates


how NOT to do something—for
example, having a dead code
path in a program. This icon
provides a visual jolt to the student,

are NOT to be emulated and making


students more careful to recognize
problems in existing code.

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.

REVIEW QUESTIONS test


student comprehension of the
major ideas and techniques
presented. Twenty questions
follow each 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.
ASSESSMENT

DEBUGGING EXERCISES are


xxx included with each chapter because
examining programs critically and
closely is a crucial programming skill.
Students can download these exercises
at www.CengageBrain.com and through
the CourseMate available for this text.
These files are also available to
instructors through sso.cengage.com.

CASE PROBLEMS provide opportunities


to build more detailed programs that
continue to incorporate increasing
functionality throughout the book.

GAME ZONE EXERCISES are included


at the end of each chapter. Students can
create games as an additional entertaining
way to understand key programming
concepts.

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

In this chapter, you will:

Define basic programming terminology


Compare procedural and object-oriented programming
Describe the features of the Java programming language
Analyze a Java application that produces console output
Compile a Java class and correct syntax errors
Run a Java application and correct logic errors
Add comments to a Java class
Create a Java application that produces GUI output
Find help

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

Learning Programming Terminology


A computer program is a set of instructions that you write to tell a computer what to do.
Computer equipment, such as a monitor or keyboard, is hardware, and programs are
software. A program that performs a task for a user (such as calculating and producing
2 paychecks, word processing, or playing a game) is application software; a program that
manages the computer itself (such as Windows or Linux) is system software. The logic
behind any computer program, whether it is an application or system program, determines
the exact order of instructions needed to produce desired results. Much of this book describes
how to develop the logic to create application software.
All computer programs ultimately are converted to machine language. Machine language,
or machine code, is the most basic set of instructions that a computer can execute. Each type
of processor (the internal hardware that handles computer instructions) has its own set of
machine language instructions. Programmers often describe machine language using 1s and
0s to represent the on-and-off circuitry of computer systems.
The system that uses only 1s and 0s is the binary numbering system. Appendix B describes the binary
system in detail. Later in this chapter, you will learn that bytecode is the name for the binary code created
when Java programs are converted to machine language.

Machine language is a low-level programming language, or one that corresponds closely to a


computer processor’s circuitry. Low-level languages require you to use memory addresses for
specific machines when you create commands. This means that low-level languages are
difficult to use and must be customized for every type of machine on which a program runs.
Fortunately, programming has evolved into an easier task because of the development of
high-level programming languages. A high-level programming language allows you to use
a vocabulary of reasonable terms, such as read, write, or add, instead of the sequences of
1s and 0s that perform these tasks. High-level languages also allow you to assign single-word,
intuitive names to areas of computer memory where you store data. This means you can use
identifiers such as hoursWorked or rateOfPay, rather than having to remember their memory
locations. Currently, over 2,000 high-level programming languages are available to
developers; Java is one of them.
Each high-level language has its own syntax, or rules about how language elements are
combined correctly to produce usable statements. For example, depending on the specific
high-level language, you might use the verb print or write to produce output. All languages
have a specific, limited vocabulary (the language’s keywords) and a specific set of rules for
using that vocabulary. When you are learning a computer programming language, such as
Java, C++, or Visual Basic, you really are learning the vocabulary and syntax for that language.
Using a programming language, programmers write a series of program statements, similar
to English sentences, to carry out the tasks they want the program to perform. Program
statements are also known as commands because they are orders to the computer, such as
“output this word” or “add these two numbers.”

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

Plan program logic

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

Execute the program

Examine
program output

Are there runtime Yes


or output errors?

No

Figure 1-1 The program development process

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.

TWO TRUTHS & A LIE


Learning Programming Terminology

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.

1. Unlike a low-level programming language, a high-level programming language


allows you to use a vocabulary of reasonable terms instead of the sequences of
on-and-off switches that perform the corresponding tasks.
2. A syntax error occurs when you misuse a language; locating and repairing all
syntax errors is part of the process of debugging a program.
3. Logic errors are fairly easy to find because the software that translates a program
finds all the logic errors for you.

can usually be discovered only by examining a program’s output.


The false statement is #3. A language translator finds syntax errors, but logic errors

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

Comparing Procedural and Object-Oriented


Programming Concepts
Two popular approaches to writing computer programs are procedural programming and
object-oriented programming.
6

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:

Creating classes, which are blueprints for objects


Creating objects, which are specific instances of those classes
Creating applications that manipulate or use those objects

Programmers use OO as an abbreviation for object-oriented; it is pronounced “oh oh.” Object-oriented


programming is abbreviated OOP, and pronounced to rhyme with soup.

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

Understanding Classes, Objects, and Encapsulation


In object-oriented terminology, a class is a term that describes a group or collection of
objects with common properties. In the same way that a blueprint exists before any houses
are built from it, and a recipe exists before any cookies are baked from it, a class definition
exists before any objects are created from it. A class definition describes what attributes its
objects will have and what those objects will be able to do. Attributes are the characteristics
that define an object; they are properties of the object. When you learn a programming
language such as Java, you learn to work with two types of classes: those that have already
been developed by the language’s creators and your own new, customized classes.

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

An object is a specific, concrete instance of a class. Creating an instance is called


instantiation. You can create objects from classes that you write and from classes written by
other programmers, including Java’s creators. The values contained in an object’s properties
often differentiate instances of the same class from one another. For example, the class
Automobile describes what Automobile objects are like. Some properties of the Automobile
8 class are make, model, year, and color. Each Automobile object possesses the same attributes,
but not necessarily the same values for those attributes. One Automobile might be a 2010
white Ford Taurus and another might be a 2015 red Chevrolet Camaro. Similarly, your dog
has the properties of all Dogs, including a breed, name, age, and whether its shots are current.
The values of the properties of an object are referred to as the object’s state. In other words,
you can think of objects as roughly equivalent to nouns, and of their attributes as similar to
adjectives that describe the nouns.
When you understand an object’s class, you understand the characteristics of the object. If
your friend purchases an Automobile, you know it has a model name, and if your friend gets a
Dog, you know the dog has a breed. Knowing what attributes exist for classes allows you to ask
appropriate questions about the states or values of those attributes. For example, you might
ask how many miles the car gets per gallon, but you would not ask whether the car has had
shots. Similarly, in a GUI operating environment, you expect each component to have
specific, consistent attributes and methods, such as a window having a title bar and a close
button, because each component gains these properties as a member of the general class of
GUI components. Figure 1-2 shows the relationship of some Dog objects to the Dog class.
By convention, programmers using Java begin their class names with an uppercase letter. Thus, the class
that defines the attributes and methods of an automobile would probably be named Automobile, and the
class for dogs would probably be named Dog. However, following this convention is not required to produce
a workable program.

Dog class definition Dog class instances (objects)

Every Dog that is


created will have
a:

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.

Understanding Inheritance and Polymorphism


An important feature of object-oriented program design is inheritance—the ability to create
classes that share the attributes and methods of existing classes, but with more specific
features. For example, Automobile is a class, and all Automobile objects share many traits and
abilities. Convertible is a class that inherits from the Automobile class; a Convertible is a
type of Automobile that has and can do everything a “plain” Automobile does—but with an
added ability to lower its top. (In turn, Automobile inherits from the Vehicle class.)
Convertible is not an object—it is a class. A specific Convertible is an object—for example,
my1967BlueMustangConvertible.

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.

Watch the video Object-Oriented Programming.

TWO TRUTHS & A LIE


Comparing Procedural and Object-Oriented
Programming Concepts

1. An instance of a class is a created object that possesses the attributes and


methods described in the class definition.
2. Encapsulation protects data by hiding it within an object.
3. Polymorphism is the ability to create classes that share the attributes and methods
of existing classes, but with more specific features.

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

Features of the Java Programming Language


Java was developed by Sun Microsystems as an object-oriented language for general-purpose
business applications and for interactive, World Wide Web-based Internet applications.
(Sun was later acquired by Oracle Corporation.) Some of the advantages that make Java
a popular language are its security features and the fact that it is architecturally neutral: 11
Unlike other languages, you can use Java to write a program that runs on any operating
system (such as Windows, Mac OS, or Linux) or device (such as PCs, phones, and tablet
computers).
Java can be run on a wide variety of computers and devices because it does not execute
instructions on a computer directly. Instead, Java runs on a hypothetical computer known as
the Java Virtual Machine (JVM). When programmers call the JVM hypothetical, they mean it
is not a physical entity created from hardware, but is composed only of software.
Figure 1-3 shows the Java environment. Programming statements written in a high-level
programming language are source code. When you write a Java program, you first
construct the source code using a text editor such as Notepad or a development
environment and source code editor such as jGRASP, which you can download from the
Web for free. A development environment is a set of tools that help you write programs by
providing such features as displaying a language’s keywords in color. The statements are
saved in a file; then, the Java compiler converts the source code into a binary program of
bytecode. A program called the Java interpreter then checks the bytecode and
communicates with the operating system, executing the bytecode instructions line by line
within the Java Virtual Machine. Because the Java program is isolated from the operating
system, it is also insulated from the particular hardware on which it is run. Because of this
insulation, the JVM provides security against intruders accessing your computer’s hardware
through the operating system. Therefore, Java is more secure than other languages.
Another advantage provided by the JVM means less work for programmers—when using
other programming languages, software vendors usually have to produce multiple versions
of the same product (a Windows version, Macintosh version, UNIX version, Linux version,
and so on) so all users can run the program. With Java, one program version runs on all
these platforms. “Write once, run anywhere” (WORA) is the slogan developed by Sun
Microsystems to describe the ability of one Java program version to work correctly on
multiple platforms.
Java also is simpler to use than many other object-oriented languages. Java is modeled after
C++. Although neither language is easy to read or understand on first exposure, Java does
eliminate some of the most difficult-to-understand features in C++, such as pointers and
multiple inheritance.

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

Java Source Code

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

JVM (named java.exe)


performs security checks
and translates bytecode to
machine language, which
Computer Operating
executes
System

Figure 1-3 The Java environment

Java Program Types


You can write two kinds of programs using Java:
Applets are programs that are embedded in a Web page. You can read about applets in a
special section at the end of this chapter.
Java applications are stand-alone programs. Java applications can be further subdivided
into console applications, which support character or text output to a computer screen,
and windowed applications, which create a GUI with elements such as menus, toolbars,
and dialog boxes. Console applications are the easier applications to create; you start using
them in the next section.

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

TWO TRUTHS & A LIE


Features of the Java Programming Language

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

Analyzing a Java Application that Produces


Console Output
At first glance, even the simplest Java application involves a fair amount of confusing syntax.
Consider the application in Figure 1-4. This program is written on seven lines, and its only
task is to display “First Java application” on the screen.

public class First


{
public static void main(String[] args)
{
System.out.println("First Java application");
}
}

Figure 1-4 The First class

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

Understanding the Statement that Produces the Output


Although the program in Figure 1-4 occupies several lines, it contains only one Java
programming statement. The statement System.out.println("First Java
application"); does the actual work in this program. Like all Java statements, this one
14 ends with a semicolon. Most Java programming statements can be spread across as
many lines as you choose, as long as you place line breaks in appropriate places. For
example, in the program in Figure 1-4, you could place a line break before or after the
opening parenthesis, or before or after the closing parenthesis. However, you usually
want to place a short statement on a single line.
The text “First Java application” is a literal string of characters—a series of characters that
will appear in output exactly as entered. Any literal string in Java is written between
double quotation marks. In Java, a literal string cannot be broken and placed on multiple
lines. Figure 1-5 labels this string and the other parts of the statement.

"First Java application"


out is a property of the is a literal string that is the argument
System is a class. System class. to the println() method.

System.out.println("First Java application");

Dots separate classes, println() is a method. Every Java statement ends


objects, and methods. Method names are always with a semicolon.
followed by parentheses.

Figure 1-5 Anatomy of a Java statement

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

Within the statement System.out.println("First Java application");, the method to


which you are passing "First Java application" is named println(). The Java methods
println() and print() both produce output. With println(), after the output is displayed,
the insertion point moves to the following line so that subsequent output appears on a
new line. With print(), however, the insertion point does not advance to a new line, so
subsequent output appears at the end of the current line. 15

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.

Understanding the First Class


Everything that you use within a Java program must be part of a class. When you write
public class First, you are defining a class named First. You can define a Java class using
any name or identifier you need, as long as it meets the following requirements:
A Java identifier must begin with a letter of the English alphabet, a non-English letter
(such as α or π), an underscore, or a dollar sign. A class name cannot begin with a digit.
A Java identifier can contain only letters, digits, underscores, or dollar signs.
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

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.

abstract continue for new switch

assert default goto package synchronized

boolean do if private this

break double implements protected throw

byte else import public throws

case enum instanceof return transient

catch extends int short try

char final interface static void

class finally long strictfp volatile

const float native super while

Table 1-1 Java reserved keywords

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

Class Name Description


Employee Begins with an uppercase letter
UnderGradStudent Begins with an uppercase letter, contains no spaces, and emphasizes each
new word with an initial uppercase letter
17
InventoryItem Begins with an uppercase letter, contains no spaces, and emphasizes the
second word with an initial uppercase letter
Budget2016 Begins with an uppercase letter and contains no spaces

Table 1-2 Some valid class names in Java

Class Name Description


Undergradstudent New words are not indicated with initial uppercase letters, making this
identifier difficult to read
Inventory_Item Underscore is not commonly used to indicate new words
BUDGET2016 Using all uppercase letters for class identifiers is not conventional
budget2016 Conventionally, class names do not begin with a lowercase letter

Table 1-3 Legal but unconventional and nonrecommended class names in Java

Class Name Description


Inventory Item Space character is illegal in an identifier
class class is a reserved word

2016Budget Class names cannot begin with a digit


phone# The number symbol ( # ) is illegal in an identifier

Table 1-4 Some illegal 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

The keyword class


public is an access identifies First as First is the name of
specifier. a class. the class.

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. }

Figure 1-6 The parts of a typical class

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

We not only have to establish an up-to-date, scientific way to live,


but we cannot do this without the help of the tenement house
woman. We contribute the ideals, the theories and the science; she
must contribute experience. We are up in the air with our castles, she
is down in the thick of the fight where the smallness of the tenement
room presses upon her, where every day she faces the high price of
food and an insufficient income, where a gentle love for her children
is constantly at war with a nervous irritability, the product of
disorder, noise and confusion.
Do you think this woman does not want a real home? Look at the
energy and thought she puts into furnishing her house, the scrimping
that preceded the buying of the ugly red carpet and the plush chairs.
There were hours of work given to hemming and hanging the ruffles
over every door, around every shelf and even around the bath tub.
Look at the tarletan festooned around the chandelier and over the
pictures; see the dozens of calendars collected and pinned on the
wall. Isn’t this a reaching out with all the power that is in a woman to
express to her family and her neighbors what, in her ignorance, she
believes to be a home? We need the energy and the courage and the
experience of these tenement housekeepers, but we must add
education; and do we?
Take the daily life of any one of our thousands of little school girls
and see how much chance she has to know the science of home-
making or even to acquire respect for housework. She is born with
the controlling desire to copy. She sees high-heeled shoes on
another’s foot; she longs for and saves until she gets shoes like them.
Her tight skirt, her big hat, her very walk, are seen first and admired
somewhere else, and so the home, whether it is perfect or imperfect,
and the school, and the teacher, and what the teacher stands for,
make the same vivid pictures in her mind; and some day she is going
to grow up and copy as nearly as she can.
This little girl wakes in the morning in one of our crowded
tenement houses, wakes to the vivid blue walls, to rooms filled with
feather beds which have been thrown all over the floor the night
before for the family and the possible boarders to occupy. The dusty
carpets, stuffed furniture, long lace curtains and draped mantle meet
her eye, and in this home of unrest there is always the crying baby,
the naturally cross father and the demand (so well known to every
little girl) to hurry up and go to the store and buy breakfast. Poor
little tenement girl, she does not even know that in well-managed
homes breakfast is bought the day before. She may learn to respect
the energy in her home, but she will never forget the disorder, the
picture of congestion and confusion and of overwrought, tired nerves
that has been stamped forever upon her mind. And no right idea of
home is given her to correct this wrong impression.
Everyone knows the way work is done in our tenement homes;
how the beds are so large that it is impossible to move them out in
the small rooms and make them properly, and how the bed clothes
are pushed across, often with a broom handle kept for the purpose;
how often the small income makes it necessary to rent out the beds
in the day time to night workers, so they are always occupied and
never aired. And every one knows how all these things make a girl
lose respect for her home, then for her family and, finally, for herself;
and how the street seems a peaceful place in comparison.
Ideals of right home-making should in the school correct the home
mistakes, but as it is now, not until she reaches the seventh grade
does this little tenement girl get her first idea that making a home is
a part of education. After she leaves home in the morning she gets
only a picture of a schoolroom with forty or fifty desks; of a teacher
who in no way is associated in her mind with any house, who, as I
heard Mrs. Kelley say not long ago, often brings her lunch in a music
roll so that no one will suspect that it is food.
The windows in the schoolroom are washed after school hours
(and at that only once or twice a year) by the janitor, the floors are
swept by men, swept badly, and always after school. And if this pupil
happens to be one of the twenty thousand who leave school each year
before reaching the seventh grade, she goes into business not
knowing that there is such a thing as scientific knowledge regarding
food and air and sun and cleanliness.
And yet this girl is going to marry, bear children and rear them,
and you and I are going to hold her responsible if those children are
not good citizens. Surely this is not a fair placing of responsibility.
Eleven years ago I started the first housekeeping center in New
York. These centers are ordinary tenement flats which find their
motive power and are successful by means of the universal love in
every little girl to play at keeping house, and the universal desire in
every one to copy that which is just above her.
A girl wants her kitchen messes, her dishes, her make-believe baby
and her tiny bed or broom just as every boy wants his bat and ball. A
housekeeping center takes these natural desires and cultivates them.
It is furnished as a home should be furnished, and such questions are
answered there as: What shall be done with the floors to insure
health and save labor; what with the walls? What curtains are the
best to admit light, give beauty to the room and wash easily? What
proportion of the sum laid aside for furnishing should go into the
buying of pots and pans, what part into mattresses, and is there any
reason to spend money for ruffles? What are the proper and
necessary tools to work with?
In the housekeeping center the neighbors and the scientifically
trained teacher work out these problems together. The teacher’s
training in chemistry has taught her that a certain quality of water
and a certain kind of soap are necessary for perfect laundry work.
The tenement house woman adds what she has learned from bitter
experience; that it is hard to heat enough of any kind of water on the
stove with coal at ten cents a pail and the stove crowded with pots
and pans.
A LESSON IN BED-MAKING

Regular lessons are given in these housekeeping centers morning,


afternoon and evening, and as the flat is like the home from which
the pupils come (only perfected) its lesson is not dissociated with the
daily home duties but is performed under home conditions and,
therefore, easy of imitation. Do the pupils want this instruction? The
answer is that every class is full and there is a waiting list, and every
girl pays for the lessons.
I find it often difficult in selling luncheons in the public schools to
persuade the children to give up three cents for a full meal, and yet
the children under fourteen in the housekeeping centers are ready
always to pay three cents a lesson, and the working girls five cents.
And what do they pay for? To learn to clean the sink so that the pipes
will not get clogged, to learn to cook substitutes for meat (for meat is
too high for many of them), to scrub closets and floors, to make and
clean beds. Only last week a class of working girls came to one of the
centers and asked for a bedbug lesson. “The people above us are
moving out” they said, “and we want to prevent the bugs getting into
our house.” A bedbug lesson is not a lecture, it means to roll up one’s
sleeves, put on a big apron, get on your knees and scrub, this after
working hard all day in a factory or shop. The desire for this
knowledge must be very real to make a girl willing to do this extra
labor, and to pay for the privilege of doing it out of her scanty wages.
In a housekeeping center it is easy and natural to borrow a baby
from the neighbor across the hall when the lesson is “how to bathe
and dress a baby.” There is nothing embarrassing about being the
patient when the lesson is “how to give a bath in bed and how to
change the sheets without disturbing the patient.” Then there are the
dinner classes where the pupils make out the menu, do the
marketing and cook the meat, and there are lessons in food values.
What I feel that we need today is a housekeeping center in every
settlement, so that every girl who is a part of the settlement will feel
it almost compulsory upon her to take the course before she marries,
and if she is enjoying the intellectual life of the settlement, or the
play side, or the social side, she must be learning the home-making
side too. We must make our settlement girl feel that the home-
making training is more important than mere recreation. The public
school will follow the settlement and then, not for one-ninth of our
girls will home-making instruction be given, but for every one.
A KITCHEN-CLEANING LESSON

Then there will be in every school the cooking-room, with its


individual equipment (necessary, but nothing in it to suggest the
kitchen at home). Next to this will be the model flat or center, this to
resemble the homes from which the children come, but furnished on
scientific lines. For eight years every school girl will see this home,
this home made right, and she will work in it. It will be no smattering
of cooking at the end of the school course,—but in the beginning,
when the love of playing house is strong, then the training will begin.
Even in the lowest school grade a child could dust her desk with a
damp duster and be told why it should be damp; she could wash her
own cup, if milk is served; learn to handle dishes carefully; and train
the eye to see things straight and the hand to steadiness.
From these small tasks, the children would graduate to larger
duties in the housekeeping center; making beds and washing many
dishes. From dusting one desk, the pupil would soon be able to give
the flat a thorough cleaning. We find in our center that the love of
playing house disappears if it is not cultivated, and the girl of
fourteen never drops entirely the wrong way of doing housework,
which she need never have acquired if the domestic science teacher
could be in her training early enough.
Scientific management means more than “having system.” You
may be ever so systematic in the way you do things, but if you
happen to be doing them the wrong way, you are doing the way that
is unnecessarily expensive in time, energy, money, comfort and
beauty.
I believe that the labor in the kitchen will become more and more
professionalized. It is too serious a work to be handled by unskilled
hands, and we must lose the nervous, irritable, overtired slave of
housework and make woman more of a child-trainer and cheerful
home-maker. She must guide her home with the quiet and skill and
delight with which the engineer drives his engine or the chauffeur his
car. This, some day, will be brought about by centralizing the work
and by an army of trained workers who will expeditiously and
noiselessly do a large part of what each woman is now trying to do
herself. But that day can come only when women through universal
home-making education push forward and demand this better
management of the home.
We must have restlessness and dissatisfaction first. This comes
from a realization of the right way and a disgust with the wrong way,
and then will come the push from the home-maker herself, not from
a few outside reformers. The tenement house occupant now is too
ready to accept the fallen plaster, the dish-water that leaks through
from the flat above and the dirty and dark halls. Her own senses are
dull and she does not see or think about these things, and the
tenement house reformer sometimes feels his work has been
accomplished by a few bath tubs and a little more light, and then
wonders at the indifference with which these gifts are received and
blames the abuse of them. Train a girl to know a home of order from
one of unrest. Teach a woman to be miserable at the thought of a
close room or an unaired bed for her baby, and the social worker can
go off and do something else. The power of action is where it ought to
be, in the awakened tenement house mother. She will not be content
to crowd her family into dark rooms; she will work until she gets
space enough and light enough for her children. She will be driven to
action because she knows the value of what she has to fight for.
When the suffrage comes to women, how naturally then these
intelligent, orderly home-makers will take their part in municipal
housecleaning!
Let us not be satisfied to force through bills at Albany that improve
our tenements; at the same time the tenement girl must be receiving
her scientific home training, so that she too, can take her part in this
great home-making profession.
A YIDDISH POET

MARY BROWN SUMNER

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

From an etching by Herman Struck


His poems are cries of pain out of his own life interpreted in terms
of the life of his class. He is always lyric, he is always personal, but he
is never egotistical. The story runs that at his machine in the midday
hour he would write a lyric of the workshop instead of eating his
meager lunch. The song to the working-girl prostitute is one of these
workshop poems which like a flash reveal working and living
conditions such as in less revealing form have been put before us by
investigators.
The twelve-hour day may be said to be the subject of My Boy. The
tailor’s baby was always asleep when his father got home from work:
MY BOY

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.

I stand by the cradle.


I stand in pain and anguish and bitterness, and I think: “When you awake some
day, my child, you will find me no more.”

Seven-day labor is the burden of the song Despair:


DESPAIR

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!

The Pale Operator gives a hint of the ravages of tuberculosis in the


garment trade:
THE PALE OPERATOR

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.

A desire for life—if it is a feast, he would sit at it; if it is a dream he


would have it a beautiful one—a love of the outdoor country life
which he knew as a boy and which he believed all should enjoy,
mingled with a sense of impotence and despair, varying with
outbursts of wailing and outbursts of hate, these things characterize
the poetry of Morris Rosenfeld. For all his power to vizualize and
voice the world about him, he is never constructive, never militant,
and seldom even virile.[6] In few poems does he express any hope for
the future. In a mood of despair he writes the beautiful workshop
poem:
A TEAR ON THE IRON

I groan and cough and press, and think


My eye grows damp, a tear falls; the iron is hot,
My little tear it seethes and seethes and will not dry up.

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.

In a mood of mingled longing and hate, he writes the Flowers of


Autumn, whose splendor is only for the well-to-do—

Therefore I do not care if I see you dying now.

There is more virility, though nothing really purposeful in the


Garden of the Dead, where the dead worker rises up to claim the
flowers on the rich man’s grave:

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 Nightingale illustrates, as Professor Wiener points out, the


poet’s command over poetic form as well as poetic thought. Even in
the English prose translation we can feel the repetition of notes, the
intricate weaving of melody in the bird’s song.
Another poem which is an example of the same power of
combining matter and manner is that drama of the garment worker’s
lift, The Sweatshop, which deserves to be quoted in full:
THE SWEAT SHOP

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!

The prose translation reproduces the thought alone; the Yiddish


original reproduces also the loud insistent stitching of the machines,
and the persistent nagging of the hateful clock. The machine beats
out these lines:

Ich arbeit, un’ arbeit, un’ arbeit ohn’ Cheschben.


Es schafft sich, un schafft sich, un schafft sich ohn’ Zahl.[8]

To what he feels to be the hopeless tragedy of the worker is added


in Rosenfeld’s verse the hopeless tragedy of the Jew—the wanderer
who has lost the power to laugh. In Sephira[9] as well as in other
poems, he brings out the fact that the Jew has set his Passover and
the period of mourning following it, in the happiest time of the year.
This poem, which has been really adequately translated into verse by
Alice Stone Blackwell, is one of his saddest and most beautiful:
SEPHIRA
Methinks I fain would call upon my lyre
To laugh a little, but in vain the call!
For to begin with, ’tis Sephira now.
Tell me, besides, can a Jew laugh at all.

Oh, God, you laugh? A wail is in the laugh!


Brothers, what is there of reality
In a Jew’s pleasures? Is his laughter real?
’Tis but the mingling of a sob and sigh.

No savor now has Jewish life, no grace


Has Jewish Joy! Above, in heaven’s deep
The silvery clouds are floating; and the woods
Are full of life, but we sit down and weep.

Spicy the forest is, the garden green;


How fresh and cool spring’s breezes blowing by!
But what concern is that of yours, O Jew?
’Tis now Sephira; you are mute and sigh.

The lovely summer, comfort of men’s lives,


Passes in sobbing and in sighs away.
What hopes into the Hebrew can it give?
To him what comfort summer or the May?

A mendicant who has no place to rest


With whom all men make sport—each day, each week, each hour,
Oh, is it meet for him to think of joys,
Of gardens with their balm, of tree or flower?

And if the Jew at times break forth in song,


Does his song seem to breathe of mirth to you?
I, in his music hear but “Roam and Roam!”
In every note I recognize the Jew.

If one who is well versed in music’s art


Should chance to listen to a Jewish song,
His eyes against his will would gush with tears,
Each note would shake him with emotion strong.
The ram’s-horn call to penitence and grief,
Oh, that is now the Hebrew’s favorite strain—
A strain that makes but feelings for the tomb,
A strain to break a heart of steel with pain.

The song of the Atonement, and the Dirge


For the great temple and the Suppliant’s Psalm;
These are his sweetest music, since his joy
Was shattered in his holy land of balm.

Since his foe broke the sweetest instruments


Of music in his Temple, ever dear,
Only the plaintive ram’s-horn to the Jew
Is left, on which he sobs but once a year.

Of drums and cymbals, organs, harps and lyres,


Flutes and guitars, all with their dulcet strains,
The gloomy ram’s-horn, withered, sad and dry,
Is all that now to the poor Jew remains.

Whate’er he sing, however he may laugh


However gay he seeks to make the strain,
There suddenly awakens in his song
The suppliant’s psalm that rends the heart with pain.

Me thinks I fain would call upon my lyre


To laugh a little, but in vain the call!
For to begin with, ’tis Sephira now,
Tell me, besides, can a Jew laugh at all?
For the Rosenfeld of the Songs from the Ghetto, the present is
terrible and the future hopeless; there is always an aching desire for
beauty and happiness, but to him beauty and happiness themselves
wait upon toil and suffering and death—the nightingale groans “upon
the great cemetery of the world.”
But Songs from the Ghetto was written some fifteen years ago.
Some of his later poetry is lighter—some hope and the joy of living
appear to have crept into it. Of these, a hitherto unpublished poem in
English called “If,” has but a gentle melancholy:
IF
If hope would fly and sorrow stay,
If stars were dark and days were gray,
If love would vanish like a breath,
What would be life? What would be death?

If songs would die out in the nests,


And pleasure to the human breasts,
If flowers were to lose their hue,—
Oh! What would be I, What would be you?

Stealings is full of personal joy:


STEALINGS
I steal a smile from thy fair face
And hide it deep within my heart;

I steal a shadow of thy grace


And hide it deep within my soul;

I steal a ray from thy bright eyes


And hide it deep within my mind;

I steal the echo of thy sighs


And weave them softly in my dreams;
A word from thy sweet lips I steal
And hide it deep within my thoughts;

I steal the rapture of thy thrill


And drown it deep within my blood;

And from these thefts, these sacred stealings


Are born the bright flames of my love,

And the fountain of all sweet feelings,


And the stream of my life’s joy.

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.

Seek me not where birds are singing,


Not there my spirit you can trace;
A slave am I—where chains are ringing,
’Tis there you’ll find my resting place.

Seek me not ’mid fountains dashing,


Not there my spirit you can trace,
Where tears are falling, teeth are gnashing,
’Tis there you’ll find my resting place.

And lov’st thou me with love’s true passion,


Thy steps unto my spirit trace,
Bring joy with thee; in love’s true fashion,
Make sweet to me my resting place.
NEW BOTTLES FOR NEW WINE

THE WORK OF ABASTENIA ST. LEGER EBERLE

CHRISTINA MERRIMAN

The recent International Exhibition of Art in New York was, from


one angle, at least, a protest against certain set standards of art
generally accepted today as inevitably right because they have
“always been.” Some of the by-products of that stimulating
movement toward freedom have been variously characterized as
“courageous” “self-expressive” and “insolent.” Certainly much of it
was a serious effort toward individual expression—a revolt against
academic rules—partaking in some instances of a defiance which was
a law unto itself, a frank disregard of what impression the mystified
public carried away.
Such, however, was not the attitude or feeling of at least one
exhibitor whose work aroused much interest and comment, and who
was one of the first artists of standing to reflect in her work the spirit
of awakened social consciousness so apparent today. Abastenia St.
Leger Eberle showed two groups, the more striking of which was The
White Slave, reproduced on the cover of this issue of The Survey.
They are the work of a sculptor who has strongly defined views as to
the part the artist should play in the common life.
“The artist should be the ‘socialist,’” says Miss Eberle. “He has no
right to work as an individualist without responsibility to others. He
is the specialized eye of society, just as the artisan is the hand, and
the thinker the brain. More than almost any other one sort of work is
art dependent on society for inspiration, material, life itself; and in

You might also like