
22,786 5,101 11MB
Pages 908 Page size 252 x 315.72 pts Year 2000
Java Programming Fifth Edition Joyce Farrell
Australia • Brazil • Japan • Korea • Mexico • Singapore • Spain • United Kingdom • United States
Java Programming, Fifth Edition Joyce Farrell Executive Editor: Marie Lee Acquisitions Editor: Amy Jollymore Managing Editor: Tricia Coia Development Editor: Dan Seiter Editorial Assistant: Julia Leroux-Lindsey Marketing Manager: Bryant Chrzan Content Project Manager: Heather Furrow Art Director: Marissa Falco Cover Designer: Bruce Bond Cover Photo: TBD
© 2010 Course Technology, Cengage Learning ALL RIGHTS RESERVED. No part of this work covered by the copyright herein may be reproduced, transmitted, stored, or used in any form or by any means— graphic, electronic, or mechanical, including but not limited to photocopying, recording, scanning, digitizing, taping, Web distribution, information networks, or information storage and retrieval systems, except as permitted under Section 107 or 108 of the 1976 United States Copyright Act—without the prior written permission of the publisher. For product information and technology assistance, contact us at Cengage Learning Customer & Sales Support, 1-800-354-9706 For permission to use material from this text or product, submit all requests online at www.cengage.com/permissions Further permissions questions can be e-mailed to [email protected]
Microsoft® is a registered trademark of the Microsoft Corporation.
Manufacturing Coordinator: Julio Esperas
ISBN-13: 978-0-3245-9951-0
Proofreader: Andrea Schein
ISBN-10: 0-3245-9951-X
Indexer: Elizabeth Cunningham Compositor: International Typesetting and Composition
Course Technology 25 Thomson Place 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.international.cengage.com/region Cengage Learning products are represented in Canada by Nelson Education, Ltd. To learn more about Course Technology, visit www.cengage.com/coursetechnology Purchase any of our products at your local bookstore or at our preferred online store www.ichapters.com Some of the product names and company names used in this book have been used for identification purposes only and may be trademarks or registered trademarks of their respective manufacturers and sellers. Course Technology, a part of Cengage Learning, reserves the right to revise this publication and make changes from time to time in its content without notice.
Printed in Canada 1 2 3 4 5 6 7 12 11 10 09 08
BRIEF CONTENTS PREFACE
xix
READ THIS BEFORE YOU BEGIN
xxv
CHAPTER 1 CREATING YOUR FIRST JAVA CLASSES
1
CHAPTER 2 USING DATA WITHIN A PROGRAM
43
CHAPTER 3 USING METHODS, CLASSES, AND OBJECTS
89
CHAPTER 4 MORE OBJECT CONCEPTS
135
CHAPTER 5 MAKING DECISIONS
187
CHAPTER 6 LOOPING
233
CHAPTER 7 CHARACTERS, STRINGS, AND THE STRINGBUILDER
273
CHAPTER 8 ARRAYS
309
CHAPTER 9 INTRODUCTION TO INHERITANCE
369
CHAPTER 10 ADVANCED INHERITANCE CONCEPTS
413
CHAPTER 11 EXCEPTION HANDLING
461
CHAPTER 12 FILE INPUT AND OUTPUT
525
CHAPTER 13 INTRODUCTION TO SWING COMPONENTS
587
CHAPTER 14 ADVANCED GUI TOPICS
641
CHAPTER 15 GRAPHICS
709
CHAPTER 16 APPLETS, IMAGES, AND SOUND
763
APPENDIX A WORKING WITH THE JAVA PLATFORM
807
APPENDIX B LEARNING ABOUT ASCII AND UNICODE
815
APPENDIX C FORMATTING OUTPUT
821
APPENDIX D GENERATING RANDOM NUMBERS
833
APPENDIX E JAVADOC
839
GLOSSARY
847
INDEX
867 iii
This page intentionally left blank
CONTENTS PREFACE
xix
READ THIS BEFORE YOU BEGIN
xxv
CHAPTER 1 CREATING YOUR FIRST JAVA CLASSES
1
LEARNING ABOUT PROGRAMMING
2
INTRODUCING OBJECT-ORIENTED PROGRAMMING CONCEPTS Procedural Programming Object-Oriented Programming Understanding Objects, Classes, and Encapsulation Understanding Inheritance and Polymorphism
4 4 4 5 7
LEARNING ABOUT JAVA Java Program Types
8 9
ANALYZING A JAVA APPLICATION THAT USES CONSOLE OUTPUT Understanding the Statement That Prints the Output Understanding the First Class Understanding the main() Method
10 10 11 14
ADDING COMMENTS TO A JAVA CLASS
16
SAVING, COMPILING, RUNNING, AND MODIFYING A JAVA APPLICATION Saving a Java Class Compiling a Java Class Running a Java Application Modifying a Java Class
18 18 18 19 19
CREATING A JAVA APPLICATION USING GUI OUTPUT
21
CORRECTING ERRORS AND FINDING HELP
23
YOU DO IT Your First Application Adding Comments to a Class Modifying a Class Creating a Dialog Box
26 26 27 28 29
DON’T DO IT
30
KEY TERMS
31
CHAPTER SUMMARY
34
REVIEW QUESTIONS
35
EXERCISES
37
v
CONTENTS
DEBUGGING EXERCISES
39
GAME ZONE
39
TOUGH QUESTIONS
40
UP FOR DISCUSSION
41
CHAPTER 2 USING DATA WITHIN A PROGRAM
43
USING CONSTANTS AND VARIABLES Declaring Variables Declaring Named Constants Pitfall: Forgetting That a Variable Holds One Value at a Time
44 45 46 48
LEARNING ABOUT THE int DATA TYPE
48
DISPLAYING DATA
50
WRITING ARITHMETIC STATEMENTS Writing Arithmetic Statements Efficiently
51 53
USING THE BOOLEAN DATA TYPE
54
LEARNING ABOUT FLOATING-POINT DATA TYPES
55
UNDERSTANDING NUMERIC-TYPE CONVERSION
56
WORKING WITH THE char DATA TYPE
58
USING THE Scanner CLASS FOR KEYBOARD INPUT Pitfall: Using nextLine() Following One of the Other Scanner Input Methods
61
USING THE JOptionPane CLASS FOR GUI INPUT Using Input Dialog Boxes Using Confirm Dialog Boxes
66 66 70
YOU DO IT Working with Numeric Values Accepting User Data Performing Arithmetic Experimenting with Java Programs
72 72 73 74 75
DON’T DO IT
76
63
KEY TERMS
77
CHAPTER SUMMARY
80
REVIEW QUESTIONS
81
EXERCISES
83
DEBUGGING EXERCISES
86
GAME ZONE
86
TOUGH QUESTIONS
86
UP FOR DISCUSSION
87
vi
CONTENTS
CHAPTER 3 USING METHODS, CLASSES, AND OBJECTS
89
CREATING METHODS WITH ZERO, ONE, AND MULTIPLE PARAMETERS Creating Methods That Require a Single Parameter Creating Methods That Require Multiple Parameters
90 94 97
CREATING METHODS THAT RETURN VALUES Calling a Method from Another Method
99 101
LEARNING ABOUT CLASS CONCEPTS
102
CREATING A CLASS
104
CREATING INSTANCE METHODS IN A CLASS
106
DECLARING OBJECTS AND USING THEIR METHODS Understanding Data Hiding
109 110
ORGANIZING CLASSES
112
AN INTRODUCTION TO USING CONSTRUCTORS
114
UNDERSTANDING THAT CLASSES ARE DATA TYPES
116
YOU DO IT Creating a Static Method That Requires No Arguments and Returns No Values Calling a Static Method from Another Class Creating a Static Method That Accepts Arguments and Returns Values Creating a Class That Contains Instance Fields and Methods Creating a Class That Instantiates Objects of Another Class Adding a Constructor to a Class Creating a More Complete Class
118 118 119 120 122 123 124 124
DON’T DO IT
125
KEY TERMS
125
CHAPTER SUMMARY
127
REVIEW QUESTIONS
128
EXERCISES
131
DEBUGGING EXERCISES
133
GAME ZONE
133
TOUGH QUESTIONS
134
UP FOR DISCUSSION
134
CHAPTER 4 MORE OBJECT CONCEPTS
135
UNDERSTANDING BLOCKS AND SCOPE
136
OVERLOADING A METHOD
142
LEARNING ABOUT AMBIGUITY
144
SENDING ARGUMENTS TO CONSTRUCTORS
147
OVERLOADING CONSTRUCTORS
148
vii
CONTENTS
LEARNING ABOUT THE this REFERENCE Using the this Reference to Make Overloaded Constructors More Efficient
149 152
USING static VARIABLES
154
USING CONSTANT FIELDS
156
USING AUTOMATICALLY IMPORTED, PREWRITTEN CONSTANTS AND METHODS
157
USING AN EXPLICITLY IMPORTED PREWRITTEN CLASS AND ITS METHODS
160
UNDERSTANDING COMPOSITION
164
A BRIEF LOOK AT NESTED AND INNER CLASSES
166
YOU DO IT Demonstrating Scope Overloading Methods Creating a Constructor That Requires an Argument Using an Explicitly Imported Prewritten Class Creating an Interactive Application with a Timer
168 168 170 171 172 174
DON’T DO IT
176
KEY TERMS
176
CHAPTER SUMMARY
177
REVIEW QUESTIONS
178
EXERCISES
181
DEBUGGING EXERCISES
184
GAME ZONE
184
TOUGH QUESTIONS
185
UP FOR DISCUSSION
185
CHAPTER 5 MAKING DECISIONS
187
UNDERSTANDING DECISION MAKING
188
MAKING DECISIONS WITH THE if AND if...else STRUCTURES Pitfall: Misplacing a Semicolon in an if Statement Pitfall: Using the Assignment Operator Instead of the Equivalency Operator Pitfall: Attempting to Compare Objects Using the Relational Operators The if...else Structure
190 191 192 192 193
USING MULTIPLE STATEMENTS IN AN if OR if...else STRUCTURE
194
NESTING if AND if...else STATEMENTS
197
USING LOGICAL AND and OR OPERATORS
199
MAKING ACCURATE AND EFFICIENT DECISIONS Using AND and OR Appropriately
202 205
USING THE switch STATEMENT
206
USING THE CONDITIONAL AND NOT OPERATORS Using the NOT Operator
209 210
UNDERSTANDING PRECEDENCE
211 viii
CONTENTS
YOU DO IT Using an if...else Creating an Event Class to Use in a Decision-Making Application Writing an Application that Uses the Event class Using the switch Statement
213 213 215 216 218
DON’T DO IT
219
KEY TERMS
220
CHAPTER SUMMARY
221
REVIEW QUESTIONS
221
EXERCISES
224
DEBUGGING EXERCISES
229
GAME ZONE
229
TOUGH QUESTIONS
231
UP FOR DISCUSSION
232
CHAPTER 6 LOOPING
233
LEARNING ABOUT THE LOOP STRUCTURE
234
USING A while LOOP TO CREATE A DEFINITE LOOP
235
USING A while LOOP TO CREATE AN INDEFINITE LOOP
239
USING SHORTCUT ARITHMETIC OPERATORS
243
USING A for LOOP
246
LEARNING HOW AND WHEN TO USE A do...while LOOP
248
LEARNING ABOUT NESTED LOOPS
250
IMPROVING LOOP PERFORMANCE Avoiding Unnecessary Operations Considering the Order of Evaluation of Short-Circuit Operators Comparing to Zero Employing Loop Fusion
252 253 253 254 255
YOU DO IT Writing a Loop to Validate Data Entries Working with Prefix and Postfix Increment Operators Working with Definite Loops Working with Nested Loops
256 256 257 259 260
DON’T DO IT
261
KEY TERMS
262
CHAPTER SUMMARY
263
REVIEW QUESTIONS
264
EXERCISES
267
DEBUGGING EXERCISES
269 ix
CONTENTS
GAME ZONE
269
TOUGH QUESTIONS
270
UP FOR DISCUSSION
271
CHAPTER 7 CHARACTERS, STRINGS, AND THE STRINGBUILDER
273
IDENTIFYING PROBLEMS THAT CAN OCCUR WHEN YOU MANIPULATE STRING DATA
274
MANIPULATING CHARACTERS
276
DECLARING A String OBJECT
278
COMPARING String VALUES
279
USING OTHER String METHODS
283
CONVERTING Strings TO NUMBERS
286
LEARNING ABOUT THE StringBuilder AND StringBuffer CLASSES
288
YOU DO IT Using String Class Methods Converting a String to an Integer Using StringBuilder Methods
293 293 295 296
DON’T DO IT
297
KEY TERMS
297
CHAPTER SUMMARY
299
REVIEW QUESTIONS
300
EXERCISES
302
DEBUGGING EXERCISES
305
GAME ZONE
305
TOUGH QUESTIONS
307
UP FOR DISCUSSION
308
CHAPTER 8 ARRAYS
309
DECLARING AND INITIALIZING AN ARRAY Initializing an Array
310 312
USING SUBSCRIPTS WITH AN ARRAY
313
DECLARING AN ARRAY OF OBJECTS
316
SEARCHING AN ARRAY FOR AN EXACT MATCH
318
SEARCHING AN ARRAY FOR A RANGE MATCH
321
PASSING ARRAYS TO AND RETURNING ARRAYS FROM METHODS Returning an Array from a Method
323 326
MANIPULATING ARRAYS OF Strings
326
SORTING ARRAY ELEMENTS Sorting Arrays of Objects
328 332 x
CONTENTS
USING TWO-DIMENSIONAL AND MULTIDIMENSIONAL ARRAYS Using the length Field with a Two-Dimensional Array Understanding Ragged Arrays Using Multidimensional Arrays
334 336 336 336
USING THE Arrays CLASS
337
USING THE ArrayList CLASS Understanding the Limitations of the ArrayList Class
341 343
YOU DO IT Creating and Populating an Array Initializing an Array Using a for Loop to Access Array Elements Creating Parallel Arrays to Eliminate Nested if Statements Creating an Application with an Array of Objects Creating an Interactive Application That Creates an Array of Objects Passing an Array to a Method Using Arrays Class Methods
344 344 345 346 346 347 348 350 351
DON’T DO IT
353
KEY TERMS
354
CHAPTER SUMMARY
355
REVIEW QUESTIONS
356
EXERCISES
359
DEBUGGING EXERCISES
363
GAME ZONE
363
TOUGH QUESTIONS
367
UP FOR DISCUSSION
367
CHAPTER 9 INTRODUCTION TO INHERITANCE
369
LEARNING ABOUT THE CONCEPT OF INHERITANCE
370
EXTENDING CLASSES
374
OVERRIDING SUPERCLASS METHODS
376
UNDERSTANDING HOW CONSTRUCTORS ARE CALLED DURING INHERITANCE
377
USING SUPERCLASS CONSTRUCTORS THAT REQUIRE ARGUMENTS
379
ACCESSING SUPERCLASS METHODS Comparing this and super
380 382
LEARNING ABOUT INFORMATION HIDING
382
METHODS YOU CANNOT OVERRIDE A Subclass Cannot Override static Methods in Its Superclass A Subclass Cannot Override final Methods in Its Superclass A Subclass Cannot Override Methods in a final Superclass
385 385 388 390
xi
CONTENTS
YOU DO IT Creating a Superclass and an Application to Use It Creating a Subclass and an Application to Use It Creating a Subclass Method That Overrides a Superclass Method Understanding the Role of Constructors in Inheritance Inheritance When the Superclass Requires Constructor Arguments Accessing an Overridden Superclass Method from Within a Subclass
391 391 393 395 397 398 401
DON’T DO IT
402
KEY TERMS
402
CHAPTER SUMMARY
403
REVIEW QUESTIONS
404
EXERCISES
407
DEBUGGING EXERCISES
410
GAME ZONE
410
TOUGH QUESTIONS
411
UP FOR DISCUSSION
412
CHAPTER 10 ADVANCED INHERITANCE CONCEPTS
413
CREATING AND USING ABSTRACT CLASSES
414
USING DYNAMIC METHOD BINDING Using a Superclass as a Method Parameter Type
418 419
CREATING ARRAYS OF SUBCLASS OBJECTS
420
USING THE Object CLASS AND ITS METHODS Using the toString() Method Using the equals() Method
422 423 425
USING INHERITANCE TO ACHIEVE GOOD SOFTWARE DESIGN
428
CREATING AND USING INTERFACES Creating Interfaces to Store Related Constants
429 434
CREATING AND USING PACKAGES
435
YOU DO IT Creating an Abstract Class Extending an Abstract Class Extending an Abstract Class with a Second Subclass Instantiating Objects from Subclasses Using Object References Overriding the Object Class equals() Method Eliminating Duplicate User Entries Creating a Package
437 437 438 440 441 442 444 445 446
DON’T DO IT
449
KEY TERMS
449 xii
CONTENTS
CHAPTER SUMMARY
450
REVIEW QUESTIONS
451
EXERCISES
454
DEBUGGING EXERCISES
457
GAME ZONE
458
TOUGH QUESTIONS
458
UP FOR DISCUSSION
458
CHAPTER 11 EXCEPTION HANDLING
461
LEARNING ABOUT EXCEPTIONS
462
TRYING CODE AND CATCHING Exceptions
467
THROWING AND CATCHING MULTIPLE Exceptions
471
USING THE Finally BLOCK
476
UNDERSTANDING THE ADVANTAGES OF EXCEPTION HANDLING
478
SPECIFYING THE Exceptions A METHOD CAN THROW
480
TRACING Exceptions THROUGH THE CALL STACK
486
CREATING YOUR OWN Exceptions
490
USING ASSERTIONS
493
YOU DO IT Catching an Exception and Using getMessage() Generating a NumberFormatException Adding NumberFormatException Handling Capabilities to an Application Creating a Class That Automatically Throws Exceptions Creating a Class That Passes on an Exception Creating an Application That Can Catch Exceptions Extending a Class That Throws Exceptions Using the printStackTrace() Method Creating an Exception Class Using an Exception You Created
498 498 500 500 501 502 504 506 507 509 509
DON’T DO IT
513
KEY TERMS
513
CHAPTER SUMMARY
514
REVIEW QUESTIONS
515
EXERCISES
518
DEBUGGING EXERCISES
522
GAME ZONE
522
TOUGH QUESTIONS
523
UP FOR DISCUSSION
523 xiii
CONTENTS
CHAPTER 12 FILE INPUT AND OUTPUT
525
UNDERSTANDING COMPUTER FILES
526
USING THE File CLASS
527
UNDERSTANDING DATA FILE ORGANIZATION AND STREAMS
530
USING STREAMS
532
WRITING TO AND READING FROM A FILE Reading from a File
536 538
WRITING FORMATTED FILE DATA
540
READING FORMATTED FILE DATA
543
USING A VARIABLE FILENAME
545
CREATING AND USING RANDOM ACCESS FILES
548
WRITING RECORDS TO A RANDOM ACCESS FILE
551
READING RECORDS FROM A RANDOM ACCESS FILE Accessing a Random Access File Sequentially Accessing a Random Access File Randomly
556 556 557
READING AND WRITING OBJECTS TO AND FROM FILES
559
YOU DO IT Using the File Class to Examine File Status Comparing Two File Dates Using InputStream and OutputStream Objects Writing to an Output File Reading Data from a File Creating a Class to Use in a File of Objects Creating a Program that Writes Event Objects to a File Creating a Program that Accesses Stored Event Object Data
563 563 564 565 568 568 569 571 572
DON’T DO IT
576
KEY TERMS
576
CHAPTER SUMMARY
578
REVIEW QUESTIONS
579
EXERCISES
581
DEBUGGING EXERCISES
584
GAME ZONE
584
TOUGH QUESTIONS
584
UP FOR DISCUSSION
585
CHAPTER 13 INTRODUCTION TO SWING COMPONENTS
587
UNDERSTANDING Swing COMPONENTS
588
USING THE JFrame CLASS Customizing a JFrame’s Appearance
589 593 xiv
CONTENTS
USING A JLabel Changing a JLabel’s Font
594 596
USING A LAYOUT MANAGER
598
EXTENDING THE JFrame CLASS
600
ADDING JTextFields, JBUTTONS, AND TOOL TIPS TO A JFrame Adding JButtons Using Tool Tips
602 604 606
LEARNING ABOUT EVENT-DRIVEN PROGRAMMING Preparing Your Class to Accept Event Messages Telling Your Class to Expect Events to Happen Telling Your Class How to Respond to Events Using the setEnabled() Method
607 607 608 608 611
UNDERSTANDING Swing EVENT LISTENERS
611
USING THE JCheckBox CLASS
614
USING THE ButtonGroup CLASS
618
USING THE JComboBox CLASS
619
YOU DO IT Creating a JFrame Ending an Application When a JFrame Closes Adding Components to a JFrame Adding Functionality to a JButton and a JTextField Distinguishing Event Sources Including JCheckBoxes in an Application
621 621 623 623 625 626 627
DON’T DO IT
630
KEY TERMS
631
CHAPTER SUMMARY
632
REVIEW QUESTIONS
634
EXERCISES
637
DEBUGGING EXERCISES
638
GAME ZONE
639
TOUGH QUESTIONS
640
UP FOR DISCUSSION
640
CHAPTER 14 ADVANCED GUI TOPICS
641
UNDERSTANDING THE CONTENT PANE
642
USING COLOR
647
LEARNING MORE ABOUT LAYOUT MANAGERS Using BorderLayout Using FlowLayout Using GridLayout
648 649 651 653 xv
CONTENTS
Using CardLayout Using Advanced Layout Managers
655 656
USING THE JPanel CLASS
657
CREATING JScrollPanes
664
A CLOSER LOOK AT EVENTS AND EVENT HANDLING An Event-Handling Example: KeyListener
666 669
USING AWTEvent CLASS METHODS Understanding x- and y-Coordinates
671 673
HANDLING MOUSE EVENTS
674
USING MENUS Using JCheckBoxMenuItem and JRadioButtonMenuItem Objects Using addSeparator() Using setMnemonic()
680 683 684 685
YOU DO IT Using BorderLayout Using Fewer than Five Components with the BorderLayout Manager Using FlowLayout Using GridLayout Using CardLayout Viewing All the Cards in CardLayout Using a Menu Bar and JPanels
686 686 687 688 689 690 690 691
DON’T DO IT
696
KEY TERMS
696
CHAPTER SUMMARY
698
REVIEW QUESTIONS
699
EXERCISES
702
DEBUGGING EXERCISES
703
GAME ZONE
704
TOUGH QUESTIONS
708
UP FOR DISCUSSION
708
CHAPTER 15 GRAPHICS
709
LEARNING ABOUT THE paint() AND repaint() METHODS Using the setLocation() Method
710 712
USING THE drawString() METHOD Using the setFont() and setColor() Methods Using Color
714 715 716
CREATING Graphics AND Graphics2D OBJECTS
717
xvi
CONTENTS
DRAWING LINES AND SHAPES Drawing Ovals Drawing Arcs Creating Shadowed Rectangles Creating Polygons Copying an Area
718 720 721 722 723 725
LEARNING MORE ABOUT FONTS AND METHODS YOU CAN USE WITH THEM Discovering Screen Statistics Using the Toolkit Class Discovering Font Statistics
726 728 729
DRAWING WITH JAVA 2D GRAPHICS Specifying the Rendering Attributes Setting a Drawing Stroke Creating Objects to Draw
731 731 733 734
YOU DO IT Using the drawString() Method Using Fonts and Colors Creating Your Own Graphics Object Examining Screen Coordinates Creating a Drawing Copying an Area Using FontMetrics Methods to Compare Fonts Using FontMetrics Methods to Place a Border Around a String Using Drawing Strokes Working with Shapes
736 736 737 738 739 740 741 742 745 746 748
DON’T DO IT
749
KEY TERMS
749
CHAPTER SUMMARY
751
REVIEW QUESTIONS
752
EXERCISES
755
DEBUGGING EXERCISES
758
GAME ZONE
758
TOUGH QUESTIONS
761
UP FOR DISCUSSION
761
CHAPTER 16 APPLETS, IMAGES, AND SOUND
763
INTRODUCING APPLETS Understanding the JApplet Class Running an Applet
764 765 765
WRITING AN HTML DOCUMENT TO HOST AN APPLET
766
CREATING A JApplet THAT CONTAINS AN init() METHOD
768
xvii
CONTENTS
WORKING WITH JApplet COMPONENTS
770
UNDERSTANDING THE JApplet LIFE CYCLE The init() Method The start() Method The stop() Method The destroy() Method
772 773 773 773 774
UNDERSTANDING MULTIMEDIA AND USING IMAGES Adding Images to JApplets Using ImageIcons
774 775 777
ADDING SOUND TO JApplets
780
YOU DO IT Creating an HTML Document to Host an Applet Creating and Running a JApplet Running a JApplet in Your Web Browser Creating a More Complicated JApplet Making the JApplet’s Button Respond to Events Understanding the Applet Life Cycle Displaying Images Playing Sounds
781 781 782 783 783 785 786 790 791
DON’T DO IT
793
KEY TERMS
793
CHAPTER SUMMARY
794
REVIEW QUESTIONS
795
EXERCISES
798
DEBUGGING EXERCISES
800
GAME ZONE
801
TOUGH QUESTIONS
805
UP FOR DISCUSSION
805
APPENDIX A WORKING WITH THE JAVA PLATFORM
807
APPENDIX B LEARNING ABOUT ASCII AND UNICODE
815
APPENDIX C FORMATTING OUTPUT
821
APPENDIX D GENERATING RANDOM NUMBERS
833
APPENDIX E JAVADOC
839
GLOSSARY
847
INDEX
867
xviii
PREFACE Java Programming, Fifth 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 quickly can 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. This book provides a solid background in good object-oriented programming techniques and introduces object-oriented terminology using clear, familiar language. The writing is nontechnical and emphasizes good programming practices. The 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. The explanations in this textbook are written clearly in straightforward sentences so that native and non-native English speakers alike can master the programming concepts. Complete, working code examples appear frequently in each chapter; these examples help the student make the transition from the theoretical to the practical. The code presented in each chapter is also provided on disk, so that students can easily run the programs and experiment with changes to them.
ORGANIZATION AND COVERAGE Java Programming, Fifth 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 and 8. Chapters 9, 10, and 11 thoroughly cover inheritance (the object-oriented concept that allows you to develop new objects quickly by adapting the features of existing ones) and exception handling (the object-oriented approach to handling errors). Both are important concepts in object-oriented design. Chapter 12 provides information on handling files so you can permanently store and retrieve program output. Chapters 13 and 14 introduce GUI Swing components—Java’s visually pleasing, user-friendly widgets—and their layout managers. Chapters 15 and 16 show you ways to provide interactive excitement using graphics, applets, images, and sound. In every chapter, Java Programming, Fifth Edition follows the text explanation with a “You Do It” section that contains step-by-step exercises to illustrate the concepts just learned, reinforcing the student’s understanding and allowing concepts to be better retained. Creating the programs in the step-by-step examples xix
PREFACE
also provides students with a successful experience in the language; finishing the examples provides them with models for their own creations. The student using Java Programming, Fifth Edition builds applications from the bottom up, rather than starting with existing objects. This facilitates a deeper understanding of the concepts used in objectoriented 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 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.
FEATURES Java Programming, Fifth Edition is a superior textbook because it also includes the following features:
» Objectives: Each chapter begins with a list of objectives so you know the topics that will be present» » NEW! »
» » NEW! »
»
NEW! »
ed in the chapter. In addition to providing a quick reference to topics covered, this feature provides a useful study aid. 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. Figures: Each chapter contains many figures. Code figures are most frequently 25 lines or less, illustrating one concept at a time. Frequently placed screen shots show exactly how program output appears. Callouts in more figures: Callouts have been added to many figures to help students focus on the points emphasized in the text. Some icons contain the words “Don’t Do It” to emphasize when an example illustrates a practice not to emulate. Color: The code figures in each chapter contain all Java keywords in brown. This helps students identify keywords more easily, distinguishing them from programmer-selected names. Files: The Student Disk holds more than 180 files that 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. Two Truths and a Lie: A new quiz reviews each chapter section, with answers provided. This quiz contains three statements from 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 mini-quizzes provide students with immediate feedback as they read, without “giving away” answers to the existing multiple-choice and programming problem questions. You Do It: In each chapter, step-by-step exercises help the student create multiple working programs that emphasize the logic a programmer uses in choosing statements to include. This section provides a means for students to achieve success on their own—even those in online or distance learning classes. 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. xx
PREFACE
» 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 mini-review of the major concepts in the chapter.
» Summaries: Following each chapter is a summary that recaps the programming concepts and tech» » »
» » » » »
»
niques covered in the chapter. This feature helps students 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. Exercises: Each chapter concludes with meaningful programming exercises that provide additional practice of the skills and concepts learned in the chapter. These exercises vary in difficulty and are designed to allow exploration of logical programming concepts. Game Zone: Each chapter provides one or more exercises in which the student creates 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. Tough Questions: Each chapter includes two or more fairly difficult, and often open-ended, questions that are typical of what an applicant might encounter in a technical job interview. Some questions involve coding; others might involve research. Up for Discussion: Each chapter concludes with a few thought-provoking questions concerning programming in general or Java in particular. The questions can be used to start classroom or online discussions, or to develop and encourage research, writing, and language skills. Glossary: This edition includes a glossary that contains definitions for all key terms in the book, presented in alphabetical order. Appendix on javadoc: This edition includes a new appendix on creating javadoc comments. Other pedagogical improvements: This edition introduces the following pedagogical improvements: » The Scanner class is introduced in Chapter 2 to facilitate user keyboard entry in programs. » Programming examples provide earlier and more consistent use of named constants. » Clearer distinction between troublesome concepts is provided—for example, argument vs. parameter and static vs. nonstatic. » The String chapter focuses on StringBuilder instead of StringBuffer because StringBuilder is more efficient. However, it is emphasized that the two classes are used in exactly the same way. » The GUI chapters have been completely rewritten and moved later in the book, which makes it easier for instructors who want to cover the concepts of inheritance and polymorphism first. Similarly, applet coverage has been removed from the GUI chapters, which makes it easier for instructors who want to cover GUI topics first. » Applets have been moved to the last chapter in the book, reflecting their diminished popularity as a business tool. Quality: Every program example in the book, as well as every exercise and game solution, was tested by the author and then tested again by a Quality Assurance team using Java Standard Edition (SE) 6, the most recent version available. (The external version number used by Sun Microsystems is 6.0; the internal version number is 1.6.0. For more information on the features of the JDK, visit http://java.sun.com.) xxi
NEW!
NEW! NEW! NEW!
PREFACE
» CD-ROM included with book: The CD that comes with this book includes the following items: » Sun Microsystems Java SE 6, the Java language, compiler, and runtime environment » The jGRASP integrated development environment for Java » Code files for all Java program examples contained in the text
TEACHING TOOLS The following supplemental materials are available when this book is used in a classroom setting. All of the teaching tools available with this book are provided to the instructor on a single CD.
» Electronic Instructor’s Manual: The Instructor’s Manual that accompanies this textbook includes
»
»
»
»
additional instructional material to assist in class preparation, including items such as Sample Syllabi, Chapter Outlines, Technical Notes, Lecture Notes, Quick Quizzes, Teaching Tips, Discussion Topics, and Key Terms. ExamView®: This textbook is accompanied by ExamView, a powerful testing software package that allows instructors to create and administer printed, computer (LAN-based), and Internetbased exams. ExamView includes hundreds of questions that correspond to the topics covered in this text, enabling students to generate detailed study guides that include page references for further review. The computer-based and Internet testing components allow students to take exams at their computers, and they save the instructor time by grading each exam automatically. PowerPoint Presentations: This book comes with Microsoft PowerPoint slides for each chapter. These are included as a teaching aid for classroom presentation, to make available to students on the network for chapter review, or to be printed for classroom distribution. Instructors can add their own slides for additional topics they introduce to the class. Solution Files: Solutions to “You Do It” exercises and all end-of-chapter exercises are provided on the Instructor Resources CD and on the Course Technology Web site at www.course.com. The solutions are password protected. Annotated solutions are provided for 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. Distance Learning: Course Technology is proud to present online test banks in WebCT and Blackboard to provide the most complete and dynamic learning experience possible. Instructors are encouraged to make the most of the course, both online and offline. For more information on how to access the online test bank, contact your local Course Technology sales representative.
xxii
PREFACE
ACKNOWLEDGEMENTS I would like to thank all of the people who helped to make this book a reality, especially Dan Seiter, Development Editor. Dan’s suggestions and attention to detail made this a superior book, and his sense of humor made writing it practically painless. Thanks also to Tricia Coia, Managing Editor; and Heather Furrow, Content Project Manager. I am lucky to work with Tricia and Heather; they are dedicated to producing quality instructional materials. Thanks to Serge Palladino, John Freitas, and Chris Scriver of the Quality Assurance Department. Thank you to Dick Grant of Seminole Community College, Sanford, Florida. He provided important technical and pedagogical suggestions based on his classroom use of this book. He possesses the rare combination of excellent teacher and programmer, and he made this book more accurate and more useful to students. I am also grateful to the many other reviewers who provided comments and encouragement during this book’s development, including Karlyn Barilovits, Kaplan University; Kay Chen, Bucks County Community College; Roman Erenshteyn, Goldey-Beacom College; Jeff Hedrington, University of Phoenix-Online; and Aaron Jagers, Louisiana Technical College. Thanks, too, to my husband, Geoff, who supports me every step of the way. Finally, this book is dedicated to our lifelong friends, George and Mary Profeta. Joyce Farrell
xxiii
This page intentionally left blank
READ THIS BEFORE 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 the Course Technology Web site by connecting to www.course.com and then searching for this book title. 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 6, available from http://java.sun.com. (Although almost all of the examples in this
» »
book will work with earlier versions of Java, this book was created using Java 6.) The book clearly points out the few cases when an example does 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, such as Internet Explorer. Hardware: To install Java on your computer, the Java Web site suggests at least a Pentium III 500-MHz system with 512 MB of memory and at least 850 MB of disk space. A Pentium IV 1.4-GHz system with 1 GB of memory and 1 GB of disk space is recommended. Data Files: You cannot complete all the chapters and projects in this book using your own computer unless you have the data files. You can get the data files from your instructor, or you can obtain the data files electronically from the Course Technology Web site by connecting to www.course.com and then searching for this book title.
The following material is provided on the CD that comes with this book:
» Sun Microsystems Java SE 6, the Java language, compiler, and runtime environment » Sun Microsystems Java Application Programming Interface (API) Specification, official documentation for the Java programming language
» The jGRASP integrated development environment for Java » Code files for all Java program examples contained in the text
VISIT OUR WORLD WIDE WEB SITE
Additional materials designed especially for this book might be available for your course. Periodically search www.course.com for more details and updates.
xxv
This page intentionally left blank
C H A P T E R O N E
1 CREATING YOUR FIRST JAVA CLASSES
»
In this chapter, you will: Learn about programming Be introduced to object-oriented programming concepts Learn about Java Analyze a Java application that uses console output Add comments to a Java class Save, compile, run, and modify a Java application Create a Java application using GUI output Correct errors and find help
1
CREATING YOUR FIRST JAVA CLASSES
JAVA ON THE JOB, SCENE 1 As you read your e-mail, your heart sinks. There’s no denying the message: “Please see me in my office as soon as you are free—Lynn Greenbrier.” Lynn is the head of programming for Event Handlers Incorporated, and you have worked for her as an intern for only two weeks. Event Handlers manages the details of private and corporate parties; every client has different needs, and the events are interesting and exciting. “Did I do something wrong?” you ask as you enter her office. “Are you going to fire me?” Lynn stands to greet you and says, “Please wipe that worried look off your face. I want to see if you are interested in a new challenge. Our Programming Department is going to create several new programs in the next few months. We’ve decided that Java is the way to go. It’s object-oriented, platform independent, and perfect for applications on the Web, which is where we want to expand our marketing efforts.” “I’m not sure what ‘object-oriented’ and ‘platform independent’ mean,” you say, “but I’ve always been interested in computers, and I’d love to learn more about programming.” “Based on your aptitude tests, you’re perfect for programming,” Lynn says. “Let’s get started now. I’ll describe the basics to you.”
LEARNING ABOUT PROGRAMMING A computer program is a set of instructions that you write to tell a computer what to do. Computers are constructed from circuitry that consists of small on/off switches, so you could create a computer program by writing something along the following lines:
»NOTE
Programmers often say that machine language consists of 1s and 0s. What they mean is that you can use 1s and 0s to represent on and off switches.
»NOTE
In every high-level programming language, the names of memory locations cannot include spaces.
first switch—on second switch—off third switch—off fourth switch—on
Your program could go on and on, for several thousand switches. A program written in this style is written in machine language, which is the most basic circuitry-level language. For this reason, machine language is a low-level programming language, or one that corresponds closely to a computer processor’s circuitry. The problems with this approach lie in keeping track of the many switches involved in programming any worthwhile task and in discovering the errant switch or switches if the program does not operate as expected. In addition, the number and location of switches vary from computer to computer, which means that you would need to customize a machine language program for every type of machine on which you want the program to run. 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 on and off switches that perform these tasks. High-level languages also allow you to assign
2
C H A P T E R O N E
intuitive names to areas of computer memory, such as “hoursWorked” or “rateOfPay,” rather than having to remember the memory locations (switch numbers) of those values. Java is a high-level programming language. Each high-level language has its own syntax, or rules of the language. 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 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 rules 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. 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 code. A compiler translates an entire program before carrying out the statement, or executing it, whereas an interpreter translates one program statement at a time, executing a statement as soon as it is translated. 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. Subsequently, the programmer can correct the error and attempt another translation by compiling or interpreting the program again. Locating and repairing all syntax errors is part of the process of debugging a program—freeing the program of all errors. 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 are easier to develop and debug. Java uses the best of both technologies— a compiler to translate your programming statements and an interpreter to read the compiled code line by line at run time. In addition to learning the correct syntax for a particular language, a programmer also must understand computer programming logic. The logic behind any program involves executing the various statements and procedures in the correct order to produce the desired results. Although you begin to debug a program by correcting all the syntax errors, it is not fully debugged until you have also fixed all logical errors. For example, you would not write statements to tell the computer program to process data until the data had been properly read into the program. Similarly, you might be able to use a computer language’s syntax correctly, but fail to end up with a logically constructed, workable program. Examples of logical errors include multiplying two values when you meant to divide them, or producing output prior to obtaining the appropriate input. Tools that will help you visualize and understand logic are presented in Chapter 5.
»NOTE
Programmers call some logical errors semantic errors. For example, if you misspell a programminglanguage word, you commit a syntax error, but if you use a correct word in the wrong context, you commit a semantic error.
3
»NOTE
You will learn more about debugging Java programs later in this chapter.
CREATING YOUR FIRST JAVA CLASSES
»TWO TRUTHS AND A LIE: LEARNING ABOUT PROGRAMMING 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 compiler executes each program statement as soon as it is translated, whereas an interpreter translates all of a program’s statements before executing any. 3. A syntax error occurs when you misuse a language; locating and repairing all syntax errors is part of the process of debugging a program. The false statement is #2. A compiler translates an entire program before carrying out any statements, whereas an interpreter translates one program statement at a time, executing a statement as soon as it is translated.
INTRODUCING OBJECT-ORIENTED PROGRAMMING CONCEPTS Two popular approaches to writing computer programs are procedural programming and object-oriented programming.
PROCEDURAL PROGRAMMING
»NOTE
Procedures are also called modules, methods, functions, and subroutines. Users of different programming languages tend to use different terms. Java programmers most frequently use the term “method.”
Procedural programming is a style of programming in which sets of operations are executed one after another in sequence. It involves using your knowledge of a programming language to 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 written for a company 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—the value might be read from an input device, the value might be multiplied by another variable representing hours worked, and the value might 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. A single procedural program often contains hundreds of variables and thousands of procedure calls.
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, creating objects from those classes, and creating applications, which are stand-alone executable programs that use those objects. After being created, classes can 4
C H A P T E R O N E
be reused over and over again to develop new programs. Thinking in an object-oriented manner involves envisioning program components as objects that belong to classes and are similar to concrete objects in the real world; then, you can manipulate the objects and have them interrelate with each other to achieve a desired result. If you’ve ever used a computer that uses a command-line operating system (such as DOS), and if you’ve also used a graphical user interface (GUI), such as Windows, then you are familiar with one of the differences between procedural and object-oriented programs. If you want to move several files from a floppy disk to a hard disk, you can type a command at a prompt or command line, or you can use a mouse in a graphical environment to accomplish the task. The difference lies in whether you issue a series of commands, in sequence, to move the three files, or you drag icons representing the files from one screen location to another, much as you would physically move paper files from one file cabinet to another in your office. You can move the same three files using either operating system, but the GUI system allows you to manipulate the files like their real-world paper counterparts. In other words, the GUI system allows you to treat files as objects.
»NOTE
Do not assume that all object-oriented programs are written to use GUI objects—they are not. However, the difference between command-line and GUI operating systems provides an analogy that helps you envision object-oriented concepts.
Understanding how object-oriented programming differs from traditional procedural programming requires understanding three basic concepts:
» Encapsulation as it applies to classes as objects » Inheritance » Polymorphism You can remember these three concepts by remembering the acronym PIE, as shown in Figure 1-1.
Polymorphism
Inheritance
Encapsulation
Figure 1-1 The three major features of object-oriented programming
UNDERSTANDING OBJECTS, CLASSES, AND ENCAPSULATION
Objects, both in the real world and in object-oriented programming, are made up of attributes and methods. Attributes are the characteristics that define an object; the values contained in attributes differentiate objects of the same class from one another. For example, some of your automobile’s attributes are its make, model, year, and purchase price. Other attributes include whether the automobile is currently running, its gear, its speed, and whether it is dirty. All automobiles possess the same attributes, but not, of course, the same values for those attributes. Similarly, your dog has the attributes of its breed, name, age, and 5
»NOTE
In object-oriented programming grammar, an object is equivalent to a noun and an attribute is an adjective. Methods are similar to verbs.
CREATING YOUR FIRST JAVA CLASSES
»NOTE
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.
»NOTE
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, so does a class exist before any objects are instantiated from it.
whether his shots are current. The values of the attributes of an object are also referred to as the object’s state. In object-oriented terminology, a class is a term that describes a group or collection of objects with common properties. A class definition describes what attributes its objects will have and what those objects will be able to do. An instance of a class is an existing object of a class. Therefore, your red Chevrolet Automobile with the dent is an instance of the class that is made up of all automobiles, and your Akita Dog named Ginger is an instance of the class that is made up of all dogs. Thinking of items as instances of a class allows you to apply your general knowledge of the class to individual members of the class. A particular instance of a class takes its attributes from the general category. 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. You might not know the current state of your friend’s Automobile— for example, its current speed, or the status of her Dog’s shots—but you do know what attributes exist for the Automobile and Dog classes. Similarly, in a GUI operating environment, you expect each component to have specific, consistent attributes, such as a button being clickable or a window being closable, because each component gains these attributes as a member of the general class of GUI components. Figure 1-2 shows the relationship of some Dog objects to the Dog class.
»NOTE
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 Breed
Ginger 6 Akita Up to date
Bowser 2 Retriever Up to date
Shot status
Figure 1-2 A class definition and some objects created from it
6
Roxy 1 Beagle Up to date
C H A P T E R O N E
Besides attributes, objects can use methods to accomplish tasks. A method is a self-contained block of program code, similar to a procedure. An Automobile, for example, can move forward and backward. It also can be filled with gasoline or be washed. Some methods can ascertain certain attributes, such as the current speed of an Automobile and the status of its gas tank. Similarly, a Dog can walk or run, eat food, and get a bath, and there are methods to determine how hungry the Dog is or what its name is. GUI operating system components can be maximized, minimized, and dragged. Like procedural programs, object-oriented programs have variables (attributes) and procedures (methods), but the attributes and methods are encapsulated into objects that are then used much like real-world objects. Encapsulation refers to the hiding of data and methods within an object. Encapsulation provides the security that keeps data and methods safe from inadvertent changes. Programmers sometimes refer to encapsulation as using a “black box,” or a device that you can use without regard to the internal mechanisms. A programmer can access and use the methods and data contained in the black box but cannot change them. If an object’s methods are well written, the user is 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 objects used in object-oriented programs.
UNDERSTANDING INHERITANCE AND POLYMORPHISM
An important feature of object-oriented programs 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 mechanism for and 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 other Automobile systems work. 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, 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
7
»NOTE
Chapters 9 and 10 provide more information about inheritance and polymorphism, and how they are implemented in Java.
CREATING YOUR FIRST JAVA CLASSES
»NOTE
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.
example, in English the verb “run” means different things if you use it with “a footrace,” a “business,” or “a computer.” You understand the meaning of “run” based on the other words used with it. Object-oriented programs are written so that the most useful verbs, such as “print” or “save,” work differently based on their context. 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.
TWO TRUTHS AND A LIE: INTRODUCING 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. The false statement is #3. Inheritance 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.
LEARNING ABOUT JAVA
»NOTE
When programmers call the JVM “hypothetical,” they don’t mean it doesn’t exist. Instead, they mean it is not a physical entity created from hardware, but is composed only of software.
»NOTE
Interactive applications are those in which a user communicates with a program by using an input device such as the keyboard or a mouse.
Java was developed by Sun Microsystems as an object-oriented language for general-purpose business applications and for interactive, Web-based Internet applications. Some of the advantages that have made Java so popular in recent years are its security features and the fact that it is architecturally neutral, which means that you can use Java to write a program that will run on any platform (operating system). Java can be run on a wide variety of computers because it does not execute instructions on a computer directly. Instead, Java runs on a hypothetical computer known as the Java Virtual Machine (JVM). Figure 1-3 shows the Java environment. Programming statements written in a high-level programming language are called source code. When you write a Java program, you first construct the source code using a text editor such as Notepad. 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, the Java program 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 8
C H A P T E R O N E
(a Windows version, Macintosh version, UNIX version, Linux version, and so on) so all users can run the program. With Java, one program version will run on all these platforms.
Java Source Code Source code is stored on a disk in a file with a name ending in .java Java Compiler
Java Interpreter
Compiler creates bytecodes that are stored on a disk in a file with a name ending in .class
Computer Operating System
JVM (named java.exe) performs security checks and translates bytecodes to machine language, which executes
Java Virtual Machine
Figure 1-3 The Java environment
Java is also 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.
JAVA PROGRAM TYPES
You can write two kinds of programs using Java. Programs that are embedded in a Web page are called Java applets. Stand-alone programs are called Java applications. Java applications can be further subdivided into console applications, which support character output to a computer screen in a DOS window, for example, and windowed applications, which create a GUI with elements such as menus, toolbars, and dialog boxes. Console applications are the easiest applications to create; you start using them in the next section.
»TWO TRUTHS AND A LIE: LEARNING ABOUT JAVA 1. Java was developed to be architecturally neutral, which means that anyone can 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. The false statement is #1. Java was developed to be architecturally neutral, which means that you can use Java to write a program that will run on any platform.
9
»NOTE
“Write once, run anywhere” (WORA) is a slogan developed by Sun Microsystems to describe the ability of one Java program version to work correctly on multiple platforms.
CREATING YOUR FIRST JAVA CLASSES
ANALYZING A JAVA APPLICATION THAT USES CONSOLE OUTPUT
»NOTE
When you see program code in figures in this book, Java keywords as well as true, false, and null will be brown and all other program elements will be black. A complete list of Java keywords is shown later in this chapter.
»NOTE
The code for every complete program shown in this book is available on your Student Disk so that you can execute the programs on your own computer.
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 print “First Java application” on the screen.
»NOTE
Some programmers prefer to reserve the term “print” for output that is produced on paper; they use “display” when referring to screen output. Because Java uses the print() and println() methods to display output on the screen, this book will use the term “print” to mean screen output.
public class First { public static void main(String[] args) { System.out.println("First Java application"); } } Figure 1-4 The First class
UNDERSTANDING THE STATEMENT THAT PRINTS THE OUTPUT
The statement System.out.println("First Java application"); does the actual work in this program. Like all Java statements, this one ends with a semicolon.
»NOTE
Most Java programming statements can be written on as many lines as you choose, as long as you place line breaks between words. However, a literal string cannot be broken and placed on multiple lines.
The text “First Java application” is a literal string of characters; that is, it is a series of characters that will appear in output exactly as entered. Any literal string in Java is written between double quotation marks. Figure 1-5 labels this string and the other parts of the statement. System is a class.
"First Java application" is a literal string that is the argument to the println() method.
System. out. println ("First Java application"); Dots separate classes, objects, and methods.
»NOTE
A statement does not necessarily end at the end of a line; a statement might run across several lines until it ends with a semicolon.
out is an object. It belongs to the System class.
println() is a method. Method names are always followed by parentheses.
Every Java statement ends with a semicolon.
Figure 1-5 Anatomy of a Java statement
»
NOTE The dots (periods) in System.out.println are used to separate the names of the class, object, and method. You will use this same class-dot-object-dot-method format repeatedly in your Java programs.
10
C H A P T E R O N E
The string “First Java application” appears within parentheses because the string is an argument to a method, and arguments to methods always appear within parentheses. Arguments are pieces of information that are sent into, or passed to, a method, usually because the method requires the information to perform its task or carry out its purpose. As an example, consider placing a catalog order with a company that sells sporting goods. Processing a catalog order is a method that consists of a set of standard procedures— recording the order, checking the availability of the item, pulling the item from the warehouse, and so on. Each catalog order also requires a set of data items, such as which item number you are ordering and the quantity of the item desired; these data items can be considered the order’s argument. If you order two of item 5432 from a catalog, you expect different results than if you order 1,000 of item 9008. Likewise, if you pass the argument “Happy Holidays” to a Java method, you expect different results than if you pass the argument “First Java application”.
»NOTE
The println() method requires only one argument. Later in this chapter, you will learn about a method named showMessageDialog() that requires two arguments. Other methods require more.
Within the statement System.out.println("First Java application");, the method to which you are passing "First Java application" is named println(). The println()method prints a line of output on the screen and positions the insertion point on the next line, so that any subsequent output appears on a new line. Within the statement System.out.println("First Java application");, out is an object. The out object represents the screen. Several methods, including println(), are available with the out object. Of course, not all objects have a println()method (for instance, you can’t print to a keyboard, to your Automobile, or to your Dog), but the creators of Java assume you frequently want to display output on a screen. Therefore, the out object was created and endowed with the method named println().
»NOTE
When you call a method, you always use parentheses following the method name. In this book you will learn about many methods that require arguments between their parentheses, and many others for which you leave the parentheses empty.
»NOTE
You can use the println()
method with no arguments when you want to print a blank line.
»NOTE
Method names usually are referenced followed by their parentheses, as in println(), so that you can distinguish method names from variable names.
»NOTE
The print()method is very similar to the println()method. With println(), after the message prints, the insertion point appears on the following line. With print(), the insertion point does not advance to a new line; it remains on the same line as the output.
Within the statement System.out.println("First Java application");, System is a class. Therefore, System defines the attributes of a collection of similar “System” objects, just as the Dog class defines the attributes of a collection of similar Dog objects. One of the System objects is out. (You can probably guess that another object is in and that it represents an input device.) The out object refers to the standard output device for a system, normally the monitor. The statement that prints the string “First Java application” cannot stand alone; it is embedded within a class, as shown in Figure 1-4.
UNDERSTANDING THE First CLASS
Everything that you use within a Java program must be part of a class. When you write public class First, you are defining a class named First. You can define 11
»NOTE
Java is case sensitive; the class named System is a completely different class from one named system, SYSTEM, or even sYsTeM.
CREATING YOUR FIRST JAVA CLASSES
a Java class using any name or identifier you need, as long as it meets the following requirements:
» A class name must begin with a letter of the English alphabet, a non-English letter (such as α or π), an underscore, or a dollar sign. A class name cannot begin with a digit.
»NOTE
Java is based on Unicode, which is an international system of character representation. The term “letter” indicates Englishlanguage letters as well as characters from Arabic, Greek, and other alphabets. You can learn more about Unicode in Appendix B.
» A class name can contain only letters, digits, underscores, or dollar signs. » A class name cannot be a Java reserved keyword, such as public or class. (See Table 1-1 for a list of reserved keywords.)
» A class name cannot be one of the following values: true, false, or null. These are not keywords (they are primitive values), but they are reserved and cannot be used. abstract
double
int
strictfp
assert
else
interface
super
boolean
enum
long
switch
break byte case
extends final finally
native new package
synchronized this throw
catch char
float for
private protected
throws transient
class
goto
public
try
const continue default do
if implements import instanceof
return short static
void volatile while
Table 1-1 Java reserved keywords
»NOTE
You should follow established conventions for Java so your programs will be easy for other programmers to interpret and follow. This book uses established Java programming conventions.
»NOTE
Using an uppercase letter to begin an identifier and to start each new word in an identifier is known as Pascal casing.
It is a Java standard, although not a requirement, to begin class identifiers with an uppercase letter and employ other uppercase letters as needed to improve readability. Table 1-2 lists some valid and conventional class names that you could use when writing programs in Java. Table 1-3 provides some examples of class names that could be used in Java (if you use these class names, the class will compile) but that are unconventional and not recommended. Table 1-4 provides some class name examples that are illegal. Class Name Employee UnderGradStudent
Description Begins with an uppercase letter Begins with an uppercase letter, contains no spaces, and
InventoryItem
emphasizes each new word with an initial uppercase letter Begins with an uppercase letter, contains no spaces, and
Budget2011
emphasizes the second word with an initial uppercase letter Begins with an uppercase letter and contains no spaces
Table 1-2 Some valid class names in Java
12
C H A P T E R O N E
Class Name
Description
Undergradstudent
New words are not indicated with initial uppercase letters; difficult to read
Inventory_Item
Underscore is not commonly used to indicate new words
BUDGET2011
Using all uppercase letters is not common
Table 1-3 Legal but unconventional and nonrecommended class names in Java
Class Name
Description
An employee
Space character is illegal
Inventory Item
Space character is illegal
class
class is a reserved word
2011Budget
Class names cannot begin with a digit
phone#
# symbol is illegal
Table 1-4 Some illegal class names in Java
In Figure 1-4 (and again in Figure 1-6), the line public class First is the class header; it contains the keyword class, which identifies First as a class. The reserved word public is an access modifier. An access modifier defines the circumstances under which a class can be accessed and the other classes that have the right to use a class. Public access is the most liberal type of access; you will learn about public and other types of access in Chapter 3.
public is an access modifier. Class header
Class body
The keyword class identifies First as a class. First is the name of the class
public class First or the identifier for the class. { public static void main(String[] args) { System.out.println("First Java application"); } }
Figure 1-6 The parts of a typical class
After the class header, you enclose the contents of a class within curly braces ({ and }). A class can contain any number of data items and methods. In Figure 1-4 (and again in Figure 1-6), the class First contains only one method within its curly braces. The name of the method is main(), and the main()method, like the println()method, contains its own set of parentheses. 13
CREATING YOUR FIRST JAVA CLASSES
»NOTE
The First class contains one method named main(). The main() method does not contain any other methods, but it does contain a method call to the println() method.
The main() method in the First class contains only one statement—the statement that uses the println() method.
»NOTE
In general, whitespace is optional in Java. Whitespace is any combination of nonprinting characters; for example, spaces, tabs, and carriage returns (blank lines). However, you cannot use whitespace within any identifier or keyword. You can insert whitespace between words or lines in your program code by typing spaces, tabs, or blank lines because the compiler ignores these extra spaces. You use whitespace to organize your program code and make it easier to read.
For every opening curly brace ( { ) in a Java program, there must be a corresponding closing curly brace ( } ). The placement of the opening and closing curly braces is not important to the compiler. For example, the following method is executed in exactly the same way as the one shown in Figure 1-4. The only difference is that the layout of the method is different—the line breaks occur in different locations. public static void main(String[] args) { System.out.println("First Java application"); }
»NOTE
The indent style in which curly braces are aligned and each occupies its own line is called the Allman style, named for Eric Allman, a programmer who popularized the style. The indent style in which the opening brace follows the header line is known as the K & R style, named for Kernighan and Ritchie, who wrote the first book on the C programming language.
Many Java programmers prefer to write code using the style shown in this example, with the opening curly brace for the method at the end of the method header line. This format saves a vertical line of type in the saved source code file. Others feel that code in which you vertically align each pair of opening and closing curly braces (as shown in Figure 1-4) is easier to read. Either style is acceptable, and both produce workable Java programs. When you write your own code, you should develop a consistent style. When you get a job as a Java programmer, your organization most likely will have a preferred style.
UNDERSTANDING THE main() METHOD
The method header for the main() method is quite complex. The meaning and purpose of each of the terms used in the method header will become clearer as you complete this textbook; a brief explanation will suffice for now. In the method header public static void main(String[] args), the word public is an access modifier, just as it is when you use it to define the First class. In Java, the reserved keyword static means that a method is accessible and usable even though no objects of the class exist. Of course, other classes eventually might have their own, different main() methods. (Figure 1-7 shows the parts of the main() method.)
14
C H A P T E R O N E
public is an access modifier.
static means this method works without instantiating an object of the class.
args is the identifier of the array of Strings that is the argument to this method.
void is the method’s return
Method header Method body
public class First type; it returns nothing. { public static void main(String[] args) { System.out.println("First Java application"); } } The square brackets mean the argument to String is a class. Any arguments to this method must be String objects.
this method is an array of Strings . Chapters 7 and 8 provide more information about Strings and arrays.
Figure 1-7 The parts of a typical main() method
In English, the word “void” means empty. When the keyword void is used in the main() method header, it does not indicate that the main() method is empty, but rather that the main() method does not return any value when it is called. This doesn’t mean that main() doesn’t produce output—in fact, the method in Figure 1-4 (and in Figure 1-7) does. It only means that the main() method does not send any value back to any other method that might use it. You will learn more about return values in Chapter 3. Not all classes have a main() method; in fact, many do not. All Java applications, however, must include a class containing a public method named main(), and most Java applications have additional classes and methods. When you execute a Java application, the JVM always executes the main() method first. In the method header public static void main(String[] args), the contents between the parentheses, (String[] args), represent the type of argument that can be passed to the main() method, just as the string "First Java application" is an argument passed to the println() method. String is a Java class that can be used to hold character strings. The identifier args is used to hold any String objects that might be sent to the main() method. The main() method could do something with those arguments, such as print them, but in Figure 1-4, the main() method does not actually use the args identifier. Nevertheless, you must place an identifier within the main() method’s parentheses. The identifier does not need to be named args—it could be any legal Java identifier—but the name args is traditional.
»
NOTE You won’t pass any arguments to the main() method in this book, but when you run a program, you could. Even though you pass no arguments, the main() method must contain String[] and a legal identifier (such as args) within its parentheses.
15
»NOTE
When you refer to the String class in the main() method header, the square brackets indicate an array of String objects. You will learn more about the String class and arrays in Chapters 7 and 8.
CREATING YOUR FIRST JAVA CLASSES
The simple application shown in Figure 1-4 has many pieces to remember. However, for now you can use the Java code shown in Figure 1-8 as a shell, in which you replace AnyClassName with a class name you choose and the line /******/ with any statements that you want to execute.
public class AnyClassName { public static void main(String[] args) { /******/ } } Figure 1-8 Shell code
TWO TRUTHS AND A LIE: ANALYZING A JAVA APPLICATION »THAT USES CONSOLE OUTPUT 1. In the method header public static void main(String[] args), the word public is an access modifier. 2. In the method header public static void main(String[] args), the word static means that a method is accessible and usable, even though no objects of the class exist. 3. In the method header public static void main(String[] args), the word void means that the main() method is an empty method. The false statement is #3. In the method header public static void main(String[] args), the word void means that the main() method does not return any value when it is called.
ADDING COMMENTS TO A JAVA CLASS
»NOTE
As you work through this book, add comments as the first three lines of every file. The comments should contain the class name and purpose, your name, and the date. Your instructor might ask you to include additional comments.
As you can see, even the simplest Java class requires several lines of code and contains somewhat perplexing syntax. Large applications that perform many tasks include much more code, and as you write larger applications it becomes increasingly difficult to remember why you included steps or how you intended to use particular variables. Documenting your program code helps you remember why you wrote lines of code the way you did. Program comments are nonexecuting statements that you add to a program for the purpose of documentation. Programmers use comments to leave notes for themselves and for others who might read their programs in the future. At the very least, your Java class files should include comments indicating the author, the date, and the class’s name or function. The best practice dictates that you also include a brief comment to describe the purpose of each method you create within a class. Comments can also be useful when you are developing an application. If a program is not performing as expected, you can comment out various statements and subsequently run the program to observe the effect. When you comment out a statement, you turn it into a comment so the compiler does not translate and the JVM does not execute its command. This can help you pinpoint the location of errant statements in malfunctioning programs.
16
C H A P T E R O N E
There are three types of comments in Java:
» Line comments start with two forward slashes (//) and continue to the end of the cur»
»
rent line. A line comment can appear on a line by itself or at the end (and to the right) of a line following executable code. Line comments do not require an ending symbol. Block comments start with a forward slash and an asterisk (/*) and end with an asterisk and a forward slash (*/). A block comment can appear on a line by itself, on a line before executable code, or on a line after executable code. Block comments can also extend across as many lines as needed. Javadoc comments are a special case of block comments. They begin with a forward slash and two asterisks (/**) and end with an asterisk and a forward slash (*/). You can use javadoc comments to generate documentation with a program named javadoc. Appendix E teaches you how to create javadoc comments.
Figure 1-9 shows how comments are used in code. In this example, the only statement that executes is the System.out.println("Hello"); statement; everything else (all the shaded parts) is a comment.
// Demonstrating comments /* This shows that these comments don't matter */ System.out.println("Hello"); // This line executes // up to where the comment started /* Everything but the println() is a comment */ Figure 1-9 A program segment containing several comments
»TWO TRUTHS AND A LIE: ADDING COMMENTS TO A JAVA CLASS 1. Line comments start with two forward slashes (//) and end with two backslashes (//); they can extend across as many lines as needed. 2. Block comments start with a forward slash and an asterisk (/*) and end with an asterisk and a forward slash (*/); they can extend across as many lines as needed. 3. Javadoc comments begin with a forward slash and two asterisks (/**) and end with an asterisk and a forward slash (*/); they are used to generate documentation with a program named javadoc. The false statement is #1. Line comments start with two forward slashes (//) and continue to the end of the current line; they do not require an ending symbol.
17
»NOTE
The forward slash (/) and the backslash (\) characters often are confused, but they are two distinct characters. You cannot use them interchangeably.
»NOTE
The Java Development Kit (JDK) includes the javadoc tool, which you can use when writing programs in Java. The tool produces HTML pages that describe classes and their contents.
CREATING YOUR FIRST JAVA CLASSES
SAVING, COMPILING, RUNNING, AND MODIFYING A JAVA APPLICATION SAVING A JAVA CLASS
»NOTE
Appendix A contains important information on saving, compiling, and running a Java application.
When you write a Java class, you must save it using some storage medium; for example, a disk, CD, or USB device. In Java, if a class is public (that is, if you use the public access modifier before the class name), you must save the class in a file with exactly the same name and a .java extension. For example, the First class must be stored in a file named First.java. The class name and filename must match exactly, including the use of uppercase and lowercase characters. If the extension is not .java, the Java compiler does not recognize the file as containing a Java class.
COMPILING A JAVA CLASS
After you write and save an application, two steps must occur before you can view the application’s output. 1. You must compile the class you wrote (called the source code) into bytecode. 2. You must use the Java interpreter to translate the bytecode into executable statements. To compile your source code from the command line, your prompt should show the folder or directory where your program file is stored. Then, you type javac followed by the name of the file that contains the source code. For example, to compile a file named First.java, you type the following and then press Enter: javac First.java
There will be one of three outcomes:
» You receive a message such as 'javac'
is not recognized as an internal or external command, operable program or batch file.
» You receive one or more program language error messages. » You receive no messages, which means that the application compiled successfully.
»NOTE
When compiling, if the source code file is not in the current path, you can type a full path with the filename.
For example: javac c:\java\MyClasses\Chapter.01\First.java
In a DOS environment, you can change directories using the cd command. For example, to change from the current directory to a subdirectory named MyClasses, you type cd MyClasses and press Enter. Within any directory, you can back up to the root directory by typing cd\ and pressing Enter.
If you receive an error message that the command is not recognized, it might mean one of the following:
18
C H A P T E R O N E
» You misspelled the command javac. » You misspelled the filename. » You are not within the correct subfolder or subdirectory on your command line. » Java was not installed properly. (See Appendix A for information on installation.) If you receive a programming language error message, there are one or more syntax errors in the source code. Recall that a syntax error is a programming error that occurs when you introduce typing errors into your program or use the programming language incorrectly. For example, if your class name is first (with a lowercase “f”) in the source code but you saved the file as First.java (with an uppercase “F”), when you compile the application you’ll receive an error message, such as class first is public, should be declared in a file named first.java because “first” and “First” are not the same in a case-sensitive language. If this error occurs, you must reopen the text file that contains the source code and make the necessary corrections.
»NOTE
Appendix A contains information on troubleshooting, including how to change filenames in a Windows environment.
If you receive no error messages after compiling the code in a file named First.java, the application compiled successfully, and a file named First.class is created and saved in the same folder as the application text file. After a successful compile, you can run the class file on any computer that has a Java language interpreter.
RUNNING A JAVA APPLICATION
To run the First application from the command line, you type the following: java First
Figure 1-10 shows the application’s output in the command window. In this example, you can see that the First class is stored in a folder named Java on the C drive.
Figure 1-10 Output of the First application
»NOTE
The procedure to confirm the storage location of your First.java class varies depending on your operating system. In a Windows operating system, for example, you can open Windows Explorer, locate the icon representing the storage device you are using, find the folder in which you have saved the file, and expand the folder. You should see the First.java file.
MODIFYING A JAVA CLASS
After viewing the application output, you might decide to modify the class to get a different result. For example, you might decide to change the First application’s output from First Java application to the following: My new and improved Java application
19
»NOTE
Once in a while, when you make a change to a Java class and then recompile and execute it, the old version still runs. The simplest solution is to delete the .class file and compile again. Programmers call this creating a clean build.
CREATING YOUR FIRST JAVA CLASSES
To produce the new output, first you must modify the text file that contains the existing class. You need to change the literal string that currently prints, and then add an additional text string. Figure 1-11 shows the class that changes the output.
public class First { public static void main(String[] args) { System.out.println("My new and improved"); System.out.println("Java application"); } } Figure 1-11 First class containing modified output from original version
The changes to the First class include the addition of the statement System.out.println ("My new and improved"); and the removal of the word “First” from the string in the other println() statement. However, if you make changes to the file as shown in Figure 1-11, save the file, and execute the program by typing java First at the command line, you will not see the new output—you will see the old output without the added line. Even though you save a text file containing the modified source code for a class, it is the compiled class in the already-compiled class file that executes. After you save the file named First.java, the old compiled version of the class with the same name is still stored on your computer. Before the new source code will execute, you must do the following: 1. Save the file with the changes (using the same filename). 2. Compile the class with the javac command. (Actually, you are recompiling the class.) 3. Interpret the class bytecode and execute the class using the java command. Figure 1-12 shows the new output.
Figure 1-12 Execution of modified First class
»NOTE
When you complete these steps, the original version of the compiled file with the .class extension is replaced, and the new application executes. The original version no longer exists. When you modify a class, you must decide whether you want to retain the original version. If you do, you must give the new version a new class and filename.
20
C H A P T E R O N E
TWO TRUTHS AND A LIE: SAVING, COMPILING, RUNNING, »AND MODIFYING A JAVA APPLICATION 1. In Java, if a class is public, you must save the class in a file with exactly the same name and a .java extension. 2. To compile a file named MyProgram.java, you type java MyProgram, but to execute the program you type java MyProgram.java. 3. A syntax error is a programming error that occurs when you introduce typing errors into your program or use the programming language incorrectly; a program will not compile with syntax errors. The false statement is #2. To compile a file named MyProgram.java, you type javac MyProgram.java, but to execute the program you type java MyProgram.
CREATING A JAVA APPLICATION USING GUI OUTPUT Besides allowing you to use the System class to produce command window output, Java provides built-in classes that produce GUI output. For example, Java contains a class named JOptionPane that allows you to produce dialog boxes. A dialog box is a GUI object resembling a window in which you can place messages you want to display. Figure 1-13 shows a class named FirstDialog. The FirstDialog class contains many elements that are familiar to you; only the two shaded lines are new.
import javax.swing.JOptionPane; public class FirstDialog { public static void main(String[] args) { JOptionPane.showMessageDialog(null, "First Java dialog"); } } Figure 1-13 The FirstDialog class
»NOTE
»NOTE
In older versions of Java, any application that used a JOptionPane dialog was required to end with a System.exit(0); statement or the application would not terminate. You can add this statement to your programs, and they will work correctly, but it is not necessary.
In Figure 1-13, the first shaded line is an import statement. You use an import statement when you want to access a built-in Java class that is contained in a group of classes called a package. To use the JOptionPane class, you must import the package named javax.swing.JOptionPane. 21
Any import statement you use must be placed outside of any class you write in a file. You will learn more about import statements in general, and the javax.swing
packages in particular, as you continue to study Java.
CREATING YOUR FIRST JAVA CLASSES
»NOTE
You do not need to use an import statement when you use the System class (as with the System.out.println() method) because the System class is contained in the package java.lang, which is automatically imported in every Java program. You could include the statement import java.lang; at the top of any file in which you use the System class, but you are not required to do so.
»NOTE
Earlier in this chapter, you learned that true, false, and null are all reserved words that represent values.
»NOTE
You will learn more about dialog boxes, including how to position them in different locations and how to add more options to them, in Chapter 2.
The second shaded statement in the FirstDialog class in Figure 1-13 uses the showMessageDialog() method that is part of the JOptionPane class. Like the println() method that is used for console output, the showMessageDialog() method is followed by a set of parentheses. However, whereas the println() method requires only one argument between its parentheses to produce an output string, the showMessageDialog() method requires two arguments. When the first argument to showMessageDialog() is null, as it is in the class in Figure 1-13, it means the output message box should be placed in the center of the screen. The second argument, after the comma, is the string that should be output. When a user executes the FirstDialog class, the dialog box in Figure 1-14 is displayed. The user must click the OK button or the Close button to dismiss the dialog box.
»NOTE
Whenever a method requires multiple arguments, the arguments are always separated with commas.
Figure 1-14 Output of the FirstDialog application
TWO TRUTHS AND A LIE: CREATING A JAVA APPLICATION »USING GUI OUTPUT 1. A dialog box is a GUI object resembling a window in which you can place messages you want to display. 2. You use an append statement when you want to access a built-in Java class that is contained in a group of classes called a package. 3. Different methods can require different numbers of arguments. The false statement is #2. You use an import statement when you want to access a built-in Java class that is contained in a group of classes called a package.
22
C H A P T E R O N E
CORRECTING ERRORS AND FINDING HELP Frequently, you might make typing errors as you enter Java statements into your text editor. When you issue the command to compile the class containing errors, the Java compiler produces one or more error messages. The exact error message that appears varies depending on the compiler you are using. In the First class (shown in Figure 1-4), if you mistype the System.out.println() code using a lowercase “s” in System (as system.out.println("First Java Application");), an error message similar to the one shown in Figure 1-15 is displayed. The first line of the error message displays the name of the file in which the error was found (First.java), the line number in which it was found (5), and the nature of the error (“package system does not exist”). The next line identifies the location of the error. This is a compile-time error, or one in which the compiler detects a violation of language syntax rules and is unable to translate the source code to machine code. In this case, the compiler cannot find a symbol named system (with a lowercase initial letter) because Java is a case-sensitive programming language.
Figure 1-15 Error message generated when program contains “system” instead of “System”
When you compile a class, the compiler reports as many errors as it can find so that you can fix as many errors as possible. Sometimes, one error in syntax causes multiple error messages that normally would not be errors if the first syntax error did not exist. Consider the ErrorTest class shown in Figure 1-16. The class contains a single error—the comment that starts in the second line is never closed. However, when you attempt to compile this class, you receive two error messages, as shown in Figure 1-17.
public class ErrorTest /* This class prints a test message { public static void main(String[] args) { System.out.println("Test"); } } Figure 1-16 The ErrorTest class with an unclosed comment
23
CREATING YOUR FIRST JAVA CLASSES
Figure 1-17 Error messages generated by ErrorTest application in Figure 1-16
»NOTE
In Figure 1-17, notice that the line number where the error was detected appears as part of the error message. For example, “ErrorTest.java:2: unclosed comment” means that the comment that is unclosed begins in line 2 of the file. Also, a caret appears below the location where Java detected the error—in this case, at the opening slash of the comment. When the compiler reports a line number in an error message, you can start to look at the indicated location. Frequently, however, the actual error you made is not precisely where Java first noticed it—only nearby. A compile-time error message indicates the spot where the program could go no further.
»NOTE
You also will receive the error message “reached end of file while parsing” if you omit a program’s closing curly brace.
»NOTE
A logic error is a type of run-time error—an error not detected until the program asks the computer to do something wrong, or even illegal, while executing.
The first error message in Figure 1-17 correctly identifies the unclosed comment. The second error message is more confusing: “reached end of file while parsing”. Parsing is the process the compiler uses to divide your source code into meaningful portions; the message means that the compiler was in the process of analyzing the code when the end of the file was encountered prematurely. If you repair the first error by closing off the comment and then save and recompile the class, both error messages disappear. The second message is generated only as a side effect of the unfinished comment. When you compile a class and view a list of errors, correct the errors that make sense to you and then recompile; sometimes, when you correct an error or two, several others disappear. On the other hand, sometimes when you fix a compile-time error and recompile a program, new error messages are generated. That’s because when you fix the first error, the compiler can proceed beyond that point and possibly discover new errors. Of course, no programmer intends to type a program containing syntax errors, but when you do, the compiler finds them all for you. A second kind of error occurs when the syntax of the program is correct and the program compiles but produces incorrect results when you execute it. This type of error is a logic error, which is usually more difficult to find and resolve. In the First class in Figure 1-4, typing the executable statement as System.out.println("Frst Java Application"); does not produce an error. The compiler does not find the spelling error of “Frst” instead of “First”; the code is compiled and the JVM can execute the statements. Other examples of logic errors include multiplying two values when you meant to add, printing one copy of a report when you meant to print five, or forgetting to produce a requested count of the number of times an event has occurred. Errors of this type must be detected by carefully examining the program output. It is the responsibility of the program author to test programs and find any logic errors. Good programming practice stresses programming structure and development that helps minimize errors.
24
C H A P T E R O N E
In addition, each chapter in this book contains four exercises in which you get the opportunity to locate and correct syntax and logic errors. Programmers call the process of correcting all these errors “debugging” a program.
»NOTE
The process of fixing computer errors has been known as debugging since a large moth was found wedged into the circuitry of a mainframe computer at Harvard University in 1945. See these Web sites for interesting details and pictures: www.jamesshuggins.com/h/tek1/first_computer_bug.htm and www.history.navy.mil/photos/images/h96000/ h96566kc.htm.
As you write Java programs, you can frequently consult this book as well as other Java documentation. A great wealth of helpful material exists at the Sun Microsystems Web site, http://java.sun.com. Of particular value is the Java application programming interface, more commonly referred to as the Java API. The Java API is also called the Java class library; it contains information about how to use every prewritten Java class, including lists of all the methods you can use with the classes. Also of interest at the java.sun.com Web site are frequently asked questions (FAQs) that provide brief answers to many common questions about Java software and products. You can also find several versions of the Java Development Kit (JDK) that you can download for free. Versions are available for Windows, Linux, and Solaris operating systems. You can search and browse documentation online or you can download the documentation file for the JDK and install it on your computer. After it is installed, you can search and browse documentation locally. A downloadable Java tutorial titled “The Java Tutorial: A practical guide for programmers” with hundreds of complete working examples is available from http://java.sun.com/docs/ books/tutorial/. The tutorial is organized into trails—groups of lessons on a particular subject. You can start the tutorial at the beginning and navigate sequentially to the end, or jump from one trail to another. As you study each chapter in this book, you are encouraged to make good use of these support materials.
TWO TRUTHS AND A LIE: CORRECTING ERRORS »AND FINDING HELP 1. When you compile a program, sometimes one error in syntax causes multiple error messages. 2. When you compile a program, sometimes multiple syntax errors cause only one error message. 3. Syntax errors are more difficult to find and resolve than logic errors. The false statement is #3. Logic errors are usually more difficult to find and resolve than syntax errors. The compiler locates all syntax errors, but logic errors can be eliminated only through careful examination of your program and its output.
25
»NOTE
The JDK is an SDK—a software development kit that includes tools used by programmers.
CREATING YOUR FIRST JAVA CLASSES
YOU DO IT YOUR FIRST APPLICATION
»NOTE
It is best to use the simplest available text editor when writing Java programs. Multifeatured word-processing programs save documents as much larger files because of all the built-in features, such as font styles and margin settings, which you do not need in your Java programs.
Now that you understand the basics of an application written in Java, you are ready to enter your first Java application into a text editor. It is a tradition among programmers that the first program you write in any language produces “Hello, world!” as its output. You will create such a program now. You can use any text editor, such as Notepad, TextPad, or any other textprocessing program. To write your first Java application: 1. Start any text editor (such as Notepad or TextPad), and then open a new document, if necessary. 2. Type the class header as follows: public class Hello
In this example, the class name is Hello. You can use any valid name you want for the class. If you choose Hello, you always must refer to the class as Hello, and not as hello, because Java is case sensitive. 3. Press Enter once, type {, press Enter again, and then type }. You will add the main() method between these curly braces. Although it is not required, it is good practice to place each curly brace on its own line and to align opening and closing curly brace pairs with each other. Using this format makes your code easier to read.
4. As shown in the shaded portion of Figure 1-18, add the main() method header between the curly braces, and then type a set of curly braces for main().
public class Hello { public static void main(String[] args) { } } Figure 1-18 The main() method shell for the Hello class
5. Next add the statement within the main() method that will produce the output, “Hello, world!”. Use Figure 1-19 as a guide for adding the shaded println() statement to the main() method.
public class Hello { public static void main(String[] args) { System.out.println("Hello, world!"); } } Figure 1-19 Complete Hello class
26
C H A P T E R O N E
6. Save the application as Hello.java. Make certain that the file extension is .java. If it is not, the compiler for Java does not recognize the file as an application it can compile. 7. Go to the command-line prompt for the drive and folder or subdirectory in which you saved Hello.java. At the command line, type: javac Hello.java
8. When the compile is successful, execute your application by typing java Hello at the command line. The output should appear on the next line, as shown in Figure 1-20.
Figure 1-20 Output of Hello application
ADDING COMMENTS TO A CLASS
In this exercise, you add comments to your Hello.java application and save it as a new class named Hello2. To add comments to your application and save it as a new class: 1. Position the insertion point at the top of the file that contains the Hello class, press Enter to insert a new line, press the Up arrow key to go to that line, and then type the following comments at the top of the file. Press Enter after typing each line. Insert your name and today’s date where indicated. // Filename Hello2.java // Written by // Written on > "); name = inputDevice.nextLine(); System.out.print("Please enter your age >> "); age = inputDevice.nextInt(); System.out.println("Your name is " + name + " and you are " + age + " years old."); } }
»NOTE Repeating as output what a user has entered as input is called echoing the input. Echoing input is a good programming practice; it helps eliminate misunderstandings when the user can visually confirm what was entered.
The print() statements that appear before each input statement are examples of prompts. A prompt is a displayed message for the user that requests and describes input. Programs would work without prompts, but they would not be as user-friendly.
»NOTE
Each prompt in the
Figure 2-8 The GetUserInfo class
GetUserInfo
class ends with a space. This is not required; it just separates the words in the prompt from the user’s input value on the screen, improving readability.
Figure 2-9 Typical execution of the GetUserInfo program
PITFALL: USING nextLine() FOLLOWING ONE OF THE OTHER Scanner INPUT METHODS
You can encounter a problem when you use one of the numeric Scanner class retrieval methods or the next() method before you use the nextLine() method. Consider the program in Figure 2-10. It is identical to the one in Figure 2-8, except that the user is asked for an age before being asked for a name. Figure 2-11 shows a typical execution.
63
USING DATA WITHIN A PROGRAM
import java.util.Scanner; public class GetUserInfo2 { public static void main(String[] args) { String name; int age; Scanner inputDevice = new Scanner(System.in); System.out.print("Please enter your age >> "); age = inputDevice.nextInt(); System.out.print("Please enter your name >> "); name = inputDevice.nextLine(); System.out.println("Your name is " + name + " and you are " + age + If you accept numeric input prior to " years old."); string input, the string input is ignored } unless you take special action. } Figure 2-10 The GetUserInfo2 class
Figure 2-11 Typical execution of the GetUserInfo2 program
In Figure 2-11, the user is prompted correctly for an age. However, after the user enters an age and the prompt for the name is displayed, the program does not pause to let the user enter a name. Instead, the program proceeds directly to the output statement, which does not contain a valid name, as you can see in Figure 2-11.
»NOTE
The keyboard buffer is sometimes called the typeahead buffer.
When you type characters using the keyboard, they are stored temporarily in a location in the memory called the keyboard buffer. All keystrokes are stored, including the Enter key. The problem occurs because of a difference in the way the nextLine() method and the other Scanner retrieval methods work. The nextLine() method reads data up to the Enter key character. When you ask for data with a method such as nextLine(), nextInt(), or nextDouble(), any leading whitespace characters are discarded, and a token is retrieved up to the next whitespace entry. However, nextLine() does not ignore leading whitespace; so, for example, when a numeric input method leaves the Enter keypress in the input buffer, and is followed by a call to nextLine(), the nextLine() method accepts the Enter key that followed the number as its input, and needs no additional input from the user. The solution to the problem is simple. After any numeric or next() input, you can add an extra nextLine() method call that will retrieve the abandoned Enter key character. Then, if string input follows, the program will execute smoothly. Figure 2-12 shows a program that contains 64
C H A P T E R T W O
just one change from Figure 2-10—the addition of the shaded statement that retrieves the abandoned Enter key character from the input buffer. Although you could assign the Enter key to a character variable, there is no need to do so. When you accept an entry and discard it without using it, programmers say that the entry is consumed. The diagram in Figure 2-12 shows how the first call to nextInt() accepts the integer, the call to nextLine() accepts the Enter key that follows the integer entry, and the second nextLine() call accepts both the entered name and the Enter key that follows it. Figure 2-13 shows that the revised program executes correctly. import java.util.Scanner; public class GetUserInfo3 { public static void main(String[] args) { String name; int age; Scanner inputDevice = new Scanner(System.in); System.out.print("Please enter your age >> "); age = inputDevice.nextInt(); inputDevice.nextLine(); System.out.print("Please enter your name >> "); name = inputDevice.nextLine(); System.out.println("Your name is " + name + " and you are " + age + " years old."); } }
System.out.print("Please enter your age >> "); 27 Enter age = inputDevice.nextInt(); inputDevice.nextLine(); System.out.print("Please enter your name >> "); Madeline Cooper Enter name = inputDevice.nextLine(); Figure 2-12 The GetUserInfo3 class and a diagram of how the input keys are consumed
»NOTE
When you write programs that accept user input, there is a risk that the user will enter the wrong type of data. For example, if you include a nextInt()
method call in your program, but the user types an alphabetic character, an error will occur and your program will stop running. You will learn to handle this type of error in Chapter 11.
Figure 2-13 Typical execution of the GetUserInfo3 program
65
USING DATA WITHIN A PROGRAM
TRUTHS AND A LIE: USING THE Scanner CLASS »FORTWOKEYBOARD INPUT 1. The System.in object refers to the standard input device, which normally is the keyboard. 2. The System.in object is more flexible than the System.out object because it can read all the basic Java data types. 3. When a user types data followed by the Enter key, the Enter key character is left in the keyboard buffer after Scanner class methods retrieve the other keystrokes. The false statement is #2. The System.in object is not as flexible as the System.out object; it is designed to read only bytes.
USING THE JOptionPane CLASS FOR GUI INPUT In Chapter 1, you learned how to display output at the command line and how to create GUI message boxes to display String objects. Earlier in this chapter, you learned to accept input from the keyboard at the command line. You can also accept input in a GUI dialog box using the JOptionPane class. Two dialog boxes that can be used to accept user input are:
» InputDialog—Prompts the user for text input » ConfirmDialog—Asks the user a question, providing buttons that the user can click for Yes, No, and Cancel responses
USING INPUT DIALOG BOXES
»NOTE
Earlier in this chapter you learned that println() is an overloaded method. Recall that when a method is overloaded, it has multiple versions with the same name that can be used with a variety of options.
An input dialog box asks a question and provides a text field in which the user can enter a response. You can create an input dialog box using the showInputDialog() method. Six overloaded versions of this method are available, but the simplest version uses a single argument that is the prompt you want to display within the dialog box. The showInputDialog() method returns a String that represents a user’s response; this means that you can assign the showInputDialog() method to a String variable and the variable will hold the value that the user enters. For example, Figure 2-14 shows an application that creates an input dialog box containing a prompt for a first name. When the user executes the application, types “Audrey”, then clicks the OK button or presses Enter on the keyboard, the response String will contain “Audrey”. The response String can then be used like any other String object. For example, in the application in Figure 2-14, the response is concatenated with a welcoming message and displayed in a message dialog box. Figure 2-15 shows the dialog box containing a user’s response, and Figure 2-16 shows the resulting output message box.
66
C H A P T E R T W O
import javax.swing.JOptionPane; public class HelloNameDialog { public static void main(String[] args) { String result; result = JOptionPane.showInputDialog(null, "What is your name?"); JOptionPane.showMessageDialog(null, "Hello, " + result + "!"); } } Figure 2-14 The HelloNameDialog class
Figure 2-15 Input dialog box of the HelloNameDialog application
Figure 2-16 Output of the HelloNameDialog application
Within the JOptionPane class, an overloaded version of the showInputDialog() method allows the programmer flexibility in controlling the appearance of the input dialog box. The version of showInputDialog() that requires four arguments can be used to display a title in the dialog box title bar and a message that describes the type of dialog box. The four arguments to showInputDialog() include:
» The parent component, which is the screen component, such as a frame, in front of » » »
which the dialog box will appear. If this argument is null, the dialog box is centered on the screen. The message the user will see before entering a value. Usually this message is a String, but it actually can be any type of object. The title to be displayed in the title bar of the input dialog box. A class field describing the type of dialog box; it can be one of the following: ERROR_MESSAGE, INFORMATION_MESSAGE, PLAIN_MESSAGE, QUESTION_MESSAGE, or WARNING_MESSAGE.
67
USING DATA WITHIN A PROGRAM
For example, when the following statement executes, it displays the input dialog box shown in Figure 2-17. JOptionPane.showInputDialog(null, "What is your area code?", "Area code information", JOptionPane.QUESTION_MESSAGE); Figure 2-17 An input dialog box with a String in the title bar and a question mark icon
Note that the title bar displays “Area code information,” and the dialog box shows a question mark icon. The showInputDialog() method returns a String object, which makes sense when you consider that you might want a user to type any combination of keystrokes into the dialog box. However, when the value that the user enters is intended to be used as a number, as in an arithmetic statement, the returned String must be converted to the correct numeric type. Earlier in this chapter, you learned how to cast a value from one data type to another. However, casting data only works with primitive data types—double, int, char, and so on— not with class objects (that are reference types) such as a String. To convert a String to an integer or double, you must use methods from the built-in Java classes Integer and Double. Each primitive type in Java has a corresponding class contained in the java.lang package; like most classes, the names of these classes begin with uppercase letters. These classes are called type-wrapper classes. They include methods that can process primitivetype values.
»NOTE
The term parse means to break into component parts. Grammarians talk about “parsing a sentence”— deconstructing it so as to describe its grammatical components. Parsing a String converts it to its numeric equivalent.
Figure 2-18 shows a SalaryDialog application that contains two String objects—wageString and dependentsString. Two showInputDialog() methods are called, and the answers are stored in the declared Strings. The shaded statements in Figure 2-18 show how the Strings are converted to numeric values using methods from the type-wrapper classes Integer and Double. The double value is converted using the Double.parseDouble() method, and the integer is converted using the Integer.parseInt() method. Figure 2-19 shows a typical execution of the application.
»NOTE
Remember that in Java, the reserved keyword static means that a method is accessible and usable even though no objects of the class exist. You can tell that the method Double.parseDouble() is a static method, because the method name is used with the class name Double—no object is needed. Similarly, you can tell that Integer.parseInt() is also a static method.
68
C H A P T E R T W O
import javax.swing.JOptionPane; public class SalaryDialog { public static void main(String[] args) { String wageString, dependentsString; double wage, weeklyPay; int dependents; final double HOURS_IN_WEEK = 37.5; wageString = JOptionPane.showInputDialog(null, "Enter employee's hourly wage", "Salary dialog 1", JOptionPane.INFORMATION_MESSAGE); weeklyPay = Double.parseDouble(wageString) *HOURS_IN_WEEK; dependentsString = JOptionPane.showInputDialog(null, "How many dependents?", "Salary dialog 2", JOptionPane.QUESTION_MESSAGE); dependents = Integer.parseInt(dependentsString); JOptionPane.showMessageDialog(null, "Weekly salary is $" + weeklyPay + "\nDeductions will be made for " + dependents + " dependents"); } } Figure 2-18 The SalaryDialog class
Figure 2-19 Sample execution of the SalaryDialog application
69
USING DATA WITHIN A PROGRAM
USING CONFIRM DIALOG BOXES
Sometimes, the input you want from a user does not have to be typed from the keyboard. When you present simple options to a user, you can offer buttons that the user can click to confirm a choice. A confirm dialog box displays the options Yes, No, and Cancel; you can create one using the showConfirmDialog() method in the JOptionPane class. Four overloaded versions of the method are available; the simplest requires a parent component (which can be null) and the String prompt that is displayed in the box. The showConfirmDialog() method returns an integer containing one of three possible values: JOptionPane.YES_OPTION, JOptionPane.NO_OPTION, or JOptionPane.CANCEL_OPTION. Figure 2-20 shows an application that asks a user a question. The shaded statement displays the dialog box shown in Figure 2-21 and stores the user’s response in the integer variable named selection.
import javax.swing.JOptionPane; public class AirlineDialog { public static void main(String[] args) { int selection; boolean isYes; selection = JOptionPane.showConfirmDialog(null, "Do you want to upgrade to first class?"); isYes = (selection == JOptionPane.YES_OPTION); JOptionPane.showMessageDialog(null, "You responded " + isYes); } } Figure 2-20 The AirlineDialog class
Figure 2-21 The confirm dialog box displayed by the AirlineDialog application
After a value is stored in selection, a Boolean variable named isYes is set to the result when selection and JOptionPane.YES_OPTION are compared. If the user has selected the Yes button in the dialog box, this variable is set to true; otherwise, the variable is set to false. Finally, the true or false result is displayed. Figure 2-22 shows the result when a user clicks the Yes button in the dialog box.
70
Figure 2-22 Output of AirlineDialog application when user clicks Yes
C H A P T E R T W O
You can also create a confirm dialog box with five arguments, as follows:
» The parent component, which can be null » The prompt message » The title to be displayed in the title bar » An integer that indicates which option button will be shown (It should be one of the class variables YES_NO_CANCEL_OPTION or YES_NO_OPTION.)
» An integer that describes the kind of dialog box (It should be one of the class variables
ERROR_MESSAGE, INFORMATION_MESSAGE, PLAIN_MESSAGE, QUESTION_MESSAGE, or WARNING_MESSAGE.)
When the following statement is executed, it displays a confirm dialog box, as shown in Figure 2-23: JOptionPane.showConfirmDialog(null, "A data input error has occurred. Continue?", "Data input error", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE);
Note that the title bar displays “Data input error,” the Yes and No buttons appear, and the dialog box shows the error message, “A data input error has occurred. Continue?” It also displays the octagonal ERROR_MESSAGE icon.
Figure 2-23 Confirm dialog box with title, Yes and No buttons, and error icon
»TWO TRUTHS AND A LIE: USING THE JOptionPane CLASS FOR GUI INPUT 1. You can create an input dialog box using the showInputDialog() method; the method returns a String that represents a user’s response. 2. Casting data only works with primitive data types, and not with reference types such as String. You must use methods from the Java classes Integer and Double when you want to convert a dialog box’s returned values to numbers. 3. A confirm dialog box can be created using the showConfirmDialog() method in the JOptionPane class; a confirm dialog box displays the options Accept, Reject, and Escape. The false statement is #3. A confirm dialog box displays the options Yes, No, and Cancel.
71
»NOTE
Confirm dialog boxes provide more practical uses when your applications can make decisions based on the users’ responses. In Chapter 5, you will learn how to make decisions within programs.
USING DATA WITHIN A PROGRAM
YOU DO IT WORKING WITH NUMERIC VALUES
In this section, you will write an application to declare and display numeric values. To declare and display an integer value in an application: 1. Open a new document in your text editor. 2. Create a class header and an opening and closing curly brace for a new class named DemoVariables by typing the following: public class DemoVariables { }
3. Position the insertion point after the opening curly brace, press Enter, press the spacebar several times to indent the line, and then type the following main() method and its curly braces: public static void main(String[] args) { }
»NOTE
You can declare variables at any point within a method prior to their first use. However, it is common practice to declare variables first in a class, and to place executable statements after them.
»NOTE
When your output contains a literal string such as “The entry is”, you can type a space before the closing quotation mark so there is a space between the end of the literal string and the value that prints.
»NOTE
Some programmers use the Tab key to indent lines; others use spaces. Tabs can pose a problem when your code is opened in an editor that is configured differently from the one in which you wrote the source code originally. This book will use three spaces as the standard indentation, but you might prefer two, four, or five spaces in your programs.
4. Position the insertion point after the opening curly brace in the main() method, press Enter, press the spacebar several times to indent the line, and then type the following to declare a variable of type int named entry with a value of 315: int entry = 315;
5. Press Enter at the end of the entry declaration statement, indent the line appropriately, and then type the following two output statements. The first statement uses the print() method to output “The entry is ” and leaves the insertion point on the same output line. The second statement uses the println() method to output the value of entry and advances the insertion point to a new line: System.out.print("The entry is "); System.out.println(entry);
6. Save the file as DemoVariables.java. 7. Compile the file from the command line by typing javac DemoVariables.java. If necessary, correct any errors, save the file, and then compile again.
72
C H A P T E R T W O
8. Execute the application from the command line by typing java DemoVariables. The command window output is shown in Figure 2-24.
Figure 2-24 Output of the DemoVariables application
ACCEPTING USER DATA
A program that displays the same value each time it executes is not as useful as one that can accept and display a user’s entered value. To accept user data in the application: 1. Return to the DemoVariables.java file in the text editor. Rename the class DemoVariables2. Immediately save the file as DemoVariables2.java. 2. At the top of the file, as the first line, type the statement that will allow you to use the Scanner class for data entry: import java.util.Scanner;
3. Remove the value assigned to entry so that the declaration becomes: int entry;
4. After the declaration of entry, add a declaration for a Scanner object that can be used to accept data entry from the keyboard: Scanner keyBoard = new Scanner(System.in);
5. On the next two lines, add a prompt that asks the user to enter an integer and write the statement that accepts the user’s entry: System.out.print("Enter an integer "); entry = keyBoard.nextInt();
6. Save the application, then compile it by typing javac DemoVariables2.java at the command line. If necessary, correct any errors, save the file, and then compile again. 7. Execute the application by typing java DemoVariables2. When the prompt appears on the screen, enter an integer. Figure 2-25 shows a typical execution.
Figure 2-25 Output of the DemoVariables2 application
73
»NOTE
When you modify a file by changing its class name, it is a good idea to save the file with the corresponding new name immediately. Otherwise, it is easy to forget that you have not saved the changes, and when you choose Save, you inadvertently write over the previous file version with the old class name.
USING DATA WITHIN A PROGRAM
8. Execute the program several times using different values, including negative numbers, and confirm that the program works as expected. Then execute the program and type an invalid entry; for example, a letter of the alphabet. Figure 2-26 shows the error messages generated when the user types something other than an integer.
Figure 2-26 Error messages generated when the user enters an “X” into the DemoVariables2 program
As you write Java programs in this chapter and the next few chapters, you are likely to make similar data-entry mistakes. The messages in Figure 2-26 might look intimidating, but you should remember two points:
» First, if you read the messages carefully, you will find they provide some useful informa-
»
tion. The last line of the message indicates that the problem occurred in line 9 of the DemoVariables2 program. In the source code file, line 9 is the one that attempts to get the next integer from the keyboard. This provides a clue that a problem occurred with data entry. Second, you can ignore the messages and simply rerun the program. When you enter valid data, the program will work as expected—you haven’t “broken” anything.
PERFORMING ARITHMETIC
In the next steps, you will accept an additional value into your program and perform arithmetic operations on the entered values. To add another variable and perform arithmetic: 1. Open the DemoVariables2.java text file, and rename the class DemoVariables3. Immediately save it as DemoVariables3.java. 2. After the declaration of entry, add a declaration for a second variable: int anotherEntry;
3. Following the existing statements that prompt for and receive a value for anotherEntry, add two statements that prompt for and receive the newly declared integer: System.out.print("Enter another integer "); anotherEntry = keyBoard.nextInt();
74
C H A P T E R T W O
4. At the end of the main() method, after the statement that displays the value of entry and just before the closing curly brace for the method, add statements that display the second entered value: System.out.print("The other entry is "); System.out.println(anotherEntry);
5. Add some statements that perform arithmetic operations on the two entered values. System.out.println(entry + " plus " + anotherEntry + " is " + (entry + anotherEntry)); System.out.println(entry + " minus " + anotherEntry + " is " + (entry - anotherEntry)); System.out.println(entry + " times " + anotherEntry + " is " + (entry * anotherEntry)); System.out.println(entry + " divided by " + anotherEntry + " is " + (entry / anotherEntry)); System.out.println("The remainder is " + (entry % anotherEntry));
6. Save the file, then compile and test the application several times using different input values. A typical execution is shown in Figure 2-27. Make sure you execute the program a few times using negative values for one or both of the integers. Notice that the remainder value is affected only by the sign of the first operand in the remainder statement, and not by the second. Figure 2-27 Output of the DemoVariables3 application
EXPERIMENTING WITH JAVA PROGRAMS
Next, you will experiment with the program you have created to get a better understanding of variables and arithmetic. To get a better understanding of Java: 1. Open the DemoVariables3.java file in your text editor and change the class name to DemoVariables4. Immediately save the file as DemoVariables4.java. 2. Remove the parentheses surrounding entry + anotherEntry in the statement that displays the sum of the two input values. Save, compile, and execute the program. What is the output? 3. Open the DemoVariables3.java file in your text editor (not DemoVariables4.java) and change the class name to DemoVariables5. Immediately save the file as DemoVariables5.java. 75
USING DATA WITHIN A PROGRAM
4. Remove the parentheses surrounding entry * anotherEntry in the statement that displays the product of the two input values. Save, compile, and execute the program. What is the significant difference between this example and the one from Step 2? Why? 5. Open the DemoVariables3.java file in your text editor and change the class name to DemoVariables6. Immediately save the file as DemoVariables6.java. 6. Change the data types of the two variables to double. Change the two prompts to ask the user for a double instead of an integer. Change the two instances of nextInt() to nextDouble(). Save, compile, and execute the program several times, entering floatingpoint values when prompted. Notice the slight imprecisions that occur with floating-point arithmetic. Study the remainder figure and see if you can determine what it means. Execute the program and enter integers, and notice that the program works appropriately. 7. Open the DemoVariables3.java file in your text editor and change the class name to DemoVariables7. Immediately save the file as DemoVariables7.java. 8. Following the two existing variable declarations, declare a String as follows: String name;
9. Just before the closing curly brace for the main() method, add the following statements that prompt a user for a name, accept it, and display it: System.out.print("Enter your name "); name = keyBoard.nextLine(); System.out.println("Goodbye, " + name);
10. Save, compile, and execute the program. After you enter the requested integers and the arithmetic results are displayed, you are not given the chance to enter a name. That’s because the nextLine() method accepts the Enter key that remained in the input buffer after the last number was entered. To remedy the situation, add the following statement after the statement that gets the last number: keyBoard.nextLine();
11. Save, compile, and execute the program. This time, you are able to enter a name and the program ends as expected.
DON’T DO IT
» Don’t attempt to assign a literal constant floating-point number, such as 2.5, to a float »
»
without following the constant with an uppercase or lowercase F. By default, constant floating-point values are doubles. Don’t forget precedence rules when you write statements that contain multiple arithmetic operations. For example, score1 + score2 / 2 does not compute the average of two scores. Instead, it adds half of score2 to score1. To compute the average, you would write (score1 + score2) / 2. Don’t forget that integer division results in an integer, dropping any fractional part. For example, 1 / 2 is not equal to 0.5; it is equal to 0. 76
C H A P T E R T W O
» Don’t attempt to assign a constant decimal value to an integer using a leading 0. For example,
» » » » »
if you declare int num = 021; and then display num, you will see 17. The leading 0 indicates that the value is in base 8 (octal), so its value is two 8s plus one 1. In the decimal system, 21 and 021 mean the same thing, but not in Java. Don’t use a single equal sign (=) in a Boolean comparison for equality. The operator used for equivalency is composed of two equal signs (==). Don’t try to store a string of characters, such as a name, in a char variable. A char variable can hold only a single character. Don’t forget that when a String and a numeric value are concatenated, the resulting expression is a string. For example, "X" + 2 + 4 results in "X24", not "X6". If you want the result to be "X6", you can use the expression "X" + (2 + 4). Don’t forget to consume the Enter key after numeric input using the Scanner class when a nextLine() method call follows. Don’t forget to use the appropriate import statement when using the Scanner or JOptionPane class.
KEY TERMS A data item is constant when it cannot be changed during the execution of an application. A literal constant is a value that is taken literally at each use. A variable is a named memory location that you can use to store a value. An item’s data type describes the type of data that can be stored there, how much memory the item occupies, and what types of operations can be performed on the data. A numeric constant is a number whose value is taken literally at each use. A primitive type is a simple data type. Java’s primitive types are byte, short, int, long, float, double, char, and boolean. Reference types are complex data types that are constructed from primitive types. A variable declaration is a statement that reserves a named memory location. A strongly typed language is one in which all variables must be declared before they can be used. Camel casing is a style in which an identifier begins with a lowercase letter and subsequent words within the identifier are capitalized. The assignment operator is the equal sign (=); any value to the right of the equal sign is assigned to the variable on the left of the equal sign. An initialization is an assignment made when you declare a variable. An assignment is the act of providing a value for a variable. Associativity refers to the order in which operands are used with operators. 77
USING DATA WITHIN A PROGRAM
An lvalue is an expression that can appear on the left side of an assignment statement. An rvalue is an expression that can appear only on the right side of an assignment statement. A garbage value is the unknown value stored in an uninitialized variable. A named constant is a memory location whose declaration is preceded by the keyword final, and whose value cannot change during program execution.
The keyword final precedes named constants. A symbolic constant is a named constant. A blank final is a final variable that has not yet been assigned a value. A magic number is a value that does not have immediate, intuitive meaning or a number that cannot be explained without additional knowledge. Unnamed constants are magic numbers. The data type int is used to store integers. An integer is a whole number without decimal places. The byte data type holds very small integers, from –128 to 127. The short data type holds small integers, from –32,768 to 32,767. The long data type holds very large integers, from –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. A value can be combined with, or concatenated to, another value. An empty String created by typing a set of quotes with nothing between them is called a null String. You use arithmetic operators to perform calculations with values in your applications. An operand is a value used in an arithmetic statement. Binary operators require two operands. Integer division is the operation in which one integer value is divided by another; the result contains no fractional part. The remainder operator is the percent sign; when it is used with two integers, the result is an integer with the value of the remainder after division takes place. The remainder operator is also called the modulus operator, or sometimes just mod. Operator precedence is the rules for the order in which parts of a mathematical expression are evaluated. A Boolean variable can hold only one of two values—true or false. A relational operator compares two items; an expression that contains a relational operator has a Boolean value. A comparison operator is another name for a relational operator.
78
C H A P T E R T W O
A floating-point number contains decimal positions. A float data type can hold a floating-point value of up to six or seven significant digits of accuracy. A double data type can hold a floating-point value of up to 14 or 15 significant digits of accuracy. The term significant digits refers to the mathematical accuracy of a value. Scientific notation is a display format that more conveniently expresses large or small numeric values; a multidigit number is converted to a single-digit number and multiplied by 10 to a power. A double-precision floating-point number is stored in a double. A single-precision floating-point number is stored in a float. A unifying type is a single data type to which all operands in an expression are converted. An implicit conversion is the automatic transformation of one data type to another. Promotion is an implicit conversion. Type casting forces a value of one data type to be used as a value of another type. A cast operator performs an explicit-type conversion; it is created by placing the desired result type in parentheses before the expression to be converted. An explicit conversion is the data-type transformation caused using a cast operator. The unary cast operator is a more complete name for the cast operator that performs explicit conversions. A unary operator uses only one operand. The char data type is used to hold any single character. String is a built-in Java class that provides you with the means for storing and manipulating character strings.
An escape sequence begins with a backslash followed by a character; the pair represents a single character. The standard input device normally is the keyboard. A token is a unit of data; the Scanner class separates input into tokens. A prompt is a message that requests and describes user input. Echoing the input means to repeat the user’s entry as output so the user can visually confirm the entry’s accuracy. The keyboard buffer is a small area of memory where keystrokes are stored before they are retrieved into a program. The type-ahead buffer is the keyboard buffer. To consume an entry is to retrieve and discard it without using it.
79
USING DATA WITHIN A PROGRAM
An input dialog box asks a question and provides a text field in which the user can enter a response. You can create an input dialog box using the showInputDialog() method. Type-wrapper classes, contained in the java.lang package, include methods that can process primitive-type values. To parse means to break into component parts. A confirm dialog box displays the options Yes, No, and Cancel; you can create one using the showConfirmDialog() method in the JOptionPane class.
CHAPTER SUMMARY
» Data is constant when it cannot be changed after a class is compiled; data is variable
» » » » »
» » » »
when it might change. Variables are named memory locations in which programs store values. You must declare all variables you want to use in a program by providing a data type and a name. Java provides for eight primitive types of data: boolean, byte, char, double, float, int, long, and short. A named constant is a memory location that holds a value that can never be changed; it is preceded by the keyword final. A variable of type int can hold any whole number value from –2,147,483,648 to +2,147,483,647. The types byte, short, and long are all variations of the integer type. You can display variable or constant values using System.out.print() and println() statements as well as by using dialog boxes. There are five standard arithmetic operators for integers: +, –, *, /, and %. Operator precedence is the order in which parts of a mathematical expression are evaluated. Multiplication, division, and remainder always take place prior to addition or subtraction in an expression. Right and left parentheses can be added within an expression when exceptions to this rule are required. When multiple pairs of parentheses are added, the innermost expression surrounded by parentheses is evaluated first. A boolean-type variable can hold a true or false value. Java supports six relational operators: >, =, 1
f. 3 + 8 , =, or !=). However, you can use any expression that evaluates as true or false, such as a simple boolean variable or a method that returns a boolean value.
PITFALL: MISPLACING A SEMICOLON IN AN if STATEMENT
In a Java if statement, the Boolean expression, such as (someVariable == 10), must appear within parentheses. Notice that there is no semicolon at the end of the first line of the if statement if(someVariable == 10) because the statement does not end there. The statement ends after the println() call, so that is where you type the semicolon. You could type the entire if statement on one line and it would execute correctly; however, the twoline format for the if statement is more conventional and easier to read, so you usually type if and the Boolean expression on one line, press Enter, and then indent a few spaces before coding the action that will occur if the Boolean expression evaluates as true. Be careful—if you use the two-line format and type a semicolon at the end of the first line, as in the example shown in Figure 5-4, the results might not be what you intended.
This semicolon ends the decision. no
if(someVariable == 10); System.out.println ("The value is 10");
someVariable == 10?
yes
This indentation has no effect.
The print statement executes no matter what the value of someVariable is.
print “The value is 10”
Figure 5-4 Logic that executes when an extra semicolon is inserted at the end of the first line of an if statement
When the if expression in Figure 5-4 is evaluated, the statement that executes when the tested expression evaluates as true is an empty statement—it contains only a semicolon. Whether the tested expression evaluates as true or false, the decision is over immediately, and execution continues with the next independent statement that prints a message. In this case, because of the incorrect semicolon, the if statement accomplishes nothing. 191
»NOTE
You learned about the relational operators in Chapter 2.
MAKING DECISIONS
PITFALL: USING THE ASSIGNMENT OPERATOR INSTEAD OF THE EQUIVALENCY OPERATOR
»NOTE
The expression if(x = true)
will compile only if x is a boolean variable, because it would be legal to assign true to x. However, such a statement would be useless because the decision could never be false.
Another common programming error occurs when a programmer uses a single equal sign rather than the double equal sign when attempting to determine equivalency. The expression someVariable = 10 does not compare someVariable to 10; instead, it attempts to assign the value 10 to the someVariable variable. When the expression containing the single equal sign is part of an if statement, the assignment is illegal. The confusion arises in part because the single equal sign is used within Boolean expressions in if statements in many other programming languages, such as COBOL, Pascal, and BASIC. Adding to the confusion, Java programmers use the word equals when speaking of equivalencies. For example, you might say, “If someVariable equals 10 . . .”. An alternative to using a Boolean expression, such as someVariable == 10, is to store the Boolean expression’s value in a Boolean variable. For example, if isValueTen is a Boolean variable, then the following statement compares someVariable to 10 and stores true or false in isValueTen: isValueTen = (someVariable == 10);
Then, you can write the if as: if(isValueTen) System.out.println("The value is 10");
This adds an extra step to the program, but makes the if statement more similar to an English-language statement.
»NOTE
When comparing a variable to a constant, some programmers prefer to place the constant to the left of the comparison operator, as in 10 == someVariable. This practice is a holdover from other programming languages, such as C++, in which an accidental assignment might be made when the programmer types the assignment operator (a single equal sign) instead of the comparison operator (the double equal sign). In Java, the compiler does not allow you to make a mistaken assignment in a Boolean expression.
PITFALL: ATTEMPTING TO COMPARE OBJECTS USING THE RELATIONAL OPERATORS
You can use the standard relational operators (==, , =, and !=) to compare the values of primitive data types such as int and double. However, you cannot use , = to compare objects; a program containing such comparisons will not compile. You can use the equals and not equals comparisons (== and !=) with objects, but when you use them, you compare the objects’ memory addresses instead of their values. Recall that every object name is a reference; the equivalency operators compare objects’ references. In other words, == only yields true for two objects when they refer to the same object in memory, not when they are different objects with the same value. To compare the values of objects, you should write specialized methods. You will learn more about this in Chapters 7 and 10.
192
C H A P T E R F I V E
THE if...else STRUCTURE Consider the following statement:
if(someVariable == 10) System.out.println("The value is 10");
Such a statement is sometimes called a single-alternative if because you only perform an action, or not, based on one alternative; in this example, you print a statement when someVariable is 10. Often, you require two options for the course of action following a decision. A dual-alternative if is the decision structure you use when you need to take one or the other of two possible courses of action. For example, you would use a dual-alternative if structure if you wanted to display one message when the value of someVariable is 10 and a different message when it is not. In Java, the if...else statement provides the mechanism to perform one action when a Boolean expression evaluates as true, and to perform a different action when a Boolean expression evaluates as false. For example, the code in Figure 5-5 displays one of two messages. In this example, when the value of someVariable is 10, the message “The value is 10” is printed. When someVariable is any other value, the program prints the message “No, it’s not”. if(someVariable == 10) System.out.println("The value is 10"); else System.out.println("No, it's not");
no
someVariable == 10?
print “No, it’s not”
yes
print “The value is 10”
Figure 5-5 An if...else structure
When you execute an if...else statement, only one of the resulting actions takes place depending on the evaluation of the Boolean expression following the if. Each statement, the one following the if and the one following the else, is a complete statement, so each ends with a semicolon.
TWO TRUTHS AND A LIE: MAKING DECISIONS WITH THE if »AND if...else STRUCTURES 1. In a Java if statement, the keyword if is followed by a Boolean expression within parentheses. 2. In a Java if statement, a semicolon follows the Boolean expression. 3. When determining equivalency in Java, you use a double equal sign. The false statement is #2. In a Java if statement, a semicolon ends the statement. It is used following the action that should occur if the Boolean expression is true. If a semicolon follows the Boolean expression, then the body of the if statement is empty.
193
»NOTE
The indentation shown in the example code in Figure 5-5 is not required, but is standard usage. You vertically align the keyword if with the keyword else, and then indent the action statements that depend on the evaluation.
»NOTE
In an if...else statement, the statement that executes when the tested expression is true ends with a semicolon, as does the statement that executes when the tested expression is false.
»NOTE
You can code an if without an else, but it is illegal to code an else without an if.
MAKING DECISIONS
USING MULTIPLE STATEMENTS IN AN if OR if...else STRUCTURE Often, you want to take more than one action following the evaluation of a Boolean expression within an if statement. For example, you might want to print several separate lines of output or perform several mathematical calculations. To execute more than one statement that depends on the evaluation of a Boolean expression, you use a pair of curly braces to place the dependent statements within a block. For example, the program segment shown in Figure 5-6 determines whether an employee has worked more than the value of a FULL_WEEK constant; if so, the program computes regular and overtime pay.
»NOTE
In Figure 5-6, no action is taken if hoursWorked is less than the value of FULL_WEEK. An actual payroll calculation would include more comprehensive instructions, but they are not necessary for the sake of the example.
if(hoursWorked > FULL_WEEK) { regularPay = FULL_WEEK * rate; overtimePay = (hoursWorked - FULL_WEEK) * OT_RATE * rate; } The if structure ends here. no
hoursWorked > FULL_WEEK?
yes
regularPay = FULL_WEEK * rate
»NOTE
When you create a block, you do not have to place multiple statements within it. It is perfectly legal to place curly braces around a single statement.
overtimePay = (hoursWorked – FULL_WEEK) * OT_RATE * rate
Figure 5-6 An if structure that determines pay
When you place a block within an if statement, it is crucial to place the curly braces correctly. For example, in Figure 5-7, the curly braces have been omitted. Within the code segment in Figure 5-7, when hoursWorked > FULL_WEEK is true, regularPay is calculated and the if expression ends. The next statement that computes overtimePay executes every time the program runs, no matter what value is stored in hoursWorked. This last statement does not depend on the if statement; it is an independent, stand-alone statement. The indentation might be deceiving; it looks as though two statements depend on the if statement, but indentation does not cause statements following an if statement to be dependent. Rather, curly braces are required if multiple statements must be treated as a block.
194
C H A P T E R F I V E
The if structure ends here. if(hoursWorked > FULL_WEEK) regularPay = FULL_WEEK * rate; overtimePay = (hoursWorked - FULL_WEEK) * OT_RATE * rate; This indentation is ignored by the compiler. no
hoursWorked > FULL_WEEK?
yes
The overtime calculation is always performed no matter what the value of hoursWorked is.
regularPay = FULL_WEEK * rate
overtimePay = (hoursWorked – FULL_WEEK) * OT_RATE * rate
Figure 5-7 Erroneous overtime pay calculation with missing curly braces
Because the curly braces are missing, regardless of whether hoursWorked is more than FULL_WEEK, the last statement in Figure 5-7 is a new stand-alone statement that is not part of the if, and so it executes. In Figure 5-7, if the hoursWorked value is FULL_WEEK or less, then the regularPay calculation does not execute (it executes only if hoursWorked is greater than FULL_WEEK), but the separate overtimePay statement does. If hoursWorked is 30, for example, and FULL_WEEK is 40, then the program calculates the value of overtimePay as a negative number (because 30 minus 40 results in –10). Therefore, the output is incorrect. Correct blocking is crucial to achieving valid output. Just as you can block statements to depend on an if, you can also block statements to depend on an else. Figure 5-8 shows an application that contains an if structure with two dependent statements and an else with two dependent statements. The program executes the final println() statement without regard to the hoursWorked variable’s value; it is not part of the if structure. Figure 5-9 shows the output from two executions of the program. In the first execution, the user entered 39 for the hoursWorked value and 20.00 for rate; in the second execution, the user entered 42 for hoursWorked and 20.00 for rate.
195
MAKING DECISIONS
import java.util.Scanner; public class Payroll { public static void main(String[] args) { double rate; double hoursWorked; double regularPay; double overtimePay; final int FULL_WEEK = 40; final double OT_RATE = 1.5; Scanner keyboard = new Scanner(System.in); System.out.print("How many hours did you work this week? "); hoursWorked = keyboard.nextDouble(); System.out.print("What is your regular pay rate? "); rate = keyboard.nextDouble(); if(hoursWorked > FULL_WEEK) { regularPay = FULL_WEEK * rate; overtimePay = (hoursWorked - FULL_WEEK) * OT_RATE * rate; } else { regularPay = hoursWorked * rate; overtimePay = 0.0; } System.out.println("Regular pay is " + regularPay + "\nOvertime pay is " + overtimePay); } } Figure 5-8 Payroll application containing an if and else with blocks
Figure 5-9 Output of the Payroll application
196
C H A P T E R F I V E
When you block statements, you must remember that any variable you declare within a block is local to that block. For example, the following code segment contains a variable named sum that is local to the block following the if. The last println() statement causes an error because the sum variable is not recognized: if(a == b) { int sum = a + b; System.out.println ("The two variables are equal"); } System.out.println("The sum is " + sum);
The sum variable is not recognized here.
TRUTHS AND A LIE: USING MULTIPLE STATEMENTS »INTWO AN if OR if...else STRUCTURE 1. To execute more than one statement that depends on the evaluation of a Boolean expression, you use a pair of curly braces to place the dependent statements within a block. 2. Indentation can be used to cause statements following an if statement to depend on the evaluation of the Boolean expression. 3. When you declare a variable within a block, it is local to that block. The false statement is #2. Indentation does not cause statements following an if statement to be dependent; curly braces are required if multiple statements must be treated as a block.
NESTING if AND if...else STATEMENTS Within an if or an else, you can code as many dependent statements as you need, including other if and else structures. Statements in which an if structure is contained inside another if structure are commonly called nested if statements. Nested if statements are particularly useful when two conditions must be met before some action is taken. For example, suppose you want to pay a $50 bonus to a salesperson only if the salesperson sells at least three items that total at least $1000 in value during a specified time. Figure 5-10 shows the logic and the code to solve the problem. Notice that there are no semicolons in the if statement code shown in Figure 5-10 until after the bonus = SALES_BONUS; statement. The expression itemsSold >= MIN_ITEMS is evaluated first. Only if this expression is true does the program evaluate the second Boolean expression, totalValue >= MIN_VALUE. If that expression is also true, the bonus assignment statement executes and the if structure ends. 197
MAKING DECISIONS
final final final bonus
int MIN_ITEMS = 3; int MIN_VALUE = 1000; int SALES_BONUS = 50; = 0;
no
yes
itemsSold >= MIN_ITEMS?
if(itemsSold >= MIN_ITEMS) if(totalValue >= MIN_VALUE) bonus = SALES_BONUS; no The Boolean expression in each if statement must be true for the bonus assignment to be made.
totalValue >= MIN_VALUE?
yes
bonus = SALES_BONUS
Figure 5-10 Determining whether to assign a bonus using nested if statements
When you use nested if statements, you must pay careful attention to placement of any else clauses. For example, suppose you want to distribute bonuses on a revised schedule, as shown in Figure 5-11. If the salesperson does not sell at least three items, you want to give a $10 bonus. If the salesperson sells at least three items whose combined value is less than $1000, the bonus is $25. If the salesperson sells at least three items whose combined value is at least $1000, the bonus is $50. final final final final final
int int int int int
MIN_ITEMS = 3; MIN_VALUE = 1000; LARGE_BONUS = 50; MEDIUM_BONUS = 25; SMALL_BONUS = 10;
no
itemsSold >= MIN_ITEMS?
yes
bonus = 0; if(itemsSold >= MIN_ITEMS) if(totalValue >= MIN_VALUE) bonus = LARGE_BONUS; else bonus = MEDIUM_BONUS; else bonus = SMALL_BONUS;
no
bonus = SMALL_BONUS
bonus = MEDIUM_BONUS
The last else goes with the first if. Figure 5-11 Determining one of three bonuses using nested if statements
198
totalValue >= MIN_VALUE?
yes
bonus = LARGE_BONUS
C H A P T E R F I V E
As Figure 5-11 shows, when one if statement follows another, the first else clause encountered is paired with the most recent if encountered. The complete nested if...else structure fits entirely within the if portion of the outer if...else statement. No matter how many levels of if...else statements are needed to produce a solution, the else statements are always associated with their ifs on a “first in-last out” basis.
»TWO TRUTHS AND A LIE: NESTING if AND if...else STATEMENTS 1. Statements in which an if structure is contained inside another if structure are commonly called nested if statements. 2. When one if statement follows another, the first else clause encountered is paired with the first if that occurred before it. 3. A complete nested if...else structure always fits entirely within either the if portion or the else portion of its outer if...else statement. The false statement is #2. When one if statement follows another, the first else clause encountered is paired with the most recent if encountered.
USING LOGICAL AND and OR OPERATORS For an alternative to some nested if statements, you can use the logical AND operator between two Boolean expressions to determine whether both are true. The AND operator is written as two ampersands (&&). For example, the two statements shown in Figure 5-12 work exactly the same way. In each case, the itemsSold variable is tested, and if it is at least the minimum number of items required for a bonus, the totalValue is tested. If totalValue is at least the minimum required value, the bonus is set to SALES_BONUS.
if(itemsSold >= MIN_ITEMS) if(totalValue >= MIN_VALUE)
bonus = SALES_BONUS; if(itemsSold >= MIN_ITEMS && totalValue >= MIN_VALUE)
bonus = SALES_BONUS; Figure 5-12 Code for bonus-determining decision using the && operator
It is important to note that when you use the && operator, you must include a complete Boolean expression on each side. If you want to set a bonus to $400 when a saleAmount is both over $1000 and under $5000, the correct statement is: if(saleAmount > 1000 && saleAmount < 5000) bonus = 400;
199
»NOTE
In Figure 5-11, the indentation of the lines of code helps to show which else is paired with which if. Remember, the compiler does not take indentation into account, but consistent indentation can help readers understand a program’s logic.
MAKING DECISIONS
»NOTE
For clarity, many programmers prefer to surround each Boolean expression that is part of a compound Boolean expression with its own set of parentheses. For example: if((saleAmount > 1000) && (saleAmount < 5000)) bonus = 400;
Use this format if it is clearer to you.
Even though the saleAmount variable is intended to be used in both parts of the AND expression, the following statement is incorrect and does not compile because there is not a complete expression on both sides of the &&: if(saleAmount > 1000 && < 5000) bonus = 400;
This statement will not compile because it does not have a Boolean expression on each side of the &&.
The expressions in each part of an AND expression are evaluated only as much as necessary to determine whether the entire expression is true or false. This feature is called shortcircuit evaluation. With the AND operator, both Boolean expressions must be true before the action in the statement can occur. (The same is true for nested ifs, as you can see in Figure 5-10.) If the first tested expression is false, the second expression is never evaluated, because its value does not matter. For example, if a is not greater than LIMIT in the following if statement, then the evaluation is complete because there is no need to evaluate whether b is greater than LIMIT. if(a > LIMIT && b > LIMIT) System.out.println("Both are greater than " + LIMIT);
»NOTE
The two vertical lines used in the OR operator are sometimes called “pipes.” The pipe appears on the same key as the backslash on your keyboard.
You are never required to use the AND operator because using nested if statements always achieves the same result, but using the AND operator often makes your code more concise, less error-prone, and easier to understand. With the AND operator, both Boolean expressions that surround the operator must be true before the action in the statement can occur. When you want some action to occur even if only one of two conditions is true, you can use nested if statements, or you can use the conditional OR operator, which is written as ||. For example, if you want to give a 10% discount to any customer who satisfies at least one of two conditions—buying at least 5 items or buying any number of items that total at least $3000 in value—you can write the code using either of the ways shown in Figure 5-13.
200
C H A P T E R F I V E
final int MIN_ITEMS = 5; final double MIN_VALUE = 3000.00; final double DISCOUNT = 0.10; double discountRate = 0; if(itemsBought >= MIN_ITEMS) discountRate = DISCOUNT; else if(itemsValue >= MIN_VALUE) discountRate = DISCOUNT;
no
no
itemsValue >= MIN_VALUE?
itemsBought >= MIN_ITEMS?
yes
yes
discountRate = DISCOUNT
discountRate = DISCOUNT
The second Boolean expression is evaluated only if the first one is false.
if(itemsBought >= MIN_ITEMS || itemsValue >= MIN_VALUE) discountRate = DISCOUNT; Figure 5-13 Determining the customer’s discount when the customer needs to meet only one of two criteria
As with the AND operator, the OR operator uses short-circuit evaluation. In other words, because only one of the Boolean expressions in an OR must be true to cause the dependent statements to execute, if the expression to the left of the || is true, then there is no need to evaluate the expression to the right of the ||.
»NOTE
A common use of the OR operator is to decide to take action whether a character variable is either the uppercase or lowercase version of a letter. For example, in the following statement, the subsequent action occurs whether the selection variable holds an uppercase or lowercase A: if(selection == 'A' || selection == 'a') System.out.println("You chose option A");
»TWO TRUTHS AND A LIE: USING LOGICAL AND and OR OPERATORS 1. The AND operator is written as two ampersands (&&) and the OR operator is written as two pipes (||). 2. When you use the && and || operators, you must include a complete Boolean expression on each side. 3. When you use an AND or OR operator, each Boolean expression that surrounds the operator is always tested in order from left to right. The false statement is #3. The expressions in each part of an AND or OR expression are evaluated only as much as necessary to determine whether the entire expression is true or false. For example, in an AND expression, if the first Boolean value is false, the second expression is not tested. In an OR expression, if the first Boolean value is true, the second expression is not tested. This feature is called short-circuit evaluation.
201
MAKING DECISIONS
MAKING ACCURATE AND EFFICIENT DECISIONS When new programmers must make a range check, they often introduce incorrect or inefficient code into their programs. A range check is a series of statements that determine within which of a set of ranges a value falls. Consider a situation in which salespeople can receive one of three possible commission rates based on their sales. For example, a sale totaling $1000 or more earns the salesperson an 8% commission, a sale totaling $500 through $999 earns 6% of the sale amount, and any sale totaling $499 or less earns 5%. Using three separate if statements to test single Boolean expressions might result in some incorrect commission assignments. For example, examine the code shown in Figure 5-14.
final final final final final final
double double double double double double
HIGH_LIM = 1000.00; HIGH_RATE = 0.08; MED_LIM = 500.00; MED_RATE = 0.06; LOW_LIM = 499.99; LOW_RATE = 0.05;
no
saleAmount >= HIGH_LIM?
yes
commissionRate = HIGH_RATE
if(saleAmount >= HIGH_LIM) commissionRate = HIGH_RATE; if(saleAmount >= MED_LIM) commissionRate = MED_RATE; if(saleAmount = MED_LIM?
A high saleAmount will be assigned an incorrect rate.
yes
commissionRate = MED_RATE
no
saleAmount = HIGH_LIM) evaluates as true, so HIGH_RATE is correctly assigned to commissionRate. However, when a saleAmount is $5000, the next if expression, (saleAmount >= MED_LIM), also evaluates as true, so the commissionRate, which was just set to HIGH_RATE, is incorrectly reset to MED_RATE. A partial solution to this problem is to use an else statement following the first evaluation, as shown in Figure 5-15. final final final final final final
double double double double double double
HIGH_LIM = 1000.00; HIGH_RATE = 0.08; MED_LIM = 500.00; MED_RATE = 0.06; LOW_LIM = 499.99; LOW_RATE = 0.05;
if(saleAmount >= HIGH_LIM) commissionRate = HIGH_RATE; else if(saleAmount >= MED_LIM) commissionRate = MED_RATE; if(saleAmount = MED_LIM?
saleAmount >= HIGH_LIM?
yes
yes
commissionRate = HIGH_RATE
commissionRate = MED_RATE
This question has already been answered.
no
saleAmount = HIGH_LIM) is true and the commissionRate becomes HIGH_RATE; then the entire if structure ends. When the saleAmount is not greater than or equal to $1000 (for example, $800), the first if expression is false and the else statement executes and correctly sets the commissionRate to MED_RATE. The code shown in Figure 5-15 works, but it is somewhat inefficient. When the saleAmount is any amount over LOW_RATE, either the first if sets commissionRate to HIGH_RATE for 203
MAKING DECISIONS
amounts that are at least $1000, or its else sets commissionRate to MED_RATE for amounts that are at least $500. In either of these two cases, the Boolean value tested in the next statement, if(saleAmount = MED_LIM) commissionRate = MED_RATE; else commissionRate = LOW_RATE;
no
commissionRate = LOW_RATE
saleAmount >= MED_LIM?
saleAmount >= HIGH_LIM?
yes
yes
commissionRate = HIGH_RATE
commissionRate = MED_RATE
Figure 5-16 Improved and efficient commission-determining logic
Within a nested if...else, like the one shown in Figure 5-16, it is most efficient to ask the question that is most likely to be true first. In other words, if you know that most saleAmount values are high, compare saleAmount to HIGH_LIM first. That way, you most frequently avoid asking multiple questions. If, however, you know that most saleAmounts are small, you should ask if(saleAmount < LOW_LIM) first. The code shown in Figure 5-17 results in the same commission value for any given saleAmount, but is more efficient when most saleAmount values are small.
204
C H A P T E R F I V E
final final final final final
double double double double double
HIGH_RATE = 0.08; MED_LIM = 1000.00 MED_RATE = 0.06; LOW_LIM = 500.00; LOW_RATE = 0.05;
if(saleAmount < LOW_LIM) commissionRate = LOW_RATE; else if(saleAmount < MED_LIM) commissionRate = MED_RATE; else commissionRate = HIGH_RATE;
no
no
yes
saleAmount < LOW_LIM?
yes
saleAmount < MED_LIM?
commissionRate = LOW_RATE
commissionRate = MED_RATE
commissionRate = HIGH_RATE
Figure 5-17 Commission-determining code asking about the smallest saleAmount first
»NOTE
In Figure 5-17, notice that the comparisons use the < operator instead of HIGH) System.out.println("Error in pay rate"); 205
MAKING DECISIONS
Similarly, your boss might request, “Print the names of those employees in departments 1 and 2.” Because the boss used the word “and” in the request, you might be tempted to write the following: if(department == 1 && department == 2) System.out.println("Name is: " + name);
Another type of mistake occurs if you use a single ampersand or pipe when you try to indicate a logical AND or OR. Both & and | are valid Java operators, but they operate on bits rather than making comparisons as && and || do.
However, the variable department can never contain both a 1 and a 2 at the same time, so no employee name will ever be printed, no matter what department the employee is in.
»TWO TRUTHS AND A LIE: MAKING ACCURATE AND EFFICIENT DECISIONS 1. A range check is a series of statements that determine within which of a set of ranges a value falls. 2. When you must make a series of decisions in a program, it is most efficient to first ask the question that is most likely to be true. 3. The statement if(payRate < 6.00 && payRate > 50.00) can be used to select payRate values that are very high or very low. The false statement is #3. The statement if(payRate < 6.00 && payRate > 50.00)cannot be used to make a selection because no value for payRate can be both below 6.00 and above 50.00 at the same time.
»NOTE
USING THE switch STATEMENT By nesting a series of if and else statements, you can choose from any number of alternatives. For example, suppose you want to print a student’s class year based on a stored number. Figure 5-18 shows one possible implementation of the program.
if(year == 1) System.out.println("Freshman"); else if(year == 2) System.out.println("Sophomore"); else if(year == 3) System.out.println("Junior"); else if(year == 4) System.out.println("Senior"); else System.out.println("Invalid year"); Figure 5-18 Determining class status using nested if statements
206
C H A P T E R F I V E
An alternative to using the series of nested if statements shown in Figure 5-18 is to use the switch statement. The switch statement is useful when you need to test a single variable against a series of exact integer or character values. The switch structure uses four keywords:
» switch starts the structure and is followed immediately by a test expression enclosed in » » »
parentheses. case is followed by one of the possible values for the test expression and a colon. break optionally terminates a switch structure at the end of each case. default is optionally used prior to any action that should occur if the test variable does not match any case.
Figure 5-19 shows the case structure used to print the four school years.
int year; // Get year value from user input, or simply by assigning switch(year) { case 1: System.out.println("Freshman"); break; case 2: System.out.println("Sophomore"); break; case 3: System.out.println("Junior"); break; case 4: System.out.println("Senior"); break; default: System.out.println("Invalid year"); } Figure 5-19 Determining class status using a switch statement
The switch structure shown in Figure 5-19 begins by evaluating the year variable shown in the switch statement. If the year is equal to the first case value, which is 1, the statement that prints “Freshman” executes. The break statement bypasses the rest of the switch structure, and execution continues with any statement after the closing curly brace of the switch structure. If the year variable is not equivalent to the first case value of 1, the next case value is compared, and so on. If the year variable does not contain the same value as any of the case statements, the default statement or statements execute. You can leave out the break statements in a switch structure. However, if you omit the break and the program finds a match for the test variable, all the statements within the switch 207
»NOTE
You are not required to list the case values in ascending order, as shown in Figure 5-19, although doing so often makes a statement easier to understand. Logically, it is most efficient to list the most common case first, instead of the case with the lowest value.
»NOTE
Besides int and char, you can use a switch statement to test values of types byte and short, which hold smaller integer values.
MAKING DECISIONS
statement execute from that point forward. For example, if you omit each break statement in the code shown in Figure 5-19, when the year is 3, the first two cases are bypassed, but “Junior”, “Senior”, and “Invalid year” all print. You should intentionally omit the break statements if you want all subsequent cases to execute after the test variable is matched. You do not need to write code for each case in a case statement. For example, suppose that the supervisor for departments 1, 2, and 3 is “Jones”, but other departments have different supervisors. In that case, you might use the code in Figure 5-20. int department; String supervisor; // Statements to get department switch(department) { case 1: case 2: case 3: supervisor = "Jones"; break; case 4: supervisor = "Staples"; break; case 5: supervisor = "Tejano"; break: default: System.out.println("Invalid department code"); } Figure 5-20 Using empty case statements so the same result occurs in multiple cases
»
NOTE When several char variables must be checked and you want to ignore whether they are uppercase or lowercase, one frequently used technique employs empty case statements, as in the following example: switch(departmentCode) { case 'a': case 'A': departmentName = "Accounting"; break; case 'm': case 'M': departmentName = "Marketing"; break; // and so on
You are never required to use a switch structure; you can always achieve the same results with nested if statements. The switch structure is simply convenient to use when there are several alternative courses of action that depend on a single integer or character variable. 208
C H A P T E R F I V E
In addition, it makes sense to use switch only when there are a reasonable number of specific matching values to be tested. For example, if every sale amount from $1 to $500 requires a 5% commission, it would not be reasonable to test every possible dollar amount using the code in Figure 5-21. Because 500 different dollar values result in the same commission, one test—if(saleAmount = 25); can become part of the relatively easy-to-read expression if(!oldEnough)....
TWO TRUTHS AND A LIE: USING THE CONDITIONAL »AND NOT OPERATORS 1. The conditional operator is used as an abbreviated version of the if...else structure and requires two expressions separated with an exclamation point. 2. The NOT operator is written as the exclamation point (!). 3. The value of any false expression becomes true when preceded by the NOT operator. The false statement is #1. The conditional operator requires three expressions separated with a question mark and a colon.
UNDERSTANDING PRECEDENCE You can combine as many AND or OR operators as you need to make a decision. For example, if you want to award bonus points (defined as BONUS) to any student who receives a perfect score on any of four quizzes, you might write a statement like the following: if(score1 == PERFECT || score2 == PERFECT || score3 == PERFECT || score4 == PERFECT) bonus = BONUS; else bonus = 0;
In this case, if at least one of the score variables is equal to the PERFECT constant, the student receives the bonus points. Although you can combine any number of AND or OR operators, special care must be taken when you combine them. You learned in Chapter 2 that operations have higher and lower precedences, and an operator’s precedence makes a difference in how an expression is evaluated. For example, within an arithmetic expression, multiplication and division are always performed prior to addition or subtraction. Table 5-1 shows the precedence of the operators you have used so far.
211
MAKING DECISIONS
Precedence
Operator(s)
Symbol(s)
Highest
Logical NOT
!
Intermediate
Multiplication, division,
Lowest
modulus
* / %
Addition, subtraction
+ -
Relational
> < >= 2 || age < 25 && gender == 'M') extraPremium = 200; // Assigns extra premiums correctly if((trafficTickets > 2 || age < 25) && gender == 'M') extraPremium = 200; Figure 5-22 Some comparisons using && and ||
Consider a 30-year-old female driver with three traffic tickets; according to the stated criteria, she should not be assigned the extra premium because she is not male. With the first if statement in Figure 5-22, the AND operator takes precedence over the OR operator, so age < 25 && gender == 'M' is evaluated first. The value is false because age is not less than 25, so the expression is reduced to trafficTickets > 2 or false. Because the value of the tickets variable is greater than 2, the entire expression is true, and $200 is assigned to extraPremium, even though it should not be. 212
C H A P T E R F I V E
In the second if statement shown in Figure 5-22, parentheses have been added so the OR operator is evaluated first. The expression trafficTickets > 2 || age < 25 is true because the value of trafficTickets is 3. So the expression evolves to true && gender== 'M'. Because gender is not ‘M’, the value of the entire expression is false, and the extraPremium value is not assigned 200, which is correct. The following two conventions are important to keep in mind:
» The order in which you use operators makes a difference. » You can always use parentheses to change precedence or make your intentions clearer.
»TWO TRUTHS AND A LIE: UNDERSTANDING PRECEDENCE 1. Assume p, q, and r are all Boolean variables that have been assigned the value true. After the following statement executes, the value of p is still true. p = !q || r;
2. Assume p, q, and r are all Boolean variables that have been assigned the value true. After the following statement executes, the value of p is still true. p = !(!q && !r);
3. Assume p, q, and r are all Boolean variables that have been assigned the value true. After the following statement executes, the value of p is still true. p = !(q || !r);
The false statement is #3. If p, q, and r are all Boolean variables that have been assigned the value true, then after p = !(q || !r); executes, the value of p is false. First q is evaluated as true, so the entire expression within the parentheses is true. The leading NOT operator reverses that result to false and assigns it to p.
YOU DO IT USING AN if...else
In this section, you will start writing a program for Event Handlers Incorporated that determines which employee will be assigned to manage a client’s scheduled event. To begin, you will prompt the user to answer a question about the event type, and then the program will display the name of the manager who handles such events. There are two event types: private events, handled by Dustin Britt, and corporate events, handled by Carmen Lindsey. To write a program that chooses between two managers: 1. Open a new text file, and then enter the first lines of code to create a class named ChooseManager. You will import the Scanner class so that you can use keyboard input. The class will contain a main() method that performs all the work of the class: import java.util.Scanner; public class ChooseManager { public static void main(String[] args) {
213
»NOTE
Using parentheses to make your intentions more clear is never wrong. Even when an expression would be evaluated in the desired way without extra parentheses, adding them can help others to more easily understand your programs.
MAKING DECISIONS
2. On new lines, declare the variables and constants this application will use. You will ask the user to enter an integer eventType. The values of the event types and the names of the managers for private and corporate events are stored as symbolic constants; the chosen manager will be assigned to the chosenManager string: int eventType; String chosenManager; final int PRIVATE_CODE = 1; final int CORPORATE_CODE = 2; final String PRIV_MANAGER = "Dustin Britt"; final String CORP_MANAGER = "Carmen Lindsey";
3. Define the input device, then add the code that prompts the user to enter a 1 or 2 depending on the event type being scheduled, and accept the response: Scanner input = new Scanner(System.in); System.out.println("What type of event are you scheduling?"); System.out.print("Enter " + PRIVATE_CODE + " for private, " + CORPORATE_CODE + " for corporate... "); eventType = input.nextInt();
4. Use an if...else statement to choose the name of the manager to be assigned to the chosenManager string, as follows: if(eventType == PRIVATE_CODE) chosenManager = PRIV_MANAGER; else chosenManager = CORP_MANAGER;
5. Display the chosen code and corresponding manager’s name: System.out.println("You entered " + eventType); System.out.println("Manager for this event will be " + chosenManager);
6. Type the two closing curly braces to end the main()method and the ChooseManager class. 7. Save the program as ChooseManager.java, and then compile and run the program. Confirm that the program selects the correct manager when you choose 1 for a private event or 2 for a corporate event. For example, Figure 5-23 shows the output when the user enters 1 for a private event.
Figure 5-23 Output of the ChooseManager application after user enters 1
214
C H A P T E R F I V E
8. Rerun the ChooseManager program and enter an invalid item, such as 3. The manager selected is Carmen Lindsey because the program tests only for an entered value of 1 or not 1. Modify the program to display an error message when the entered value is not 1 or 2. Rename the class ChooseManager2 and save the file as ChooseManager2.java.
CREATING AN Event CLASS TO USE IN A DECISION-MAKING APPLICATION
Next, you will create an Event class. The class will be used by Event Handlers Incorporated to store data about a planned event. Each Event object includes three data fields: the type of event, the name of the manager for the event, and the hourly rate charged for handling the event. The Event class also contains a get and set method for each field. To create the Event class: 1. Open a new text file and type the class header for the Event class, followed by declarations for the three data fields: public class Event { private int typeOfEvent; private double rate; private String manager;
2. Create three get methods; each returns one of the data fields in the Event class: public int getType() { return typeOfEvent; } public double getRate() { return rate; } public String getManager() { return manager; }
3. Also add three set methods; each sets a single data field: public void setType(int eventType) { typeOfEvent = eventType; } public void setRate(double eventRate) { rate = eventRate; } public void setManager(String managerName) { manager = managerName; }
215
MAKING DECISIONS
4. Type the closing curly brace for the class. 5. Save the file as Event.java, then compile the file and correct any errors.
WRITING AN APPLICATION THAT USES THE Event CLASS
Now that you have created an Event class, you will create a CreateEventObject application. You will prompt the user for an event type, and then select both a manager and a rate for the Event based on the selected type. Private events are managed by Dustin Britt and cost $47.99 per hour. Corporate events are managed by Carmen Lindsey and cost $75.99 per hour. Events held by nonprofit organizations are managed by Robin Armenetti and cost $40.99 per hour. After the user selects an event type, you will instantiate an Event object containing appropriate event data. To create an application that uses the Event class: 1. Open a new file in your text editor and type the following to begin the CreateEventObject class: import java.util.Scanner; public class CreateEventObject { public static void main(String[] args) {
2. Add variables and constants that will be used in the program as follows: int eventType; String chosenManager = ""; double chosenRate = 0; Event scheduledEvent = new Event(); final int PRIVATE_CODE = 1; final int CORPORATE_CODE = 2; final int NONPROFIT_CODE = 3; final String PRIVATE_MANAGER = "Dustin Britt"; final String CORP_MANAGER = "Carmen Lindsey"; final String NONPROFIT_MANAGER = "Robin Armenetti"; final double PRIVATE_RATE = 47.99; final double CORP_RATE = 75.99; final double NONPROFIT_RATE = 40.99; boolean choiceIsGood = true;
3. Declare a Scanner object to be used for input, prompt the user for an event type, and read it in: Scanner input = new Scanner(System.in); System.out.println("What type of event are you scheduling?"); System.out.print("Enter " + PRIVATE_CODE + " for private, " + CORPORATE_CODE + " for corporate, or " + NONPROFIT_CODE + " for nonprofit... "); eventType = input.nextInt();
216
C H A P T E R F I V E
4. Write a decision that selects the correct manager and rate based on the user’s choice. Because two statements execute when the user selects 1, 2, or 3, the statements must be blocked using curly braces. If the user does not enter 1, 2, or 3, set the Boolean variable choiceIsGood to false: if(eventType == PRIVATE_CODE) { chosenManager = PRIVATE_MANAGER; chosenRate = PRIVATE_RATE; } else if(eventType == CORPORATE_CODE) { chosenManager = CORP_MANAGER; chosenRate = CORP_RATE; } else if(eventType == NONPROFIT_CODE) { chosenManager = NONPROFIT_MANAGER; chosenRate = NONPROFIT_RATE; } else choiceIsGood = false;
5. If the user made a valid choice, set values for the three fields that are contained in the scheduled Event object. Otherwise, display an error message: if(choiceIsGood) { scheduledEvent.setType(eventType); scheduledEvent.setManager(chosenManager); scheduledEvent.setRate(chosenRate); } else System.out.println("You entered " + eventType + " which is invalid.");
6. To confirm that the Event was created properly, display the Event object’s fields: System.out.println("Scheduled event:"); System.out.println("Type: " + scheduledEvent.getType() + " Manager: " + scheduledEvent.getManager() + " Rate: " + scheduledEvent.getRate() + " per hour");
7. Add a closing curly brace for the main() method and another for the class. 8. Save the application as CreateEventObject.java. Compile and run the program several times with different input at the prompt. Confirm that the output shows the correct event manager, type, and rate based on your response to the prompt. (If your response is an invalid event type, then the default values for the event should appear.) Figure 5-24 shows two executions of the program. 217
MAKING DECISIONS
Figure 5-24 Output of the CreateEventObject application after the user enters 3 and then 4
9. Experiment with the program by removing the initialization values for chosenManager and chosenRate. When you compile the program, you receive error messages for the setManager() and setRate() statements that chosenManager and chosenRate might not have been initialized. The compiler determines that the values for those variables are set based on if statements, and so, depending on the outcome, they might never have been given valid values. Replace the initialization values for the variables to make the program compile successfully. 10. Experiment with the program by removing the initialization value for the Boolean variable choiceIsGood. When you compile the program, you receive an error message that the variable might never have been initialized. Because the variable is set to false only under certain conditions (an invalid event-type entry), the compiler determines that the variable might not have a usable value. Replace the initialization value and recompile the program to make it work correctly.
USING THE switch STATEMENT
Next, you will modify the CreateEventObject program to convert the nested if statements to a switch structure. To convert the CreateEventObject decision-making process to a switch structure: 1. If necessary, open the CreateEventObject.java file and change the class name to CreateEventObjectSwitch. Immediately save the file as CreateEventObjectSwitch.java. 2. Delete the if...else statements that currently determine which number the user entered, and then replace them with the following switch structure:
218
C H A P T E R F I V E
switch(eventType) { case PRIVATE_CODE: chosenManager = PRIVATE_MANAGER; chosenRate = PRIVATE_RATE; break; case CORPORATE_CODE: chosenManager = CORP_MANAGER; chosenRate = CORP_RATE; break; case NONPROFIT_CODE: chosenManager = NONPROFIT_MANAGER; chosenRate = NONPROFIT_RATE; break; default: choiceIsGood = false; }
3. Save the file, compile, and test the application. Make certain the correct output appears when you enter 1, 2, 3, or any invalid number as keyboard input.
DON’T DO IT
» Don’t ignore subtleties in boundaries used in decision making. For example, selecting » » » » » » »
employees who make less than $20 an hour is different from selecting employees who make $20 an hour or less. Don’t use the assignment operator instead of the comparison operator when testing for equality. Don’t insert a semicolon after the Boolean expression in an if statement; insert the semicolon after the entire statement is completed. Don’t forget to block a set of statements with curly braces when several statements depend on the if or the else statement. Don’t forget to include a complete Boolean expression on each side of an && or || operator. Don’t try to use a switch structure to test anything other than an integer or character value. Don’t forget a break statement if one is required by the logic of your switch structure. Don’t use the standard relational operators to compare objects; use them only with the built-in Java types. In Chapter 7, you will learn how to compare Strings correctly, and in Chapter 10 you will learn how to compare other objects.
219
MAKING DECISIONS
KEY TERMS Pseudocode is a tool that helps programmers plan a program’s logic by writing plain English statements. A flowchart is a tool that helps programmers plan a program’s logic by writing the steps in diagram form, as a series of shapes connected by arrows. A sequence structure is a logical structure in which one step follows another unconditionally. A decision structure is a logical structure that involves choosing between alternative courses of action based on some value within a program. True or false values are Boolean values; every computer decision results in a Boolean
value. In Java, the simplest statement you can use to make a decision is the if statement; you use it to write a single-alternative decision. The equivalency operator (==) compares values and returns true if they are equal. An empty statement contains only a semicolon. A single-alternative if is a decision structure that performs an action, or not, based on one alternative. A dual-alternative if is a decision structure that takes one of two possible courses of action. In Java, the if...else statement provides the mechanism to perform one action when a Boolean expression evaluates as true, and to perform a different action when a Boolean expression evaluates as false. Statements in which an if structure is contained within another if structure commonly are called nested if statements. You can use the logical AND operator between Boolean expressions to determine whether both are true. The AND operator is written as two ampersands (&&). Short-circuit evaluation describes the feature of the AND and OR operators in which evaluation is performed only as far as necessary to make a final decision. You can use the conditional OR operator between Boolean expressions to determine whether either expression is true. The OR operator is written as two pipes (||). A range check is a series of statements that determine within which of a set of ranges a value falls. The switch statement uses up to four keywords to test a single variable against a series of exact integer or character values. The keywords are switch, case, break, and default. The conditional operator requires three expressions separated with a question mark and a colon, and is used as an abbreviated version of the if...else structure. You use the NOT operator, which is written as an exclamation point (!), to negate the result of any Boolean expression. 220
C H A P T E R F I V E
CHAPTER SUMMARY
» Making a decision involves choosing between two alternative courses of action based on some value within a program.
» You can use the if statement to make a decision based on a Boolean expression that
»
» » » » » »
evaluates as true or false. If the Boolean expression enclosed in parentheses within an if statement is true, the subsequent statement or block executes. A single-alternative if performs an action based on one alternative; a dual-alternative if, or if...else, provides the mechanism for performing one action when a Boolean expression is true and a different action when the expression is false. To execute more than one statement that depends on the evaluation of a Boolean expression, you use a pair of curly braces to place the dependent statements within a block. Within an if or an else statement, you can code as many dependent statements as you need, including other if and else statements. Nested if statements are particularly useful when two conditions must be met before some action occurs. You can use the AND operator (&&) within a Boolean expression to determine whether two expressions are both true. You use the OR operator (||) when you want to carry out some action even if only one of two conditions is true. New programmers frequently cause errors in their if statements when they perform a range check incorrectly or inefficiently, or when they use the wrong operator with AND and OR. You use the switch statement to test a single variable against a series of exact integer or character values. The conditional operator requires three expressions, a question mark, and a colon, and is used as an abbreviated version of the if...else statement. You use the NOT operator (!) to negate the result of any Boolean expression. Operator precedence makes a difference in how expressions are evaluated. You can always use parentheses to change precedence or make your intentions clearer.
REVIEW QUESTIONS 1. The logical structure in which one instruction occurs after another with no branching is a ___________ . a. sequence
c. loop
b. selection
d. case
2. Which of the following is typically used in a flowchart to indicate a decision? a. square
c. diamond
b. rectangle
d. oval
3. Which of the following is not a type of if statement? a. single-alternative if
c. reverse if
b. dual-alternative if
d. nested if 221
MAKING DECISIONS
4. A decision is based on a(n) ___________ value. a. Boolean
c. definitive
b. absolute
d. convoluted
5. In Java, the value of (4 > 7) is ___________ . a. 4
c. true
b. 7
d. false
6. Assuming the variable q has been assigned the value 3, which of the following statements prints XXX? a. if(q > 0) System.out.println("XXX"); b. if(q > 7); System.out.println("XXX"); c. Both of the above statements print XXX. d. Neither of the above statements prints XXX.
7. What is the output of the following code segment? t = 10; if(t > 7) { System.out.print("AAA"); System.out.print("BBB"); } a. AAA
c. AAABBB
b. BBB
d. nothing
8. What is the output of the following code segment? t = 10; if(t > 7) System.out.print("AAA"); System.out.print("BBB"); a. AAA
c. AAABBB
b. BBB
d. nothing
9. What is the output of the following code segment? t = 7; if(t > 7) System.out.print("AAA"); System.out.print("BBB"); a. AAA
c. AAABBB
b. BBB
d. nothing
222
C H A P T E R F I V E
10. When you code an if statement within another if statement, as in the following, then the if statements are ___________ . if(a > b) if(c > d)x = 0;
a. notched
c. nested
b. nestled
d. sheltered
11. The operator that combines two conditions into a single Boolean value that is true only when both of the conditions are true, but is false otherwise, is ___________ . a. $$
c. ||
b. !!
d. &&
12. The operator that combines two conditions into a single Boolean value that is true when at least one of the conditions is true is ___________ . a. $$
c. ||
b. !!
d. &&
13. Assuming a variable f has been initialized to 5, which of the following statements sets g to 0? a. if(f > 6 || f == 5) g = 0; b. if(f < 3 || f > 4) g = 0; c. if(f >= 0 || f < 2) g = 0; d. All of the above statements set g to 0.
14. Which of the following groups has the lowest operator precedence? a. relational
c. addition
b. equality
d. logical OR
15. Which of the following statements correctly prints the names of voters who live in district 6 and all voters who live in district 7? a. if(district == 6 || 7) System.out.println("Name is " + name); b. if(district == 6 || district == 7) System.out.println("Name is " + name); c. if(district = 6 && district == 7) System.out.println("Name is " + name); d. two of these
223
MAKING DECISIONS
16. Which of the following prints “Error” when a student ID is less than 1000 or more than 9999? a. if(stuId < 1000) if(stuId > 9999) System.out.println("Error"); b. if(stuId < 1000 && stuId > 9999) System.out.println("Error"); c. if(stuId < 1000) System.out.println("Error"); else if(stuId > 9999) System.out.println("Error"); d. Two of these are correct.
17. You can use the ___________ statement to terminate a switch structure. a. switch
c. case
b. end
d. break
18. The switch argument within a switch structure requires a(n) ___________ . a. integer value
c. double value
b. character value
d. integer or character value
19. Assuming a variable w has been assigned the value 15, what does the following statement do? w == 15 ? x = 2 : x = 0; a. assigns 15 to w c. assigns 0 to x b. assigns 2 to x
d. nothing
20. Assuming a variable y has been assigned the value 6, the value of !(y < 7)is ___________ . a. 6
c. true
b. 7
d. false
EXERCISES 1. a. Write an application that prompts the user for a checking account balance and a savings account balance. Display the message “Checking account balance is low” if the checking account balance is less than $10. Display the message “Savings account balance is low” if the savings account balance is less than $100. Save the file as Balance.java. b. Modify the application in Exercise 1a to display an additional message, “Both accounts are dangerously low”, if both fall below the specified limits. Save the file as Balance2.java.
224
C H A P T E R F I V E
2. a. Write an application for a furniture company; the program determines the price of a table. Ask the user to choose 1 for pine, 2 for oak, or 3 for mahogany. The output is the name of the wood chosen as well as the price of the table. Pine tables cost $100, oak tables cost $225, and mahogany tables cost $310. If the user enters an invalid wood code, set the price to 0. Save the file as Furniture.java. b. Add a prompt to the application you wrote in Exercise 2a to ask the user to specify a (1) large table or a (2) small table, but only if the wood selection is valid. Add $35 to the price of any large table, and add nothing to the price for a small table. Display an appropriate message if the size value is invalid and assume the price is for a small table. Save the file as Furniture2.java. 3. a. Write an application for a college’s admissions office. Prompt the user for a student’s numeric high school grade point average (for example, 3.2) and an admission test score from 0 to 100. Print the message “Accept” if the student has any of the following:
» A grade point average of 3.0 or above and an admission test score of at least 60 » A grade point average below 3.0 and an admission test score of at least 80 If the student does not meet either of the qualification criteria, print “Reject”. Save the file as Admission.java. b. Modify the application in Exercise 3a so that if a user enters a grade point average under 0 or over 4.0, or a test score under 0 or over 100, an error message appears instead of the “Accept” or “Reject” message. Save the file as Admission2.java. 4. Create a class named CheckingAccount with data fields for an account number and a balance. Include a constructor that takes arguments for each field. The constructor sets the balance to 0 if it is below the required $200.00 minimum for an account. Also include a method that displays account details, including an explanation if the balance was reduced to 0. Write an application named TestAccount in which you instantiate two CheckingAccount objects, prompt the user for values for the account number and balance, and display the values of both accounts. Save both the CheckingAccount.java and TestAccount.java files. 5. a. Write an application that prompts an employee for an hourly pay rate and hours worked. Compute gross pay (hours times rate), withholding tax, and net pay (gross pay minus withholding tax). Withholding tax is computed as a percentage of gross pay based on the following: Gross Pay ($)
Withholding (%)
Up to and including 300.00
10
300.01 and up
12
Save the file as ComputeNet.java.
225
MAKING DECISIONS
b. Modify the application you created in Exercise 5a using the following withholding percentage ranges: Gross Pay ($)
Withholding (%)
0 to 300.00
10
300.01 to 400.00
12
400.01 to 500.00
15
500.01 and over
20
Save the file as ComputeNet2.java. 6. Write an application that prompts the user for two integers and then prompts the user to enter an option as follows: 1 to add the two integers, 2 to subtract the second integer from the first, 3 to multiply the integers, and 4 to divide the first integer by the second. Display an error message if the user enters an option other than 1—4 or if the user chooses the divide option but enters 0 for the second integer. Otherwise, display the results of the arithmetic. Save the file as Calculate.java. 7. a. Write an application for a lawn-mowing service. The lawn-mowing season lasts 20 weeks. The weekly fee for mowing a lot under 4,000 square feet is $25. The fee for a lot that is 4,000 square feet or more, but under 600 square feet, is $35 per week. The fee for a lot that is 6,000 square feet or over is $50 per week. Prompt the user for the length and width of a lawn, and then print the weekly mowing fee, as well as the 20-week seasonal fee. Save the file as Lawn.java. b. To the Lawn application you created in Exercise 7a, add a prompt that asks the user whether the customer wants to pay (1) once, (2) twice, or (3) 20 times per year. If the user enters 1 for once, the fee for the season is simply the seasonal total. If the customer requests two payments, each payment is half the seasonal fee plus a $5 service charge. If the user requests 20 separate payments, add a $3 service charge per week. Display the number of payments the customer must make, each payment amount, and the total for the season. Save the file as Lawn2.java. 8. Write an application that recommends a pet for a user based on the user’s lifestyle. Prompt the user to enter whether he or she lives in an apartment, house, or dormitory (1, 2, or 3) and the number of hours the user is home during the average day. The user will select an hour category from a menu: (1) 18 or more; (2) 10–17; (3) 8–9; (4) 6–7; or (5) 0–5. Print your recommendation based on the following table:
226
C H A P T E R F I V E
Residence
Hours Home
Recommendation
House
18 or more
Pot-bellied pig
House
10 to 17
Dog
House
Fewer than 10
Snake
Apartment
10 or more
Cat
Apartment
Fewer than 10
Hamster
Dormitory
6 or more
Fish
Dormitory
Fewer than 6
Ant farm
Save the file as PetAdvice.java. 9. a. Write an application that displays a menu of three items in a restaurant as follows: (1) Cheeseburger
4.99
(2) Pepsi
2.00
(3) Chips
0.75
Prompt the user to choose an item using the number (1, 2, or 3) that corresponds to the item, or to enter 0 to quit the application. After the user makes the first selection, if the choice is 0, display a bill of $0. Otherwise, display the menu again. The user should respond to this prompt with another item number to order or 0 to quit. If the user types 0, display the cost of the single requested item. If the user types 1, 2, or 3, add the cost of the second item to the first, and then display the menu a third time. If the user types 0 to quit, display the total cost of the two items; otherwise, display the total for all three selections. Save the file as FastFood.java. b. Modify the application in Exercise 9a so that if the user makes a menu selection he or she has already made, ignore the selection—that is, do not add a second price for the same item to the total. The user is still allowed only three entries. Save the file as FastFood2.java. 10. a. Create a class named Invoice that holds an invoice number, balance due, and three fields representing the month, day, and year that the balance is due. Create a constructor that accepts values for all five data fields. Within the constructor, assign each argument to the appropriate field with the following exceptions:
» If an invoice number is less than 1000, force the invoice number to 0. » If the month field is less than 1 or greater than 12, force the month field to 0. » If the day field is less than 1 or greater than 31, force the day field to 0. » If the year field is less than 2009 or greater than 2015, force the year field to 0. In the Invoice class, include a display method that displays all the fields on an Invoice object. Save the file as Invoice.java. 227
MAKING DECISIONS
b. Write an application containing a main() method that declares several Invoice objects, proving that all the statements in the constructor operate as specified. Save the file as TestInvoice.java. c. Modify the constructor in the Invoice class so that the day is not greater than 31, 30, or 28, depending on the month. For example, if a user tries to create an invoice for April 31, force it to April 30. Also, if the month is invalid, and thus forced to 0, also force the day to 0. Save the modified Invoice class as Invoice2.java. Then modify the TestInvoice class to create Invoice2 objects. Create enough objects to test every decision in the constructor. Save this file as TestInvoice2.java. 11. Use the Web to locate the lyrics to the traditional song “The Twelve Days of Christmas.” The song contains a list of gifts received for the holiday. The list is cumulative so that as each “day” passes, a new verse contains all the words of the previous verse, plus a new item. Write an application that displays the words to the song starting with any day the user enters. (Hint: Use a switch statement with cases in descending day order and without any break statements so that the lyrics for any day repeat all the lyrics for previous days.) Save the file as TwelveDays.java. 12. Barnhill Fastener Company runs a small factory. The company employs workers who are paid one of three hourly rates depending on skill level: Skill Level
Hourly Pay Rate ($)
1
17.00
2
20.00
3
22.00
Each factory worker might work any number of hours per week; any hours over 40 are paid at one and one-half times the usual rate. In addition, workers in skill levels 2 and 3 can elect the following insurance options: Option
Explanation
1
Medical insurance
Weekly Cost to Employee ($) 32.50
2
Dental insurance
20.00
3
Long-term disability insurance
10.00
Also, workers in skill level 3 can elect to participate in the retirement plan at 3% of their gross pay. Write an interactive Java payroll application that calculates the net pay for a factory worker. The program prompts the user for skill level and hours worked, as well as appropriate insurance and retirement options for the employee’s skill level category. The application displays: (1) the hours worked, (2) the hourly pay rate, (3) the regular pay for 228
C H A P T E R F I V E
40 hours, (4) the overtime pay, (5) the total of regular and overtime pay, and (6) the total itemized deductions. If the deductions exceed the gross pay, display an error message; otherwise, calculate and display (7) the net pay after all the deductions have been subtracted from the gross. Save the file as Pay.java.
DEBUGGING EXERCISES Each of the following files in the Chapter.05 folder on your Student Disk has syntax and/ or logic errors. In each case, determine the problem and fix the program. After you correct the errors, save each file using the same filename preceded with Fix. For example, save DebugFive1.java as FixDebugFive1.java. a. DebugFive1.java b. DebugFive2.java c. DebugFive3.java d. DebugFive4.java
GAME ZONE 1. In Chapter 1, you created a class called RandomGuess. In this game, players guess a number, the application generates a random number, and players determine whether they were correct. Now that you can make decisions, modify the application so it allows a player to enter a guess before the random number is displayed, and then displays a message indicating whether the player’s guess was correct, too high, or too low. Save the file as RandomGuess2.java. (After you finish Chapter 6, you will be able to modify the application so that the user can continue to guess until the correct answer is entered.) 2. Create a lottery game application. Generate three random numbers (see Appendix D for help in doing so), each between 0 and 9. Allow the user to guess three numbers. Compare each of the user’s guesses to the three random numbers and display a message that includes the user’s guess, the randomly determined three-digit number, and the amount of money the user has won as follows: Matching Numbers Any one matching Two matching Three matching, not in order Three matching in exact order No matches
Award ($) 10 100 1000 1,000,000 0
229
MAKING DECISIONS
Make certain that your application accommodates repeating digits. For example, if a user guesses 1, 2, and 3, and the randomly generated digits are 1, 1, and 1, do not give the user credit for three correct guesses—just one. Save the file as Lottery.java. 3. In Chapter 3, you created a Card class. Modify the Card class so the setValue() method does not allow a Card’s value to be less than 1 or higher than 13. If the argument to setValue() is out of range, assign 1 to the Card’s value. In Chapter 3, you also created a PickTwoCards application that randomly selects two playing cards and displays their values. In that application, all Card objects were arbitrarily assigned a suit represented by a single character, but they could have different values, and the player observed which of two Card objects had the higher value. Now, modify the application so the suit and the value are both chosen randomly. Using two Card objects, play a very simple version of the card game War. Deal two Cards—one for the computer and one for the player—and determine the higher card, then display a message indicating whether the cards are equal, the computer won, or the player won. (Playing cards are considered equal when they have the same value, no matter what their suit is.) For this game, assume the Ace (value 1) is low. Make sure that the two Cards dealt are not the same Card. For example, a deck cannot contain more than one Card representing the 2 of Spades. If two cards are chosen to have the same value, change the suit for one of them. Save the application as War.java. (After you learn about arrays in Chapter 8, you will be able to create a more sophisticated War game in which you use an entire deck without repeating cards.) 4. In Chapter 4, you created a Die class from which you could instantiate an object containing a random value from 1–6. You also wrote an application that randomly “throws” two dice and displays their values. Modify the application so it determines whether the two dice are the same, the first has a higher value, or the second has a higher value. Save the application as TwoDice2.java. 5. In the game Rock Paper Scissors, two players simultaneously choose one of three options: rock, paper, or scissors. If both players choose the same option, then the result is a tie. However, if they choose differently, the winner is determined as follows:
» Rock beats scissors, because a rock can break a pair of scissors. » Scissors beats paper, because scissors can cut paper. » Paper beats rock, because a piece of paper can cover a rock. Create a game in which the computer randomly chooses rock, paper, or scissors. Let the user enter a number 1, 2, or 3, each representing one of the three choices. Then, determine the winner. Save the application as RockPaperScissors.java. (In Chapter 7, you will modify the game so that the user enters a string for “rock”, “paper”, and “scissors”, rather than just entering a number.)
230
C H A P T E R F I V E
TOUGH QUESTIONS 1. What is a quick way to determine whether a value is even or odd? 2. What is the output of the following code? public static void main(String args[]) { int num = 5; if(num > 0) System.out.println("true"); else; System.out.println("false"); }
3. What is the output of the following code? int x = 5; boolean isNumBig = (x > 100); if(isNumBig = true) System.out.println("Number is big"); else System.out.println("Number is not big");
4. What is the output of the following code? public static void main(String args[]) { if(thisMethod() && thatMethod()) System.out.println("Goodbye"); } public static boolean thisMethod() { System.out.println("Hello"); return false; } public static boolean thatMethod() { System.out.println("How are you?"); return true; }
5. Rewrite the following method to work exactly the same way as it does now, using as few words as possible in the method body: public static boolean interesting(boolean value) { if(value == true) { if(value == false) value = false; else value = true; }
231
MAKING DECISIONS
else if(value == false) value = false; else value = true; return value; }
6. What is the output of the following code, assuming that department = 1? switch(department) { case 3: System.out.println("Manufacturing"); case 1: System.out.println("Accounting"); case 2: System.out.println("Human Resources"); }
UP FOR DISCUSSION 1. In this chapter, you learned how computer programs make decisions. Insurance companies use programs to make decisions about your insurability as well as the rates you will be charged for health and life insurance policies. For example, certain preexisting conditions may raise your insurance premiums considerably. Is it ethical for insurance companies to access your health records and then make insurance decisions about you? 2. Job applications are sometimes screened by software that makes decisions about a candidate’s suitability based on keywords in the applications. For example, when a help-wanted ad lists “management experience,” the presence of those exact words might determine which résumés are chosen for further scrutiny. Is such screening fair to applicants? 3. Medical facilities often have more patients waiting for organ transplants than there are available organs. Suppose you have been asked to write a computer program that selects which of several candidates should receive an available organ. What data would you want on file to use in your program, and what decisions would you make based on the data? What data do you think others might use that you would not use?
232
C H A P T E R S I X
6 LOOPING
»
In this chapter, you will: Learn about the loop structure Use a while loop Use shortcut arithmetic operators Use a for loop Learn how and when to use a do...while loop Learn about nested loops Understand how to improve loop performance
233
LOOPING
JAVA ON THE JOB, SCENE 6 “Still having problems?” asks Lynn Greenbrier, who watches intently as you code a new program. “My programs can finally respond to questions and make choices,” you reply. “But I still feel like something is missing.” “It’s probably because you want to do the same task more than once without writing the procedure more than one time,” Lynn suggests. “Let me introduce you to the control structure called looping.”
LEARNING ABOUT THE LOOP STRUCTURE One execution of any loop is called an iteration.
»NOTE
Recall that a block of statements might be a single statement without curly braces, or one or more statements within curly braces.
If making decisions is what makes programs seem smart, looping is what makes programs seem powerful. A loop is a structure that allows repeated execution of a block of statements. Within a looping structure, a Boolean expression is evaluated. If it is true, a block of statements called the loop body executes and the true Boolean expression is evaluated again. As long Boolean loop body expression as the expression is true, the statements in the loop body continue to execute. When the false Boolean evaluation is false, the loop ends. Figure 6-1 shows a diagram of the logic of a Figure 6-1 Flowchart of a loop structure loop. In Java, you can use several mechanisms to create loops. In this chapter, you will learn to use three types of loops:
» A while loop, in which the loop-controlling Boolean expression is the first statement in the loop
» A for loop, which is usually used as a concise format in which to execute loops » A do...while loop, in which the loop-controlling Boolean expression is the last statement in the loop
»TWO TRUTHS AND A LIE: LEARNING ABOUT THE LOOP STRUCTURE 1. A loop is a structure that allows repeated execution of a block of statements as long as a tested expression is true. 2. If a loop’s tested Boolean expression is true, a block of statements called the loop body executes before the Boolean expression is evaluated again. 3. When the Boolean evaluation tested in a loop becomes false, the loop body executes one last time. The false statement is #3. When the Boolean evaluation tested in a loop is false, the loop ends.
»NOTE
234
C H A P T E R S I X
USING A while LOOP TO CREATE A DEFINITE LOOP You can use a while loop to execute a body of statements continually as long as the Boolean expression that controls entry into the loop continues to be true. In Java, a while loop consists of the keyword while followed by a Boolean expression within parentheses, followed by the body of the loop, which can be a single statement or a block of statements surrounded by curly braces. You can use a while loop when you need to perform a task a predetermined number of times. A loop that executes a specific number of times is a definite loop or a counted loop. To write a definite loop, you initialize a loop control variable, a variable whose value determines whether loop execution continues. While the Boolean value that results from comparing the loop control variable and another value is true, the body of the while loop continues to execute. In the body of the loop, you must include a statement that alters the loop control variable. For example, the program segment shown in Figure 6-2 prints the series of integers 1 through 10. The variable val is the loop control variable—it starts the loop holding a value of 1, and while the value remains under 11, the val continues to print and be increased. int val; final int LIMIT = 11; val = 1; while(val < LIMIT) { System.out.println(val); val = val + 1; }
»NOTE
val = 1
yes
val < LIMIT?
print val
val = val + 1
no Figure 6-2 A while loop that prints the integers 1 through 10
When you write applications containing loops, it is easy to make mistakes. For example, executing the code shown in Figure 6-3 causes the message “Hello” to display (theoretically) forever because there is no code to end the loop. A loop that never ends is called an infinite loop.
This loop never will end. while(4 > 2) { System.out.println("Hello"); }
4 > 2? no
Figure 6-3 A loop that displays “Hello” infinitely
235
yes
print “Hello”
To an algebra student, a statement such as val = val + 1; looks wrong—a value can never be one more than itself. In algebra, the equal sign means equivalency. In Java, however, the equal sign assigns a value to the variable on the left. Therefore, val = val + 1; takes the value of val, adds 1 to it, and then assigns the new value back into val.
LOOPING
»NOTE
As an inside joke to programmers, the address of Apple Computer, Inc. is One Infinite Loop, Cupertino, California.
»NOTE
On many keyboards, the Break key is also the Pause key.
»NOTE
An infinite loop might not actually execute infinitely. Depending on the tasks the loop performs, eventually the computer memory might be exhausted (literally and figuratively) and execution might stop. Also, it’s possible that the processor has a time-out feature that forces the loop to end. Either way, and depending on your system, quite a bit of time could pass before the loop stops running.
In Figure 6-3, the expression 4 > 2 evaluates to true. You obviously never need to make such an evaluation, but if you do so in this while loop, the body of the loop is entered and “Hello” displays. Next, the expression is evaluated again. The expression 4 > 2 is still true, so the body is entered again. “Hello” displays repeatedly; the loop never finishes because 4 > 2 is never false. It is a bad idea to intentionally write an infinite loop. However, even experienced programmers write them by accident. So, before you start writing loops, it is good to know how to exit from an infinite loop in the event you find yourself in the midst of one. You might suspect an infinite loop if the same output is displayed repeatedly or if the screen simply remains idle for an extended period of time without displaying the expected output. If you think your application is in an infinite loop, you can press and hold Ctrl, and then press C or Break; the looping program should terminate. To prevent a while loop from executing infinitely, three separate actions must occur:
» A named loop control variable is initialized to a starting value. » The loop control variable is tested in the while statement. » If the test expression is true, the body of the while statement must take some action that alters the value of the loop control variable; the test of the while statement must eventually evaluate to false so that the loop can end.
All of these conditions are met by the example in Figure 6-4. First, a loop control variable loopCount is named and set to a value of 1. Second, the statement while(loopCount < 3) is tested. Third, the loop body is executed because the loop control variable loopCount
is less than 3. Note that the loop body shown in Figure 6-4 consists of two statements made into a block by their surrounding curly braces. The first statement prints “Hello” and then the second statement adds 1 to loopCount. The next time loopCount is evaluated, it is 2. It is still less than 3, so the loop body executes again. “Hello” prints a second time, and loopCount becomes 3. Finally, because the expression loopCount < 3 now evaluates to false, the loop ends. Program execution then continues with any subsequent statements.
236
C H A P T E R S I X
Loop control variable initialized.
loopCount = 1; while(loopCount < 3) { System.out.println("Hello"); loopCount = loopCount + 1; }
Loop control variable tested. Loop control variable altered.
loopCount = 1
loopCount < 3?
yes
print “Hello”
loopCount = loopCount + 1
no Figure 6-4 A while loop that prints “Hello” twice
It is important that the loop control variable be altered within the body of the loop. Figure 6-5 shows the same code as in Figure 6-4, but the curly braces have been eliminated. In this case, the while loop body ends at the semicolon that appears at the end of the “Hello” statement. Adding 1 to the loopCount is no longer part of a block that contains the loop, so the value of loopCount never changes and an infinite loop is created.
loopCount = 1; while(loopCount < 3) System.out.println("Hello"); loopCount = loopCount + 1;
loopCount = 1
This indentation has no effect. Loop control variable is not altered in the loop.
loopCount < 3?
yes
print “Hello”
no loopCount = loopCount + 1
Figure 6-5 A while loop that prints “Hello” infinitely because loopCount is not altered in the loop body
As with the decision making if statement that you learned about in Chapter 5, placement of the statement ending semicolon is important when you work with the while statement. If a semicolon is mistakenly placed at the end of the partial statement while (loopCount < 3);,
237
LOOPING
as shown in Figure 6-6, the loop is also infinite. This loop has an empty body, or a body with no statements in it. So, the Boolean expression is evaluated, and because it is true, the loop body is entered. Because the loop body is empty, no action is taken, and the Boolean expression is evaluated again. Nothing has changed, so it is still true, the empty body is entered, and the infinite loop continues.
This semicolon causes the loop loopCount = 1; to have an empty body. while(loopCount < 3); { System.out.println("Hello"); loopCount = loopCount + 1; }
loopCount = 1
loopCount < 3?
yes
no print “Hello”
loopCount = loopCount + 1
Figure 6-6 A while loop that loops infinitely with no output because the loop body is empty
It is very common to alter the value of a loop control variable by adding 1 to it, or incrementing the variable. However, not all loops are controlled by adding 1. The loop shown in Figure 6-7 prints “Hello” twice, just as the loop in Figure 6-4 does, but its loop is controlled by subtracting 1 from a loop control variable, or decrementing it.
loopCount = 3; while(loopCount > 1) { System.out.println("Hello"); loopCount = loopCount - 1; } Figure 6-7 A while loop that prints “Hello” twice, decrementing the loopCount variable in the loop body
In the program segment shown in Figure 6-7, the variable loopCount begins with a value of 3. The loopCount is greater than 1, so the loop body prints “Hello” and decrements loopCount to 2. The Boolean expression in the while loop is tested again. Because 2 is more than 1, “Hello” prints again and loopCount becomes 1. Now loopCount is not greater than 1,
238
C H A P T E R S I X
so the loop ends. There are many ways to execute a loop two times. For example, you can initialize a loop control variable to 10 and continue to print while the value is greater than 8, decreasing the value by 1 each time you pass through the loop. Similarly, you can initialize the loop control variable to 12, continue while it is greater than 2, and decrease the value by 5 each time. In general, you should not use such unusual methods to count repetitions because they simply make a program confusing. To execute a loop a specific number of times, the clearest and best method is to start the loop control variable at 0 or 1, stop when the loop control variable reaches the appropriate limit, and increment by 1 each time through the loop.
»NOTE
When you first start programming, it seems reasonable to initialize counter values to 1, and that is a workable approach. However, many seasoned programmers start counter values at 0 because they are used to doing so when working with arrays. When you study arrays in Chapter 8, you will learn that their elements are numbered beginning with 0.
»
TWO TRUTHS AND A LIE: USING A while LOOP TO CREATE A DEFINITE LOOP 1. A finite loop executes a specific number of times; an indefinite loop is one that never ends. 2. A well-written while loop contains an initialized loop control variable that is tested in the while expression and then altered in the loop body. 3. When a variable is incremented, 1 is added to it; when it is decremented, 1 is subtracted from it. The false statement is #1. A loop that executes a specific number of times is a definite loop or a counted loop; a loop that never ends is an infinite loop.
USING A while LOOP TO CREATE AN INDEFINITE LOOP Within a loop, you are not required to alter the loop control variable by adding to it or subtracting from it. Often, the value of a loop control variable is not altered by arithmetic, but instead is altered by user input. For example, perhaps you want to continue performing some task as long as the user indicates a desire to continue. In this case, while you are writing the program, you do not know whether the loop eventually will be executed two times, 200 times, or at all. Unlike a loop that you program to execute a fixed number of times, a loop controlled by the user is a type of indefinite loop because you don’t know how many times it will eventually loop. Consider an application in which you ask the user for a bank balance and then ask whether the user wants to see the balance after interest has accumulated for each year. Each time the user chooses to continue, an increased balance appears, reflecting one more year of
239
»NOTE
A definite loop is a counter-controlled loop. An indefinite loop is an eventcontrolled loop; that is, an event occurs that determines whether the loop continues.
LOOPING
accumulated interest. When the user finally chooses to exit, the program ends. The program appears in Figure 6-8.
import java.util.Scanner; public class BankBalance { public static void main(String[] args) { double balance; String response; char responseChar; int tempBalance; int year = 1; final double INT_RATE = 0.03; Scanner keyboard = new Scanner(System.in); In Chapter 2, you learned to call System.out.print("Enter initial bank balance > "); nextLine()after numeric input so balance = keyboard.nextDouble(); that the Enter key is consumed before using the next call to nextLine(). keyboard.nextLine(); System.out.println("Do you want to see next year's balance?"); System.out.print("Enter y or n > "); response = keyboard.nextLine(); The call to charAt(0)retrieves the first responseChar = response.charAt(0); character from response. while(responseChar == 'y') { balance = balance + balance * INT_RATE; These two statements round the balance to two decimal places. tempBalance = (int)(balance * 100); balance = tempBalance / 100.0; System.out.println("After year " + year + " at " + INT_RATE + " interest rate, balance is $" + balance); year = year + 1; System.out.print("Do you want to see the balance " + "\nat the end of another year? y or n? >"); response = keyboard.nextLine(); responseChar = response.charAt(0); } } } Figure 6-8 The BankBalance application
The program shown in Figure 6-8 declares needed variables and a constant for a 3% interest rate, and then asks the user for a balance. The application accepts a user’s answer from the keyboard as a String, and then uses the first character of the String to determine whether the loop should continue. As long as the user wants to continue, the application continues to display increasing bank balances. 240
C H A P T E R S I X
The loop in the application in Figure 6-8 begins with the line that contains: while(responseChar == 'y')
If the user enters any value other than ‘y’, the loop body never executes; instead, the program ends. However, if the user enters ‘y’, all the statements within the loop body execute. The application increases the balance by the interest rate value. Then, the balance times 100 is cast to an integer (for example, a calculated balance of 10.635 becomes 1063), and the result is divided by 100 (for example, 1063 becomes 10.63). The net effect of these two statements is to limit the number of decimal places in the balance to two. After these calculations, the application displays the new balance and asks whether the user wants another balance. The year variable increases and the loop body ends with a closing curly brace. After the loop body executes, control returns to the top of the loop, where the Boolean expression in the while loop is tested again. If the user enters ‘y’ to continue, the loop is entered and the process begins again. Figure 6-9 shows the output of the BankBalance application after the user enters a $575.00 starting balance and responds with ‘y’ five times to the prompt for increased interest payments.
Figure 6-9 Typical execution of the BankBalance application
Programmers commonly use indefinite loops when validating input data. Validating data is the process of ensuring that a value falls within a specified range. For example, suppose you require a user to enter a value no greater than 3. Figure 6-10 shows an application that does not progress past the data entry loop until the user enters a correct value. If the user enters 3 or less at the first prompt, the shaded loop never executes. However, if the user enters a number greater than 3, the shaded loop executes, providing the user with another chance to enter a correct value. While the user continues to enter incorrect data, the loop repeats. Figure 6-11 shows a typical execution. 241
»NOTE
You first learned about type casting in Chapter 2.
LOOPING
import java.util.Scanner; public class EnterSmallValue { public static void main(String[] args) { int userEntry; final int LIMIT = 3; Scanner input = new Scanner(System.in); System.out.print("Please enter an integer no higher than " + LIMIT + " > "); userEntry = input.nextInt(); while(userEntry > LIMIT) { System.out.println("The number you entered was too high"); System.out.print("Please enter an integer no higher than " + LIMIT + " > "); userEntry = input.nextInt(); } System.out.println("You correctly entered " + userEntry); } } Figure 6-10 The EnterSmallValue application
Figure 6-11 Typical execution of the EnterSmallValue program
»NOTE
Figure 6-10 illustrates an excellent method for validating input. Before the loop is entered, the first input is retrieved. This first input might be a value that prevents any executions of the loop. This first input statement prior to the loop is called a priming read or priming input. Within the loop, the last statement retrieves subsequent input values for the same variable that will be checked at the entrance to the loop.
Novice programmers often make the mistake of checking for invalid data using a decision instead of a loop. That is, they ask whether the data is invalid using an if statement; if the data is invalid, they reprompt the user. However, they forget that a user might enter incorrect data multiple times. Usually, a loop is the best structure to use when validating input data. 242
C H A P T E R S I X
»
TWO TRUTHS AND A LIE: USING A while LOOP TO CREATE AN INDEFINITE LOOP 1. To avoid creating an infinite loop, you must alter the loop control variable arithmetically within the loop body. 2. In an indefinite loop, you don’t know how many times the loop will occur. 3. Validating data is the process of ensuring that a value falls within a specified range. The false statement is #1. Within a loop, you are not required to alter the loop control variable by adding to it or subtracting from it. Often, the value of a loop control variable is not altered by arithmetic, but instead is altered by user input.
USING SHORTCUT ARITHMETIC OPERATORS Programmers commonly need to increase the value of a variable in a program. As you saw in the previous section, many loops are controlled by continually adding 1 to some variable, as in count = count + 1;. Incrementing a variable in a loop to keep track of the number of occurrences of some event is also known as counting. Similarly, in the looping bank balance program shown in Figure 6-8, the program not only incremented the year variable by adding 1, but also increased a bank balance by an interest amount with the statement balance = balance + balance * INT_RATE;. In other words, the bank balance became its old value plus a new interest amount; the process of repeatedly increasing a value by some amount is known as accumulating. Because increasing a variable is so common, Java provides you with several shortcuts for incrementing and accumulating. The statement count += 1; is identical in meaning to count = count + 1. The += is the add and assign operator; it adds and assigns in one operation. Similarly, balance += balance * INT_RATE; increases a balance by the INT_RATE percentage. Besides using the shortcut operator +=, you can use the subtract and assign operator (-=), the multiply and assign operator (*=), the divide and assign operator (/=), and the remainder and assign operator (%=). Each of these operators is used to perform the operation and assign the result in one step. For example, balanceDue -= payment subtracts payment from balanceDue and assigns the result to balanceDue. When you want to increase a variable’s value by exactly 1, you can use two other shortcut operators—the prefix ++, also known as the prefix increment operator, and the postfix ++, also known as the postfix increment operator. To use a prefix ++, you type two plus signs before the variable name. The statement someValue = 6; followed by ++someValue; results in someValue holding 7—one more than it held before you applied the ++. To use a postfix ++, you type two plus signs just after a variable name. The statements anotherValue = 56; anotherValue++; result in anotherValue containing 57. Figure 6-12 shows four ways you can increase a value by 1; each method produces the same result. You are never required to use shortcut operators; they are merely a convenience. 243
LOOPING
int value; value = 24; ++value; // Result: value is 25 value = 24; value++; // Result: value is 25 value = 24; value = value + 1; // Result: value is 25 value = 24; value += 1; // Result: value is 25 Figure 6-12 Four ways to add 1 to a value
»NOTE
You can use the prefix ++ and postfix ++ with variables, but not with constants. An expression such as ++84; is illegal because an 84 must always remain an 84. However, you can create a variable as int val = 84 and then write ++val; or val++; to increase the variable’s value.
»NOTE
The prefix and postfix increment operators are unary operators because you use them with one value. As you learned in Chapter 2, most arithmetic operators, such as those used for addition and multiplication, are binary operators—they operate on two values. Other examples of unary operators include the cast operator, as well as + and – when used to indicate positive and negative values.
When you simply want to increase a variable’s value by 1, there is no difference between using the prefix and postfix increment operators. For example, when value is set to 24 in Figure 6-12, both ++value and value++ result in value becoming 25; each operator results in increasing the variable by 1. However, these operators do function differently in terms of when the increment operation occurs. When you use the prefix ++, the result is calculated and stored, and then the variable is used. For example, if b = 4 and c = ++b, the result is that both b and c hold the value 5. When you use the postfix ++, the variable is used, and then the result is calculated and stored. For example, if b = 4 and c = b++, 4 is assigned to c, and then after the assignment, b is increased and takes the value 5. In other words, if b = 4, the value of b++ is also 4, but after the statement is completed, the value of b is 5. If d = 8 and e = 8, both ++d == 9 and e++ == 8 are true expressions. Figure 6-13 shows an application that illustrates the difference between how the prefix and postfix increment operators work. Notice from the output in Figure 6-14 that when the prefix increment operator is used on myNumber, the value of myNumber increases from 17 to 18, and the result is stored in answer, which also becomes 18. After the value is reset to 17, the postfix increment operator is used; 17 is assigned to answer, and myNumber is incremented to 18.
244
C H A P T E R S I X
public class IncrementDemo { public static void main(String[] args) { int myNumber, answer; myNumber = 17; System.out.println("Before incrementing, myNumber is " + myNumber); answer = ++myNumber; System.out.println("After prefix increment, myNumber is " + myNumber); System.out.println(" and answer is " + answer); myNumber = 17; System.out.println("Before incrementing, myNumber is " + myNumber); answer = myNumber++; System.out.println("After postfix increment, myNumber is " + myNumber); System.out.println(" and answer is " + answer); } } Figure 6-13 The IncrementDemo application
Figure 6-14 Output of the IncrementDemo application
Similar logic can be applied when you use the prefix and postfix decrement operators. For example, if b = 4 and c = b--, 4 is assigned to c, and then after the assignment, b is decreased and takes the value 3. If b = 4 and c = --b, b is decreased to 3 and 3 is assigned to c.
»TWO TRUTHS AND A LIE: USING SHORTCUT ARITHMETIC OPERATORS 1. Assume x = 4 and y = 5. The value of ++y + ++x is 11. 2. Assume x = 4 and y = 5. The value of y == x++ is true. 3. Assume x = 4 and y = 5. The value of y += x is 9. The false statement is #2. If x is 4 and y is 5, then the value of x++ is 4, and so y is not equal to 4.
245
LOOPING
USING A for LOOP
»NOTE
A for loop provides a convenient way to create a countercontrolled loop.
A for loop is a special loop that is used when a definite number of loop iterations is required. Although a while loop can also be used to meet this requirement, the for loop provides you with a shorthand notation for this type of loop. When you use a for loop, you can indicate the starting value for the loop control variable, the test condition that controls loop entry, and the expression that alters the loop control variable—all in one convenient place. You begin a for loop with the keyword for followed by a set of parentheses. Within the parentheses are three sections separated by exactly two semicolons. The three sections are usually used for the following:
» Initializing the loop control variable » Testing the loop control variable » Updating the loop control variable The body of the for statement follows the parentheses. As with an if statement or a while loop, you can use a single statement as the body of a for loop, or you can use a block of statements enclosed in curly braces. The for statement shown in Figure 6-15 produces the same output as the while statement shown below it— both print the integers 1 through 10.
for(int val = 1; val < 11; ++val) System.out.println(val); int val = 1; while(val < 11) { System.out.println(val); ++val; } Figure 6-15 A for loop and a while loop that print the integers