Apago PDF Enhancer
JAVA
Programming
Fundamentals
Problem Solving Through Object
Oriented Analysis and Design
Apago PDF Enhancer
CRC_C6547_FM.indd i
10/16/2008 4:35:38 PM
This page intentionally left blank
fb.com/ebook.sos
JAVA
Programming
Fundamentals
Problem Solving Through Object
Oriented Analysis and Design
Apago PDF Enhancer
Premchand S. Nair
CRC_C6547_FM.indd iii
10/16/2008 4:35:40 PM
CRC Press
Taylor & Francis Group
6000 Broken Sound Parkway NW, Suite 300
Boca Raton, FL 33487-2742
© 2009 by Taylor & Francis Group, LLC
CRC Press is an imprint of Taylor & Francis Group, an Informa business
No claim to original U.S. Government works
Printed in the United States of America on acid-free paper
10 9 8 7 6 5 4 3 2 1
International Standard Book Number-13: 978-1-4200-6547-3 (Softcover)
This book contains information obtained from authentic and highly regarded sources. Reasonable efforts have been
made to publish reliable data and information, but the author and publisher cannot assume responsibility for the validity of all materials or the consequences of their use. The authors and publishers have attempted to trace the copyright
holders of all material reproduced in this publication and apologize to copyright holders if permission to publish in this
form has not been obtained. If any copyright material has not been acknowledged please write and let us know so we may
rectify in any future reprint.
Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, transmitted, or utilized in any form by any electronic, mechanical, or other means, now known or hereafter invented, including photocopying, microfilming, and recording, or in any information storage or retrieval system, without written permission from the
publishers.
Apago PDF Enhancer
For permission to photocopy or use material electronically from this work, please access www.copyright.com (http://
www.copyright.com/) or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA 01923,
978-750-8400. CCC is a not-for-profit organization that provides licenses and registration for a variety of users. For organizations that have been granted a photocopy license by the CCC, a separate system of payment has been arranged.
Trademark Notice: Product or corporate names may be trademarks or registered trademarks, and are used only for
identification and explanation without intent to infringe.
Library of Congress Cataloging-in-Publication Data
Nair, Premchand S., 1956Java programming fundamentals : problem solving through object oriented analysis and design / by
Premchand S. Nair.
p. cm.
Includes bibliographical references and index.
ISBN-13: 978-1-4200-6547-3
ISBN-10: 1-4200-6547-5
1. Java (Computer program language) 2. Object-oriented programming (Computer science) I. Title.
QA76.73.J38N345 2008
005.1’17--dc22
Visit the Taylor & Francis Web site at
and the CRC Press Web site at
2008017335
Dedication
To five people in my life,
M.K. Krishna Pillai
Grandfather
S. Sukumaran Nair
Dad
Sarada Devi
Apago A.PDF
Enhancer
Mom
Suseela Nair
Wife
Meera Nair
Daughter
CRC_C6547_FM.indd v
10/16/2008 4:35:41 PM
This page intentionally left blank
Apago PDF Enhancer
Contents
Preface
xix
Acknowledgments
xxiii
Author
xxv
CHAPTER 1 Object Model of Computation
1
INTRODUCTION
1
OBJECT MODEL OF COMPUTATION
2
DATA REPRESENTATION
5
HARDWARE OVERVIEW
5
BRIEF HISTORY OF PROGRAMMING LANGUAGES AND
MODELS OF COMPUTATION
6
CREATING AND EXECUTING JAVA PROGRAM
8
Step 1. Create Java Source File
8
Step 2. Compile Source Code into Bytecode
8
Step 3. Execute Java Program
9
Apago PDF Enhancer
INTRODUCTION TO SOFTWARE ENGINEERING
10
Analysis and Use Case Diagram
12
REVIEW
14
EXERCISES
16
ANSWERS TO SELF-CHECK
17
CHAPTER 2 Class and Java Fundamentals
19
JAVA APPLICATION PROGRAM
20
Identifier
21
vii
CRC_C6547_FM.indd vii
10/16/2008 4:35:41 PM
viii
■
Contents
Reserved Word
24
Comment Lines
24
JAVA GREETINGS PROGRAM
26
Advanced Topic 2.1: Frequently Used Escape Sequences
27
Advanced Topic 2.2: Details on println Method
29
Concatenation and the length of Strings
29
Positional Value of a Character in String
30
DATA TYPES
31
Primitive Data Types
32
boolean Data Type
33
char Data Type
33
Advanced Topic 2.3: Unicode Character Specification
35
Integer Data Type
35
Advanced Topic 2.4: Various Integer Representations
36
Floating Point Data Type
36
Advanced Topic 2.5: Floating Point Notation
37
OPERATIONS ON NUMERIC DATA TYPES
37
Operator Precedence Rules
40
Rules for Evaluating Mixed Expressions
42
Advanced Topic 2.6: Mixed Expressions Involving String
44
NAMED CONSTANTS AND VARIABLES
46
Changing Data Values of Variable
51
Assignment Statement
51
INPUT STATEMENT
55
PACKAGES AND import STATEMENT
57
Single Character Input
58
INTERACTIVE MODE AND PROMPT LINES
60
EXPLICIT DATA–TYPE CONVERSION
61
Advanced Topic 2.7: Increment and Decrement Operators
63
Advanced Topic 2.8: Compound Assignment Operators
65
REVIEW
66
EXERCISES
67
PROGRAMMING EXERCISES
74
ANSWERS TO SELF-CHECK
75
Apago PDF Enhancer
CRC_C6547_FM.indd viii
10/16/2008 4:35:41 PM
Contents
CHAPTER 3 Class Design
■
ix
77
CLASS
77
Attributes
78
Operations
80
METHOD INVOCATION
80
METHOD DEFINITION
82
CATEGORIES OF VARIABLES
84
Syntax Template
85
Initialization
85
Scope
85
Existence
86
return STATEMENT
86
JAVADOC CONVENTION
86
ACCESSOR METHOD
86
MUTATOR METHOD
88
toString METHOD
90
Apago PDF Enhancer
APPLICATION-SPECIFIC METHODS
90
CONSTRUCTOR
91
PUTTING ALL PIECES TOGETHER
92
Advanced Topic 3.1: Representing Class in UML 2
94
TESTING
95
Advanced Topic 3.2: Representing Relationship in UML 2
98
Advanced Topic 3.3: Class Design, Implementation,
and Testing
99
Design
99
Decide on Attributes
100
Decide on Methods
100
Implementation
102
Testing
104
REVIEW
106
EXERCISES
108
PROGRAMMING EXERCISES
111
ANSWERS TO SELF-CHECK
112
CRC_C6547_FM.indd ix
10/16/2008 4:35:41 PM
x
■
Contents
CHAPTER 4 Decision Making
115
CONTROL STRUCTURES
115
LOGICAL EXPRESSION AND OPERATORS
118
LOGICAL OPERATORS
120
RELATIONAL OPERATORS
123
RELATIONAL OPERATORS AND NUMERICAL DATA TYPES
124
RELATIONAL OPERATORS AND CHARACTER DATA TYPES
126
Advanced Topic 4.1: Relational Operators and Objects
127
LEXICOGRAPHICAL ORDERING OF STRINGS
127
Advanced Topic 4.2: Equality Operators and String Class
130
PRECEDENCE RULES
132
Advanced Topic 4.3: Syntax Error Explained
137
Advanced Topic 4.4: Short-Circuit Evaluation
137
Advanced Topic 4.5: Additional Logical Operators
138
Advanced Topic 4.6: Positive Logic
140
SELECTION STRUCTURES
142
Apago PDF Enhancer
ONE-WAY SELECTION STRUCTURE
142
BLOCK STATEMENT
148
TWO-WAY SELECTION STRUCTURE
151
PRIMITIVE DATA TYPE boolean
156
NESTED STRUCTURES
157
Advanced Topic 4.7: Better Coding Options
161
Advanced Topic 4.8: Order of Logical Expressions
164
Advanced Topic 4.9: Overriding if ... else Pairing Rule
165
Advanced Topic 4.10: Ternary Operator
166
MULTIWAY STRUCTURE switch
167
Advanced Topic 4.11: Sharing Code in a switch Statement
170
Advanced Topic 4.12: Limitations of a switch Statement
173
Advanced Topic 4.13: Enumerated Types
177
CASE STUDY 4.1: PAYROLL FOR A SMALL BUSINESS
180
Specification
180
Input
181
Output
181
Decide on Classes
181
CRC_C6547_FM.indd x
10/16/2008 4:35:42 PM
Contents
■
xi
Decide on Attributes
181
Decide on Methods
182
Implementation
184
Application Program
193
Testing
196
REVIEW
197
EXERCISES
199
PROGRAMMING EXERCISES
204
ANSWERS TO SELF-CHECK
206
CHAPTER 5 The Power of Repetition
209
CONTROL STRUCTURES
210
USING TEXT FILE FOR INPUT
211
Declaring Exceptions
211
USING FILE FOR OUTPUT
213
Method close
213
REPETITION STRUCTURE: while
215
PDF Enhancer
Counter-ControlledApago
while Statement
218
Advanced Topic 5.1: Use of Counter inside Counter-Controlled
while Statement
222
Advanced Topic 5.2: Event-Controlled while Statement
224
Advanced Topic 5.3: Data-Controlled while Statement
227
Data Validation
227
Sentinel Data
227
REPETITION STRUCTURE: for
229
Advanced Topic 5.4: Use of Counter inside for Statement
234
Advanced Topic 5.5: Repetition Statement : do … while
235
Advanced Topic 5.6: Guidelines for Choosing Repetition Structure
238
NESTING OF CONTROL STRUCTURES
239
Advanced Topic 5.7: Statements break and continue
245
Statements break and continue with Optional Label
249
CASE STUDY 5.1: PAYROLL FOR SMALL BUSINESS: REVISITED
252
Specification
252
Input
252
Output
252
CRC_C6547_FM.indd xi
10/16/2008 4:35:42 PM
xii
■
Contents
Application Program
252
Testing
256
REVIEW
256
EXERCISES
257
PROGRAMMING EXERCISES
263
ANSWERS TO SELF-CHECK
266
CHAPTER 6 Methods and Constructors
267
CLASSIFICATION OF METHODS
267
Math Class
270
Character Class
272
String Class
272
METHOD INVOCATION
274
USER-DEFINED METHODS
281
Formal Parameter List
282
Signature of a Method
282
Parameter Passing Apago PDF Enhancer
284
CONSTRUCTORS
297
Copy Constructor
305
Self-Reference
308
Advanced Topic 6.1: Common Methods
309
copy Method
309
equals Method
313
Advanced Topic 6.2: Finalizer and Garbage Collection
316
Advanced Topic 6.3: Class Variable
318
static Methods
321
Advanced Topic 6.4: Creating and Using Packages
328
Option 1
328
Option 2
329
Step 1
329
Step 2
330
Step 3
330
Step 4
331
Step 5
331
CRC_C6547_FM.indd xii
10/16/2008 4:35:42 PM
Contents
■
xiii
CASE STUDY 6.1: FRACTION CALCULATOR
331
REVIEW
344
EXERCISES
345
PROGRAMMING EXERCISES
351
ANSWERS TO SELF-CHECK
353
CHAPTER 7 Object-Oriented Software Design
355
OBJECTS
355
Data-Centric View
356
Attribute
356
Operation
356
Client–Server View
357
Soft ware Design View
359
SUBCLASS
359
Inheritance
361
Creating Subclass
363
Invoking Method ofApago
Superclass PDF Enhancer
365
Accessing Private Attribute of Superclass
366
Invoking Constructor of Superclass
366
Subclass Objects as Superclass Instance
376
Polymorphic Behavior
377
Advanced Topic 7.1: instanceof Operator
381
Advanced Topic 7.2: Use of protected Attributes
381
Advanced Topic 7.3: Design Options
386
protected Operations
386
package Access
386
Modifier final
386
ABSTRACT CLASSES AND METHODS
387
Advanced Topic 7.4: Object Class
403
Advanced Topic 7.5: Composition
403
Accessor and Mutator Methods
404
Constructor
405
Application-Specific Services
406
INTERFACE
412
CRC_C6547_FM.indd xiii
10/16/2008 4:35:42 PM
xiv
■
Contents
CASE STUDY 7.1: PAYROLL FOR SMALL BUSINESS: REDESIGNED
412
REVIEW
427
EXERCISES
429
PROGRAMMING EXERCISES
432
ANSWERS TO SELF-CHECK
433
CHAPTER 8 GUI Applications, Applets, and Graphics
435
COMMON THEME BEHIND ALL GUI APPLICATION PROGRAMS
436
CREATING APPLICATION WINDOW
437
Creating New Application Class
438
Invoking Constructor of Superclass
440
Define Size of JFrame
440
Make JFrame Visible
441
Provide Graceful Way to Exit Application
441
Get Reference of Content Pane
444
Create and Place GUI Components in Content Pane
445
Apago PDF Enhancer
Component creation
445
Component placement
448
EVENT-DRIVEN PROGRAMMING
450
Event-Driven Model of Computation
451
Implementing Listener interface
452
Registering Listener interface
454
METRIC CONVERSION HELPER
458
Advanced Topic 8.1: Programming Options for Implementing
Event Listeners
466
Option B
467
Option C
470
Option D
471
Advanced Topic 8.2: Applets
472
Creating Applet from GUI Application
473
Advanced Topic 8.3: Applet and GUI Application
483
Advanced Topic 8.4: Graphics
490
Advanced Topic 8.5: Color
494
Advanced Topic 8.6: Font
500
Advanced Topic 8.7: Drawing Services
503
CRC_C6547_FM.indd xiv
10/16/2008 4:35:42 PM
Contents
■
xv
REVIEW
505
EXERCISES
506
PROGRAMMING EXERCISES
508
ANSWERS TO SELF-CHECK
510
CHAPTER 9 Simple Data Structures
513
ONE-DIMENSIONAL ARRAY
514
Declaring Array
514
Instantiating Array
515
Advanced Topic 9.1: Programming Option
518
Advanced Topic 9.2: Alternate Syntax
519
Attribute length
519
PROCESSING ONE-DIMENSIONAL ARRAYS
521
Initialize Array with Certain Specific Values
522
Enhanced for Statement
522
Initialize Array Locations with Different Values
524
Apago PDF Enhancer
Initialize Array Using User Input
525
Output Array
525
Perform Various Numeric Computations
526
Search for Item
527
CASE STUDY 9.1: MR. GRACE’S LATEST GRADING POLICY
528
Advanced Topic 9.3: Array Index Out of Bounds Exception
535
Advanced Topic 9.4: Assignment and Relational Operators
536
Advanced Topic 9.5: Role of Inheritance
539
Advanced Topic 9.6: Passing Arrays as Parameters in Methods
543
Advanced Topic 9.7: Returning Arrays in Method Invocation
549
TWO-DIMENSIONAL ARRAY
551
Declaring and Instantiating Array
552
Advanced Topic 9.8: Alternate Syntax
554
Advanced Topic 9.9: Ragged Array
555
Advanced Topic 9.10: Processing Two-Dimensional Arrays
556
Processing Specific Row
556
Processing Entire Array Row by Row
558
Processing Specific Column
559
Processing Entire Array Column by Column
560
CRC_C6547_FM.indd xv
10/16/2008 4:35:43 PM
xvi
■
Contents
Advanced Topic 9.11: Passing Arrays as Parameter in Methods
561
Advanced Topic 9.12: Returning Arrays in Method Invocation
568
Advanced Topic 9.13: Multidimensional Array
571
Vector AND ArrayList CLASSES
573
Wrapper Classes
574
Advanced Topic 9.14: Abstract Data Types
583
CASE STUDY 9.2: MR. GRACE’S GRADE SHEET
584
REVIEW
588
EXERCISES
589
PROGRAMMING EXERCISES
593
ANSWERS TO SELF-CHECK
595
CHAPTER 10 Search and Sort
597
SEARCH ALGORITHMS
600
Linear Search
600
Binary Search
605
Apago PDF Enhancer
EFFICIENCY OF ALGORITHMS
612
Empirical Approach
612
Analysis Approach
616
Advanced Topic 10.1: Levels of Complexity
617
SORT ALGORITHMS
618
Selection Sort
618
Insertion Sort
623
Bubble Sort
627
CASE STUDY 10.1: MR. GRACE’S SORTED GRADE SHEET
634
REVIEW
641
EXERCISES
642
PROGRAMMING EXERCISES
644
ANSWERS TO SELF-CHECK
644
CHAPTER 11 Defensive Programming
647
INTRODUCTION
647
EXCEPTION AND ERROR
648
Unchecked and Checked Exceptions
648
CRC_C6547_FM.indd xvi
10/16/2008 4:35:43 PM
Contents
■
xvii
THROWING AND CATCHING OF EXCEPTIONS
650
Throwing Exception
652
Catching Exception
654
Advanced Topic 11.1: Design Options for catch Block
663
Advanced Topic 11.2: User-Defined Exception Class
666
Advanced Topic 11.3: Design Options for Exception Handling
668
REVIEW
668
EXERCISES
669
PROGRAMMING EXERCISES
670
ANSWERS TO SELF-CHECK
671
Appendix A: Operator Precedence
673
Appendix B: ASCII Character Set
675
Appendix C: Keywords
677
Appendix D: Coding Conventions
679
Appendix E : JDK and Documentation
681
Apago PDF Enhancer
Appendix F: Solution to Odd-Labeled Exercises
685
Index
711
CRC_C6547_FM.indd xvii
10/16/2008 4:35:43 PM
This page intentionally left blank
Apago PDF Enhancer
Preface
Programming is an art. Although traditional art imitates life, programming simulates life.
Every abstract concept in programming, and to a great extent in the field of computer science, has its roots in our daily life. For example, humans and possibly all other living forms
were multiprocessing long before the term entered into computer science lingo. Therefore,
any concept in programming can in fact be illustrated through examples from our dayto-day life. Such an approach not only enables the student to assimilate and internalize
the concept presented in a programming situation but also provides a solid foundation for
the very process of programming, namely, the simulation of the real world. Unfortunately,
textbooks currently on the market do not exploit this fact through examples or meaningful discussions. Thus, for many students, an abstract concept remains abstract. This is
especially true in the case of object-oriented programming. The “wow moment” one gets
by seeing programming as a simulation of the real-world situation is never realized.
This book on Java programming teaches object-oriented design and programming principles in a completely integrated and incremental fashion. This book allows the reader to
experience the world we live in as object-oriented. From the very outset the reader will
realize that everything in this world is an object. Every concept of object-oriented design
is first illustrated through real-life analogy. Corresponding Java language constructs are
introduced in an integrated fashion to demonstrate the programming required to simulate
the real-world situation. Instead of compartmentalizing all the object-oriented concepts
into one chapter, this book takes an incremental approach.
The pedagogy of this book mirrors the classroom style the author has developed over the
years as a teacher of computer science. In particular, every programming concept is introduced through simple examples followed by short programming examples. Case studies
at the end of each chapter illustrate various design issues as well as the usefulness of many
new concepts encountered in that chapter.
Java has emerged as the primary language for soft ware development. From a soft ware
engineering perspective, object-oriented design has established itself as the industry standard. Thus, more and more teaching institutions are moving toward a CS1 course that
teaches Java programming and object-oriented design principles. A common approach
followed in many textbooks on the market is to introduce object-oriented concepts from
the very beginning and ignore many traditional programming techniques completely. The
objective of this book is to present object-oriented programming and design without compromising the training one needs on traditional programming constructs and structures.
Apago PDF Enhancer
xix
CRC_C6547_FM.indd xix
10/16/2008 4:35:43 PM
xx
■
Preface
OUTSTANDING FEATURES
• Object first approach and unified modeling language (UML). The object-oriented
design principles and UML notation are introduced from the very beginning. Case
studies at the end of each chapter take the reader through a journey that starts at
requirement specification and ends at an object-oriented program.
• Incremental approach to topic presentation. Object-oriented concepts are introduced
in an incremental fashion. This book does not compartmentalize all object-oriented
principles into one chapter; rather, new concepts are introduced and used throughout
the book.
• In-depth treatment of topics. Concepts on object-oriented design and programming
are presented in an in-depth fashion. The reader could easily master all concepts by
working through various examples. Topics that can be skipped in an introductory
course are labeled as Advanced Topic and can be omitted.
• Numerous examples drawn from everyday life. This book contains many fully developed programming examples. In addition, each concept is illustrated through
simple examples drawn from everyday life. Examples do not depend on mastery in
mathematics.
• Notes on common pitfalls and good programming practice. Notes on common pitfalls
and good programming styles appear throughout this book.
Apago PDF Enhancer
PEDAGOGICAL ELEMENTS
Every chapter begins with a list of objectives. This list in a way summarizes the theme of
the chapter.
This book uses examples at four different levels. First, simple examples are presented. To
follow those examples, the reader need not know anything about programming or material
covered in the book until then. Second, examples are provided to illustrate the proper and
appropriate usage. Third, examples illustrate the new concept through a simple program.
Fourth, case study examples are employed to demonstrate the need and effectiveness of the
concept in a broader problem-solving context.
Introspection, a unique pedagogical element of this book, is a thought-provoking technique that will empower the instructor with ample materials to start a discussion on the
major concepts discussed in each section. This technique will enable the student to internalize the concepts in a meaningful way.
Self-check questions are presented at the end of each subsection. It not only checks the
understanding of the subject matter presented in the subsection but also highlights the
major concepts the reader is expected to know from that point on.
The quick review presented at the end of each chapter provides a summary of the chapter. The aim of the quick review is to highlight major points explained in the chapter. Thus,
quick review works as a checklist for the student as well.
CRC_C6547_FM.indd xx
10/16/2008 4:35:43 PM
Preface
■
xxi
Each chapter presents major constructs of Java language along with topics that can be
covered depending on the availability of time and the student’s level of comprehension.
Those topics are labeled as Advanced Topic for easy identification.
The case study at the end of the chapter serves two important purposes. First, it allows
the reader to see the application of the new concepts learned in a practical situation. Second,
we have used two major themes throughout the book. The same theme is used at different
levels of complexity to illustrate the application and usefulness of the new concepts.
Solved exercises at the end of each chapter provide enough challenges and further consolidate the concepts introduced in the chapter.
SUPPLEMENTS AND COMPANION WEBSITE
The companion website www.premnair.net contains many useful links, documents, and
programs. The instructor can obtain the instructor’s manual that contains solutions to all
problems presented at the end of the chapter, including the programming exercises. Both
the instructor and the students can access all programs presented in this book as well as
PowerPoint presentations of each of the chapters.
CHAPTER DEPENDENCY
Chapters in this book can be taught in the sequence presented. However, the instructor has
the liberty to tailor the course on the basis of the needs as long as the following dependency
diagram is followed:
Apago PDF Enhancer
Chapters 1 through 6
Chapter 7
Chapter 9
Chapter 10
Chapter 8
CRC_C6547_FM.indd xxi
Chapter 11
10/16/2008 4:35:43 PM
This page intentionally left blank
Apago PDF Enhancer
Acknowledgments
I am extremely thankful to the following reviewers whose valuable suggestions and corrections transformed my manuscript into this book in its present form: Dr. Mark Meysenburg
(Doane College) and Dr. Charles Riedesel (University of Nebraska–Lincoln). I have a wonderful person, Randi Cohen, as my acquisition editor at Taylor & Francis. She is one of the
most kind-hearted and efficient persons I have ever known. I am so lucky to work with
her on this project. I would like to thank Amber Donley, the project coordinator, Editorial
Project Development, for the successful and timely completion of this project.
I would like to thank my wife Dr. Suseela Nair, who patiently read the entire manuscript
several times and gave me many valuable suggestions and corrections. I am grateful to my
daughter Meera Nair for all her love. My thanks are also due to my parents, S. Sukumaran
Nair and A. Sarada Devi, and grandfather M.K. Krishna Pillai for all the wonderful things
in my life. Thanks are also due to George and Susan Koshy, who are my best friends. They
have been my cheerleaders and advisors for the past two decades.
I am so grateful to Creighton University, which has supported all my professional efforts
throughout my career. I would, in particular, like to thank Dr. Robert E. Kennedy, dean
of the College of Arts and Science, one of the most decent, honest, and fair-minded persons this great institution has ever had. It is my privilege and honor to work under his
leadership.
I welcome your comments and suggestions. Please contact me through e-mail at prem@
premnair.net.
Apago PDF Enhancer
Premchand S. Nair
xxiii
CRC_C6547_FM.indd xxiii
10/16/2008 4:35:44 PM
This page intentionally left blank
Apago PDF Enhancer