100% found this document useful (6 votes)
28 views

Java Programming 8th Edition Joyce Farrell download

The document provides information about the 8th edition of 'Java Programming' by Joyce Farrell, including links for instant ebook downloads in various formats. It also lists other programming-related titles available for download. Additionally, it contains copyright information and a brief overview of the book's contents and structure.

Uploaded by

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

Java Programming 8th Edition Joyce Farrell download

The document provides information about the 8th edition of 'Java Programming' by Joyce Farrell, including links for instant ebook downloads in various formats. It also lists other programming-related titles available for download. Additionally, it contains copyright information and a brief overview of the book's contents and structure.

Uploaded by

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

Java Programming 8th Edition Joyce Farrell

download

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

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


Get Your Digital Files Instantly: PDF, ePub, MOBI and More
Quick Digital Downloads: PDF, ePub, MOBI and Other Formats

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.
Another Random Scribd Document
with Unrelated Content
interior of the west door. The style of the work is clearly late. The initials A.
M. may stand for the name of Mallet, as there seem to be three mallets on
the shield.

Fig. 636.—Culross Abbey. Interior of Doorway of Tower.

The tower (Fig. 637) measures 84 feet high to the top of the parapet; it
has been operated on at various times. The projecting round staircase-turret
is an addition of, perhaps, the fifteenth century; the lower part of the tower,
as is evident from the west doorway, is probably of the thirteenth century. It
is groin vaulted at the first story, as shown on Plan. This vault, and all above,
are of sixteenth century work, with the exception of the upper part above the
cornice, which dates from this century. The old finishing of the tower is
shown by Slezer to have been carried out with a cape house and bartisan like
the pele towers, or as shown at the churches of Torphichen, Dysart, and
Dundee.
Fig. 637.—Culross Abbey. Tower from North-East.

Fig. 638.—Culross Abbey. View from South-East.


Fig. 639.—Culross Abbey. North Transept.

The doorway from the tower to the east church and the passage leading to
the chapel, which stood on the east side of the transept, are late Gothic. The
east church, as already stated, is a complete cruciform structure, having
choir, transepts, and nave in itself. The north transept (see Fig. 637) was
built, in 1640, by George Bruce of Carnock, it is surmised, on older
foundations. The south transept is, generally speaking, old; it had an east
aisle, opening by two arches from the transept and one arch from the choir.
This aisle is now removed, and the arches are built up, but their outlines are
visible from the exterior (Fig. 638). This aisle is shown by Slezer with a
lean-to roof against the transept. In the corresponding position on the north
side there appears to have been a similar aisle; part of its east wall still exists
(Fig. 639), with an early two-light window, and the remains of what appears
to have been a canopied tomb, although Mr. Beveridge[84] regards it as being
the doorway to the north aisle. Built against the wall, in an upright position,
is the recumbent figure probably belonging to this tomb.
All the original windows of the east church, which were large and
important, have been built up during this century, and smaller windows of a
debased type inserted, with the exception of the east window (see Fig. 638),
which is original, and is of good design; but even this is lost to the interior,
being partitioned off in order to allow a gallery stair to pass it.
A part of the west wall of a chapel, which formerly existed to the north of
the tower, is indicated by the jamb and springing of a window. A sketch
section of its mouldings is given in Fig. 640, as also a section of the
mouldings of the door to the turret, which entered from this chapel. These
mouldings are evidently not earlier than late fourteenth century work. There
are two seventeenth century burial vaults adjoining the north transept. In the
larger of these is the fine monument to Sir Robert Bruce of Carnock,
illustrated in The Castellated and Domestic Architecture of Scotland, Vol. V.
p. 207.
Adjoining the south transept on the
south is the sacristy, now converted into a
vestry, and hardly to be recognised as old,
owing to alterations. The shape and
position of this apartment clearly indicate
its original use; it had the usual east
window, now built up, and has otherwise
been altered.
To the south of the sacristy was the
chapter house, which also occupied its
normal position. Just enough remains to
enable it to be identified, viz., the
northmost of the usual three west
openings to the cloister (Fig. 641), with Fig. 640.—Culross Abbey.
the jamb and springing of the central Sections of Mouldings of
opening, or as much of it as can be seen Chapel Window and Turret Door.
for the modern walls that are built up
against it. This fragment, even in its mutilated state, is a fine example of first
pointed work. The inner order of the arch mouldings has fallen away, and
otherwise the work has been greatly destroyed, its beauty not having been
appreciated. The shafts and arch mouldings (Fig. 642) are all of very bold
and pure design. The caps and bases are rounded, and the hood mould,
which was also a string course, is ornamented with the dog-tooth. The
chapter house had two rows of columns, as is evident from the remains of
the springing of the first arch from between the two existing openings as
shown in Fig. 641 and the Plan (Fig. 642). It was usual for the two side
openings to be unglazed windows rather than doors, but
Fig. 641.—Culross Abbey. Opening to Chapter House.

Mr. Sharp, in his paper on “The Architecture of the Cistercians,”[85]


points out that it was common for the three openings to be doorways, with
the peculiarity seen here that they were not intended to have doors.

Fig. 642.—Culross Abbey. Door to Chapter House.


Fig. 643.—Culross Abbey. Entrance to West Side of Cloister.

Of the western alley of the cloister there are considerable remains. The
manse, adjoining the nave, appears to include a part of the original buildings.
It is dated on the Plan “1647,” that figure being carved on a dormer; but
portions of the walls are undoubtedly older, and possibly a thorough
examination might reveal ancient features. To the south of the manse is the
vaulted entrance to the cloister (Fig. 643), and further southward the
truncated remains of the building shown in Fig. 644. The latter enters from
the exterior by a narrow door, having a stair in the thickness of the wall
adjoining leading to the upper floor. As already mentioned, there are
extensive cellars beneath. This range of buildings was what Mr. Sharp calls
the Domus Conversorum,[86] or the place for the workmen and servants of
the monastery, which contained their day room on the ground floor and
dormitory above.
Fig. 644.—Culross Abbey. Chamber on West Side of Cloister.

About a quarter of a mile north from the abbey there exist the remains of
a lodge, with indications of an arched “pend.” The lodge is still in use, but
quite modernised. This archway was probably an entrance to the grounds of
the abbey.
The most remarkable feature of the edifice is the tower which divides the
east church from the west. From its architecture we may at once conclude
that the upper portion is a structure of late date, probably of the sixteenth
century. The interior doorway (see Fig. 636) is clearly of about that period,
but some of the features of the lower story seem, as above mentioned, to
point to that part being of an earlier time, probably thirteenth century.
The puzzle here is to understand how this solid tower should have been
set down in the centre of the church, thus completely cutting off the western
portion from the eastern, and forming two separate churches. Two possible
solutions of this difficulty present themselves.
1. The two churches may have been intentionally kept separate, the
western portion being the parish church and the eastern that of the monks.
Such an arrangement is unusual in Scotland, but Mr. Freeman has described
several churches in England where one portion belonged to the parishioners
and the remainder to the monks. The chief difficulty connected with this
theory is that the parish of Culross (as above mentioned) was provided with
a separate parish church at a little distance away.[87]
2. The second supposition is that, in course of time, the monastery may
have dwindled, and the buildings may have fallen into disrepair. The
question would then arise whether it would not be better to diminish the size
of the church by abandoning the western portion and erecting the tower
where it stands. This might have occurred towards the close of the fifteenth
century. But there are difficulties connected with this solution of the problem
also. The tower shows the springing and jambs of windows on its west side,
which appear to be of about the same date as itself, thus indicating the
intention of continuing the structure westwards and restoring the old west
church.

THE OLD PARISH CHURCH OF CULROSS, Perthshire.


A ruinous structure, situated about one mile north-west from the abbey. It
is a plain oblong (Fig. 645), 71 feet long by 16 feet wide (inside), with walls
about 3 feet thick, but parts of them have been recently rebuilt on the old
foundations. It is thus impossible to say what the original arrangement of
doors and windows may have been, only one small pointed window, which
seems to be original, remaining next the south doorway. A north and south
doorway face one another towards the west end, but these have evidently
been inserted at a late date. Both doorways have straight lintels (Fig. 646),
and these consist of ancient tombstones, carved with foliaged crosses and
swords (Fig. 647).
Fig. 645.—The Old Parish Church of Culross. Plan.

Fig. 646.—The Old Parish Church of Culross. Interior, looking East.

Numerous other recumbent tombstones are found in the church, and some
have been placed against the east wall when it was rebuilt. A top stone
containing the socket for a cross is preserved at the east end. The south
doorway has probably had a porch.
This church had apparently fallen into decay before the Reformation, for
in 1633 an Act was passed making the abbey the parish church, and stating
that the abbey church had been used for preaching since the Reformation,
and that the church called the “Parioche Kirk, where service is not nor has
been since the memory of man, is altogether ruinous, decayed, and fallen
down in certain parts.”
It is still surrounded with the old burying-ground, which contains some
interesting monuments. A large tombhouse has been built, like a transept, on
the south side of the church. It appears to be an erection of the seventeenth
century.

Fig. 647.
The Old Parish Church of Culross.
Tombstones used as Door Lintels.

BEAULY PRIORY, Inverness-shire.


This monastery was pleasantly situated on the north side of the river
Beauly, not far from the point where it falls into the sea at the head of the
Beauly Frith, which forms the inner portion of the Moray Frith. The land is
level and fertile, and the scenery on the river is very beautiful. The priory is
about ten miles west from Inverness, and about one mile from Beauly
Railway Station. It is believed to have been founded in 1230, and was
thereafter endowed by Sir John Bisset of Lovat.[88] The priory was dedicated
to St. John the Baptist, and was occupied by seven French monks of the
Order of Valliscaulium. This was one of the strict orders established at the
time of the revival of religion in the twelfth century. The mother house of the
order was at Langres, in Burgundy. Of this order there were only three
priories in Scotland: one at Pluscarden, in Morayshire; one at Ardchattan, in
Argyle; and one at Beauly. The monks were austere in their lives, and
formed a centre of devotion and enlightenment in the midst of these wild and
uncivilised districts. The charter of the foundation was confirmed by Pope
Gregory XI. in 1231. The priory was probably erected during the thirteenth
century, but its records are few for a long period.
The Frasers succeeded the Bysets in the lands surrounding the priory, and
Hugh Fraser, who was first Lord of Lovat, died in 1398. His son, Alexander,
was a great benefactor of the priory, and is said to have erected a beautiful
steeple of carved oak on the west gable, and put curious bells therein.
Hugh Fraser (about 1430-40) afforded means for building the north work
of the priory and the chapel of the Holy Cross.
The church was soon after repaired at the expense of the superior, a
natural son of Alexander of Kintail, who was there buried, A.D. 1479. His
tomb is opposite that of his brother, Sir Kenneth Mackenzie of Kintail, with
the date 1491. Sir Kenneth was the first of his family who was buried at
Beauly, having married a daughter of Lord Lovat and obtained the Beauly
property.
In 1530 Abbot Robert Reid of Kinloss received a gift of the Abbey of
Beauly in commendam.[89] It is recorded by Ferrerius that many new
buildings were erected and old ones repaired by this abbot. He is stated to
have collected materials in 1537 and to have rebuilt the nave in 1540, and
the structure bears evidence of his operations. He also restored the bell
tower, which had been destroyed by lightning; but in 1541 that work was
demolished, and the bells destroyed by a violent storm, which also did much
damage throughout the country.
In 1544 Bishop Reid (being now promoted to the See of Orkney)
removed the ruinous house of the prior, and erected a new and spacious
house, with six vaults on the basement; but of this structure there is now no
trace.
Robert Reid was succeeded, as commendator, by his nephew, Walter
Reid, who was also his successor in the abbacy of Kinloss. The possessions
of the Priory of Beauly were alienated, in 1571, by Walter, the new
commendator, as were also those of Kinloss. The lands thus became the
property of the Lovat family. On the forfeiture of Lord Lovat, in 1516, the
abbey reverted to the Crown.
The priory consisted of the church, with a cloister to the south, which
was, in all probability, surrounded by the usual monastic buildings; but the
latter, including the spacious prior’s house erected by Bishop Reid, have
almost entirely disappeared. The walls of the church (Fig. 648) survive, but
even these have been sadly abused. The buttresses have all been torn down,
apparently for the sake of the freestone dressings, and the tracery of the
windows has been greatly demolished.
The church consists of a single long aisleless chamber, a little over 150
feet in length by 24 feet 6 inches in width (within the walls). The eastern part
formed the presbytery and choir, and the western part the nave, but there is
no architectural feature to mark the divisions. About the place where a
transept might have been there are two projections, which break the long line
of the exterior. These projecting chambers or chapels are shut off from the
main church by solid walls containing doorways and monuments. They thus
formed separate chapels, or one of them may have been a sacristy. The
architecture of the choir and presbytery (Fig. 649) is remarkably fine, and is
of first pointed character. Although in this remote region its date may
probably be later than usual, it can scarcely be, as Mr. Muir suggests, so late
as the beginning of the fourteenth century.
The details are very simple, the jambs and arches having plain splays.
The caps of the shafts adjoining the windows in the interior are moulded and
have round abaci, but the shafts, which were detached in the early manner,
have disappeared. The arrangement of the arches is different on the two
opposite sides. The east window was very wide, and, doubtless, was filled
with tracery, which had several mullions. This may have been a later
addition; the tracery has entirely disappeared. The lower portions of the
buttresses of the choir have been rebuilt within recent years, probably in
consequence of an agreement entered into between Lord Lovat and the
Crown, whereby the former undertakes to keep the buildings in good repair.
Fig. 648.—Beauly Priory. Plan.

The most striking feature of the nave is the row of triangular pointed
windows running along the south side (Fig. 650). These have evidently been
curtailed in height in the design, so as to admit of the roof of the cloister
walk resting against the south wall of the church, the corbels for its support
being yet visible. The west end of this wall has evidently had domestic
buildings of a high and substantial character erected against it, some
fragments of which still remain, showing a fireplace, portions of a staircase,
&c. (see Fig. 650).
Fig. 649.—Beauly Priory. Choir, looking East.

The western façade bears the marks of Bishop Reid’s workmanship, and
is no doubt part of what is meant to be attributed to him when it is said that
he rebuilt the nave. The triangular south windows above mentioned, and the
two light pointed windows on the south side of the nave, are undoubtedly
much earlier than his date, which was about 1540-50, but other parts of the
walls of the nave may have been re-erected by him when he restored the
west end. The latter (see Fig. 650) is beyond doubt his work. The doorway in
the centre, the arch of which is semicircular, contains the monogram I.H.S.
on one of the label terminations, while the other drip stone shows two hands
and two feet, with a heart in the centre (Fig. 651), emblems of the Passion.
The arch of the doorway is round; but this, as we have seen elsewhere, is a
common feature in Scottish work of all dates, and occurs especially often in
late work.
The upper part of the west wall contains three pointed lancet windows,
and is an example of the revival of early features in late work. Some of the
windows in the side walls are of similar form, and are probably of the same
date. The sill of the central window in the west end is kept high, so as to
admit of a shallow ogee-headed niche for a figure over the entrance door.
The figure may have represented the Baptist, but the niche is now empty. On
a panel on the sill are Bishop Reid’s initials, R. R., and his arms, a stag’s
head (see Fig. 651).

Fig. 650.—Beauly Priory. Nave from South-West.

The part of the church which projects to the north measures 25 feet by 22
feet 6 inches internally. It has been vaulted in two bays, the vaults springing
from corbels in the walls; part of the vault still remains. This chamber is said
to have been the sacristy. It has a turret at the north-west angle, containing a
stair to the roof. In a recess in the wall which divides this chapel from the
choir lies the tomb (abovementioned) of Sir Kenneth Mackenzie of Kintail.
We have seen that the “north work” was erected at the expense of Hugh
Fraser (1430-40), and the style of this chapel corresponds with that date.
The repairs carried out by
Prior Alexander were probably
the work required for the erection
of the tomb of Sir Kenneth and
his own tomb, which was in a
recess in the choir on the opposite
side of the wall from that of Sir
Kenneth.
Fig. 651.—Beauly Priory.
Drip Stone and Panel.
Fig. 652.—Beauly Priory. Tomb of Sir Kenneth Mackenzie.
The tomb of Sir Kenneth (Fig. 652) is a good specimen of the work of the
period, and is very similar to other tombs of the same kind at Fortrose and
Fearn. The recumbent figure, clad in full armour, rests on an arcaded tomb or
pedestal, and the recess, which is covered with a pointed canopy, is enriched
with a crocketed label and pinnacle bearing a shield, and the whole tomb is
flanked by two thin buttresses. On the sill is engraved the following
inscription:—“Hic Jacet Kanyens M. Kynych d’us de Kyntayl. q. obiit dii
Februarii A. Di M.CCCC.LXXXXI.”
The chamber to the south of the choir has also contained monuments, but
they are now destroyed. It measures 22 feet by 17 feet internally, and seems
to have been connected by a door with the conventual buildings to the south.
It has contained two stories, the upper story forming a gallery, connected
with the church by a wide arch (see Fig. 649).
The choir contains a double piscina, near the east end, in a good first
pointed style.
Under the triangular windows in the south wall of the nave are a piscina
and ambry. These mark the position of an altar, which may have been
erected at the rood screen, which probably separated the nave from the choir
at this point, thus dividing the portion of the church open to the parishioners
from that reserved for the clerics. Opposite this piscina there is a door (now
built up) in the north wall, and near it, on the outside, there is another
piscina. This may possibly mark the position of another chapel, which may
have been that of the Holy Cross above, said to have been erected by Hugh
Fraser in the fifteenth century.

NEWBATTLE OR NEWBOTLE ABBEY,[90] Mid-Lothian.


Newbotle Abbey or, as it is now called (without the name having any
special meaning), Newbattle Abbey is situated on the river Esk, about two
miles south from Dalkeith. It was founded by David I. in the year 1140, for
monks of the Cistercian order, who were brought to Newbotle (or new
residence) from Melrose. The “leader of the colony” appears to have been
Ralph, the first abbot, who obtained numerous gifts and privileges for the
convent, and consecrated a “cemetery within the precinct of the monastery.”
The second abbot, Alfred, who died in 1179, was also a great benefactor to
the abbey. He brought to it many relics, which he enclosed in a silver chest.
“He adorned the chapter house with handsome seats, and also erected proper
stalls, with convenient desks or menologies of wood, in the cloisters on the
side where the ‘collation’ or reading of the lives of the saints was held, for
the use of the brethren during the reading of collation before compline at the
washing of feet at Maunday.”[91]
During the time of the tenth abbot, Constantine, the church was dedicated
by Andrew de Moravia, Bishop of Moray, in March 1233.
In the year 1241, Mary de Couci, queen of Alexander II., “looking to her
time of peril, and impressed with the frail tenure of life, bequeathed her body
to be buried in the church of Newbotle.”[92] This would seem to indicate that
the fabric of the church, if not finished by this time, was far advanced. Mary
de Couci survived for about thirty years, when her desire to be buried here
was carried out; and Father Hay describes her tomb, apparently from the
record of an eye-witness. “In the midst of the church was seen the tomb of
the queen of King Alexander, of marble, supported on six lions of marble. A
human figure was placed reclining on the tomb, surrounded with an iron
grating.”[93]
In 1275 Waldeve, the seventeenth abbot, “going the way of all flesh, with
blessed end, departed to the Lord, leaving his house in full peace and
excellent condition.”
Gervase, the nineteenth abbot, who demitted office in 1323, settled for
ever on the infirmary of the abbey an annual rent of three merks, “to be
expended for the uses of the sick and the recreation of the feeble.”[94] These
few notices seem to show that about the middle of the fourteenth century the
abbey was in a fairly complete state. It possessed great estates in the counties
of the Lothians, Lanark, Peebles, and Stirling. Father Hay writes that, about
this time, he “finds, from the books of receipts and expenses, the annual
income of the monastery could maintain eighty monks and seventy lay
brethren, with the corresponding establishment.”[95]
But evil days were at hand. In 1385, during the expedition of Richard II.,
“the English,” writes Father Hay, “burnt the monastery of Newbotle; and, at
the same time, several of the granges and farms of the monastery were
destroyed, and the others were deserted, while the lands were left untilled.
The towers or peles, built by the monastery for protection against English
marauders, fared in the same way. Some of the monks were carried away
prisoners; others fled to other monasteries. The few who remained in the
abbey, having scarce sufficient food, were compelled, by great distress, to
sell twenty-nine excellent chalices, nine crosses of exquisite workmanship,
and other sacred ornaments, with their silver household plate. At that time
the greater part of the abbey tower was ruined by the falling of the cross.”
These events happened during the time of Hugh, the twenty-third abbot.
The work of restoration was, doubtless, gone on with as soon as
convenient; and, in 1390, Sir James Douglas of Dalkeith, by his will, gave
his body to be buried in the monastery of St. Mary of Newbotle. “At the
same time he bequeathed to the abbey a ‘nowche,’ or jewel of St. John,
worth 40 merks, or its value, and, in addition, £23, 6s. 8d. for the building of
the church and wages of the masons employed upon it. For the service of the
monks’ refectory he gave twelve silver dishes, weighing eighteen pounds,
six shillings sterling, enjoining his heirs to see that they should not be
abstracted from the use of the refectory or sold.”[96] Two years later Sir
James, in another will, bequeaths similar sums to the abbey, without
appropriating a part to the building or to the payment of workmen, which
seems to show, as Mr. Innes remarks, that the rebuilding of the abbey church
had been completed in the meantime.
In 1419 Edward of Crechton paid a sum for the restoring and building of
the monastery.
In the Hertford expedition of 1544, “upon the 15th day of May the
horsmen raid to Newbottill and brynt it.”[97] As is remarked by Mr. Innes,
[98] this was, perhaps, but a partial destruction, as, three years afterwards,
Mary of Lorraine held at Newbotle a great convention of the lords of her
party, preparatory to declaring war with England.
The last so-called abbot was Mark Ker. He is styled Commendator of
Newbotle in 1560; and the lordship of Newbotle, being conferred on his son,
has remained with their descendants to the present day.
Such is the scanty history of this great abbey, so far as relates to the
structure and ornaments; but of the former almost nothing remains above
ground except part of the monastic buildings on the east side of the cloisters.
The abbey, including the church, appears to have been almost completely
demolished shortly after the Reformation, the only parts of the monastic
buildings allowed to remain being the fratry and portions of the chapter
house, which were incorporated with the mansion house, and of the former
of which a view has already been given.[99]
The accompanying Plan (Fig. 653) has been prepared by Mr. John
Ramsay, the resident Clerk of Works to the Marquis of Lothian, showing the
result of considerable excavations recently carried out at the building,
together with some details which have been discovered. The Plan shows that
the buildings extended about 400 feet from north to south by about 270 feet
from east to west, and that the monastery was of the usual plan.
The recent excavations deal chiefly with the foundations of the abbey and
church, although explorations within the mansion have also brought to light
some old work hitherto concealed from view. The first discovery of the
existence of buried portions of the abbey was made in 1878, when some
works were in progress; and again, in 1892,
A. Presbytery. H. Fratry. O. Entrance to Cloister.
B. Crossing. I. Large Hall. P. Perhaps Porter’s Room.
C. Nave. J. Necessaria. Q. Cellars or Workshops.
D. North Transept. K. Kitchen. R. Necessaria of the Conversi.
E. South Transept. L. Refectory. S. S. Arched Culverts, separated by a Wall.
F. Slype or Sacristy. M. Passage with Stair. T. South Boundary Wall.
G. Chapter House. N. Cellars.

Fig. 653.—Newbattle Abbey. Plan.

when digging was going on connected with the planting of trees, some
further remains were found. But in 1893-4 a systematic search was made,
both above and below ground, which enabled an almost complete Plan of the
abbey to be accurately measured and laid down.[100]

Fig. 654.—Newbattle Abbey. Bases in West Side of Cloister (at Q).

The total length of the abbey church, within the walls, was 239 feet 3
inches, and on the exterior 253 feet 3 inches; while the interior width was 57
feet 1 inch, and the exterior width (excluding the buttresses) was 66 feet 7
inches. The nave, which contained ten bays, had a length of 161 feet 6
inches, and its central aisle a width of 31 feet, while the side aisles were 13
feet. The choir and presbytery comprised one bay and a-half, and had two
large piers, each 10 feet in diameter. The crossing had four similar large
piers, and measured 41 feet 9 inches over the piers. The piers supported a
tower over the crossing. The transept was 117 feet 6 inches in length from
north to south, and had an eastern aisle, making the width 45 feet. The north
transept had enormous angle buttresses and a square pier. The large piers and
flat angle buttresses of the choir indicate early work, probably Norman.
The great angle buttresses at the north transepts belong, doubtless, to a
late period. The Plan clearly shows that they have been added to existing flat
buttresses, in the same manner as was done at the east wall of St. Andrews
Cathedral. Unfortunately, no details have been discovered to enable the date
to be more definitely fixed.
Fig. 655.—Newbattle Abbey. Font.

Fig. 656.—Newbattle Abbey. Seated Figure of Ecclesiastic.

The east side of the cloister, which is included in the modern mansion,
extends southwards from the church for a distance of about 200 feet.
Adjoining the transept has been the slype or sacristy; then comes the chapter
house, of which only the bases of a double row of pillars remain. It was
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookgate.com

You might also like