
11,879 3,759 58MB
Pages 978 Page size 252 x 312.48 pts Year 2011
This is an electronic version of the print textbook. Due to electronic rights restrictions, some third party content may be suppressed. Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. The publisher reserves the right to remove content from this title at any time if subsequent rights restrictions require it. For valuable information on pricing, previous editions, changes to current editions, and alternate formats, please visit www.cengage.com/highered to search by ISBN#, author, title, or keyword for materials in your areas of interest.
SIXTH EDITION
JAVA
TM
PROGRAMMING
JOYCE FARRELL
Australia l Brazil l Japan l Korea l Mexico l Singapore l Spain l United Kingdom l United States
Java Programming, Sixth Edition Joyce Farrell Executive Editor: Marie Lee Acquisitions Editor: Brandi Shailer Senior Product Manager: Alyssa Pratt Development Editor: Dan Seiter Editorial Assistant: Jacqueline Lacaire Associate Marketing Manager: Shanna Shelton Senior Content Project Manager: Jill Braiewa Art Director: Faith Brosnan Cover Designer: Bruce Bond Cover Photo: ªistockphoto.com/ Dimitrije Print Buyer: Julio Esperas Copyeditor: Mark Goodin
© 2012 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 cengage.com/permissions Further permissions questions can be e-mailed to [email protected] Library of Congress Control Number: 2010941935 ISBN-13: 978-1-111-52944-4
Proofreader: Suzanne Huizenga
ISBN-10: 1-111-52944-2
Indexer: Liz Cunningham
Course Technology 20 Channel Center Street Boston, MA 02210
Compositor: Integra Software Services
Microsoft® is a registered trademark of the Microsoft Corporation. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners. 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. Any fictional data related to people, companies, or URLs used throughout this book is intended for instructional purposes only. At the time this book was printed, any such data was fictional and not belonging to any real people or companies. 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. The programs in this book are for instructional purposes only. They have been tested with care, but are not guaranteed for any particular intent beyond educational purposes. The author and the publisher do not offer any warranties or representations, nor do they accept any liabilities with respect to the programs. Cengage Learning is a leading provider of customized learning solutions with office locations around the globe, including Singapore, the United Kingdom, Australia, Mexico, Brazil, and Japan. Locate your local office at: www.cengage.com/global Cengage Learning products are represented in Canada by Nelson Education, Ltd. To learn more about Course Technology, visit www.cengage.com/coursetechnology Purchase any of our products at your local college store or at our preferred online store: www.cengagebrain.com
Printed in the United States of America 1 2 3 4 5 6 7 17 16 15 14 13 12 11
Brief Contents iii
Preface
. . . . . . . . . . . . . . . . . . . . . xviii
CHAPTER 1
Creati ng Your First Java Classes
. . . . . . . . . . .1
CHAPTER 2
Using Data
CHAPTER 3
Using Methods, Classes, and Objects
CHAPTER 4
More Object Concepts
CHAPTER 5
Making Decisions
CHAPTER 6
Looping . . . . . . . . . . . . . . . . . . . . . 259
CHAPTER 7
Characters, Strings, and the StringBuilder . . . 301
CHAPTER 8
Arrays
CHAPTER 9
Advanced Array Concepts . . . . . . . . . . . . . 381
CHAPTER 10
Introduction to Inheritance
CHAPTER 11
Advanced Inheritance Concepts
CHAPTER 12
Exception Handl ing . . . . . . . . . . . . . . . . 519
CHAPTER 13
File Input and Output . . . . . . . . . . . . . . . 579
CHAPTER 14
Introduction to Swing Components
CHAPTER 15
Advanced GUI Topics . . . . . . . . . . . . . . . 699
CHAPTER 16
Graphics
CHAPTER 17
Applets, Images, and Sound . . . . . . . . . . . . 825
APPENDIX A
Working with the Java Platform
APPENDIX B
Learning About Data Representation . . . . . . . . 877
APPENDIX C
Formatting Output
APPENDIX D
Generating Random Numbers
APPENDIX E
Javadoc . . . . . . . . . . . . . . . . . . . . . 905
. . . . . . . . . . . . . . . . . . . . 51 . . . . . . . 103
. . . . . . . . . . . . . . 157
. . . . . . . . . . . . . . . . 211
. . . . . . . . . . . . . . . . . . . . . 341
. . . . . . . . . . . . 425 . . . . . . . . . . 469
. . . . . . . . 643
. . . . . . . . . . . . . . . . . . . . 769
. . . . . . . . . . 869
. . . . . . . . . . . . . . . . 885 . . . . . . . . . . . 897
Glossary . . . . . . . . . . . . . . . . . . . . . 913 Index
. . . . . . . . . . . . . . . . . . . . . . 937
Contents iv
Preface C H AP T E R 1
. . . . . . . . . . . . . . . . . xviii
Creating Your First Java Classes . . . . . . . . 1 Learning About Programming . . . . . . . . . . . . . Comparing Procedural and Object-Oriented Programming Concepts . . . . . . . . . . . . . . . Procedural Programming . . . . . . . . . . . . . . Object-Oriented Programming . . . . . . . . . . . . Understanding Classes, Objects, and Encapsulation . . . Understanding Inheritance and Polymorphism . . . . . . Features of the Java Programming Language . . . . . . . Java Program Types . . . . . . . . . . . . . . . . Analyzing a Java Application that Produces Console Output . Understanding the Statement that Produces the Output . Understanding the First Class . . . . . . . . . . . Indent Style . . . . . . . . . . . . . . . . . . . . Understanding the main() Method . . . . . . . . . . Adding Comments to a Java Class . . . . . . . . . . . Saving, Compiling, Running, and Modifying a Java Application Saving a Java Class . . . . . . . . . . . . . . . . Compiling a Java Class . . . . . . . . . . . . . . . Running a Java Application . . . . . . . . . . . . . Modifying a Java Class . . . . . . . . . . . . . . . Creating a Java Application that Produces GUI Output . . . Correcting Errors and Finding Help . . . . . . . . . . . You Do It . . . . . . . . . . . . . . . . . . . . . . Your First Application . . . . . . . . . . . . . . . . Adding Comments to a Class . . . . . . . . . . . . Modifying a Class . . . . . . . . . . . . . . . . . Creating a Dialog Box . . . . . . . . . . . . . . . Don’t Do It . . . . . . . . . . . . . . . . . . . . . Key Terms . . . . . . . . . . . . . . . . . . . . . Chapter Summary . . . . . . . . . . . . . . . . . . Review Questions . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2 5 .5 .6 .7 .9 10 12 13 13 15 18 19 21 23 23 23 25 25 27 29 33 33 34 35 36 37 39 42 43
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 46 Debugging Exercise . . . . . . . . . . . . . . . . . . . 48 Game Zone . . . . . . . . . . . . . . . . . . . . . . . 48 C H AP T E R 2
Using Data . . . . . . . . . . . . . . . . . 51 Using Constants and Variables . . . . . . . . . . . . . . . Declaring Variables . . . . . . . . . . . . . . . . . . . Declaring Named Constants . . . . . . . . . . . . . . . The Scope of Variables and Constants . . . . . . . . . . Pitfall: Forgetting That a Variable Holds One Value at a Time . Learning About Integer Data Types . . . . . . . . . . . . . Using the boolean Data Type . . . . . . . . . . . . . . . Learning About Floating-Point Data Types . . . . . . . . . . Working with the char Data Type . . . . . . . . . . . . . Displaying Data and Performing Arithmetic . . . . . . . . . . Performing Arithmetic . . . . . . . . . . . . . . . . . Writing Arithmetic Statements Efficiently . . . . . . . . . . Pitfall: Not Understanding Imprecision in Floating-Point Numbers Understanding Numeric Type Conversion . . . . . . . . . . Using the Scanner Class for Keyboard Input . . . . . . . . Pitfall: Using nextLine() Following One of the Other Scanner Input Methods . . . . . . . . . . . . Using the JOptionPane Class for GUI Input . . . . . . . . . Using Input Dialog Boxes . . . . . . . . . . . . . . . . Using Confirm Dialog Boxes . . . . . . . . . . . . . . . You Do It . . . . . . . . . . . . . . . . . . . . . . . . Working with Numeric Values . . . . . . . . . . . . . . Accepting User Data . . . . . . . . . . . . . . . . . . Performing Arithmetic . . . . . . . . . . . . . . . . . Experimenting with Java Programs . . . . . . . . . . . . Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . Key Terms . . . . . . . . . . . . . . . . . . . . . . . Chapter Summary . . . . . . . . . . . . . . . . . . . . Review Questions . . . . . . . . . . . . . . . . . . . . Exercises . . . . . . . . . . . . . . . . . . . . . . . Debugging Exercise . . . . . . . . . . . . . . . . . . Game Zone . . . . . . . . . . . . . . . . . . . . . .
C H AP T E R 3
. . . . . . . . . . . . . . .
52 53 54 56 56 57 59 61 62 67 69 71 71 73 76
. 78 . 81 . 81 . 85 . 87 . 87 . 89 . 90 . 91 . 92 . 93 . 96 . 97 100 102 102
Using Methods, Classes, and Objects . . . . 103 Creating Methods . . . . . . . . . . . . . . . . . . . . 104 Adding Parameters to Methods . . . . . . . . . . . . . . . 108 Creating Methods That Require Multiple Parameters . . . . . 112
v
CONTENTS
Creating Methods That Return Values . . . . . . . . . . . Chaining Method Calls . . . . . . . . . . . . . . . . Learning About Class Concepts . . . . . . . . . . . . . Creating a Class . . . . . . . . . . . . . . . . . . . . Creating Instance Methods in a Class . . . . . . . . . . . Declaring Objects and Using Their Methods . . . . . . . . Understanding Data Hiding . . . . . . . . . . . . . . Organizing Classes . . . . . . . . . . . . . . . . . . . An Introduction to Using Constructors . . . . . . . . . . . Understanding that Classes are Data Types . . . . . . . . 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 . . . . . . . . . . . . Don’t Do It . . . . . . . . . . . . . . . . . . . . . . Key Terms . . . . . . . . . . . . . . . . . . . . . . Chapter Summary . . . . . . . . . . . . . . . . . . . Review Questions . . . . . . . . . . . . . . . . . . . Exercises . . . . . . . . . . . . . . . . . . . . . . Debugging Exercise . . . . . . . . . . . . . . . . . Game Zone . . . . . . . . . . . . . . . . . . . . .
vi
C H AP T E R 4
More Object Concepts
. . . . . . . . . . .
114 117 118 120 123 126 128 129 132 134 137
. 137 . 139 . . . . . . . . . . . .
140 142 143 144 145 145 146 148 149 151 154 154
. . . . . . . . . . 157
Understanding Blocks and Scope . . . . . . . . . . . . . . Overloading a Method . . . . . . . . . . . . . . . . . . Learning About Ambiguity . . . . . . . . . . . . . . . . . Using Constructors with Parameters . . . . . . . . . . . . Overloading Constructors . . . . . . . . . . . . . . . . Learning About the this Reference . . . . . . . . . . . . Using the this Reference to Make Overloaded Constructors More Efficient . . . . . . . . . . . . . . . . . . . . Using static Variables . . . . . . . . . . . . . . . . . Using Constant Fields . . . . . . . . . . . . . . . . . . Using Automatically Imported, Prewritten Constants and Methods . . Using the GregorianCalendar Class . . . . . . . . . . Understanding Composition . . . . . . . . . . . . . . . . A Brief Look at Nested and Inner Classes . . . . . . . . . .
158 165 167 171 172 173 176 178 181 182 184 189 191
You Do It . . . . . . . . . . . . . . . . . Demonstrating Scope . . . . . . . . . . Overloading Methods . . . . . . . . . . . Creating Overloaded Constructors . . . . . Using an Explicitly Imported Prewritten Class . Creating an Interactive Application with a Timer Don’t Do It . . . . . . . . . . . . . . . . Key Terms . . . . . . . . . . . . . . . . Chapter Summary . . . . . . . . . . . . . Review Questions . . . . . . . . . . . . . Exercises . . . . . . . . . . . . . . . . Debugging Exercise . . . . . . . . . . . Game Zone . . . . . . . . . . . . . . .
C H AP T E R 5
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
193 193 195 196 198 199 201 201 202 203 206 208 209
Making Decisions . . . . . . . . . . . . . 211 Planning Decision-Making Logic . . . . . . . . . . . . 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 . . . . . . . . . . . . . . Using Multiple Statements in an if or if … else Structure . Nesting if and if … else Statements . . . . . . . . . Using Logical AND and OR Operators . . . . . . . . . . Making Accurate and Efficient Decisions . . . . . . . . . Using && and || Appropriately . . . . . . . . . . . . Using the switch Statement . . . . . . . . . . . . . Using the Conditional and NOT Operators . . . . . . . . Using the NOT Operator . . . . . . . . . . . . . . Understanding Operator Precedence . . . . . . . . . . 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 . . . . . . . . . . . . Don’t Do It . . . . . . . . . . . . . . . . . . . . . Key Terms . . . . . . . . . . . . . . . . . . . . . Chapter Summary . . . . . . . . . . . . . . . . . . Review Questions . . . . . . . . . . . . . . . . . .
. . 212 . . 214 . . 215 . . 216 . . . . . . . . . . . . .
. . . . . . . . . . . . .
216 217 218 222 225 227 231 232 236 237 238 241 241
. . . . . . .
. . . . . . .
242 243 246 246 247 248 249
vii
CONTENTS
Exercises . . . . . . . . . . . . . . . . . . . . . . . 252 Debugging Exercise . . . . . . . . . . . . . . . . . . 256 Game Zone . . . . . . . . . . . . . . . . . . . . . . 256
viii
C H AP T E R 6
Looping . . . . . . . . . . . . . . . . . 259 Learning About the Loop Structure . . . . . . . . . . . . Creating while Loops . . . . . . . . . . . . . . . . . Writing a Definite while Loop . . . . . . . . . . . . Writing an Indefinite while Loop . . . . . . . . . . . . Using Shortcut Arithmetic Operators . . . . . . . . . . . Creating a for Loop . . . . . . . . . . . . . . . . . . Learning How and When to Use a do…while Loop . . . . . Learning About Nested Loops . . . . . . . . . . . . . . Improving Loop Performance . . . . . . . . . . . . . . Avoiding Unnecessary Operations . . . . . . . . . . . . Considering the Order of Evaluation of Short-Circuit Operators Comparing to Zero . . . . . . . . . . . . . . . . . . Employing Loop Fusion . . . . . . . . . . . . . . . . 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 . . . . . . . . . . . . . . Don’t Do It . . . . . . . . . . . . . . . . . . . . . . Key Terms . . . . . . . . . . . . . . . . . . . . . . Chapter Summary . . . . . . . . . . . . . . . . . . . Review Questions . . . . . . . . . . . . . . . . . . . Exercises . . . . . . . . . . . . . . . . . . . . . . Debugging Exercise . . . . . . . . . . . . . . . . . Game Zone . . . . . . . . . . . . . . . . . . . . .
C H AP T E R 7
Characters, Strings, and the StringBuilder
. . . . . . . . . . . . . . . . . . . . . . . . .
260 261 261 266 270 273 275 278 281 281 282 282 284 285 285 286 288 289 290 291 292 293 296 298 298
. . . 301
Understanding String Data Problems . . . . . . . . . . Manipulating Characters . . . . . . . . . . . . . . . Declaring and Comparing String Objects . . . . . . . . Comparing String Values . . . . . . . . . . . . . Using Other String Methods . . . . . . . . . . . . . Converting Strings to Numbers . . . . . . . . . . . Learning About the StringBuilder and StringBuffer Classes . . . . . . . . . . . . . . . . . . . . . You Do It . . . . . . . . . . . . . . . . . . . . . . Using String Class Methods . . . . . . . . . . . .
. . . . . .
. . . . . .
302 303 307 308 312 316
. . 319 . . 324 . . 324
Converting a String to an Integer Using StringBuilder Methods Don’t Do It . . . . . . . . . . . Key Terms . . . . . . . . . . . Chapter Summary . . . . . . . . Review Questions . . . . . . . . Exercises . . . . . . . . . . . Debugging Exercise . . . . . . Game Zone . . . . . . . . . . C H AP T E R 8
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
326 327 329 329 331 331 334 337 337
Arrays . . . . . . . . . . . . . . . . . . 341 Declaring and Initializing an Array . . . . . . . . . . . . Initializing an Array . . . . . . . . . . . . . . . . . Using Subscripts with an Array . . . . . . . . . . . . . Declaring and Using Arrays of Objects . . . . . . . . . . Using the Enhanced for Loop . . . . . . . . . . . . Manipulating Arrays of Strings . . . . . . . . . . . Searching an Array . . . . . . . . . . . . . . . . . . Searching an Array for a Range Match . . . . . . . . . Passing Arrays to and Returning Arrays from Methods . . . Returning an Array from a Method . . . . . . . . . . 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 . . . . . . . . . . . . Don’t Do It . . . . . . . . . . . . . . . . . . . . . Key Terms . . . . . . . . . . . . . . . . . . . . . Chapter Summary . . . . . . . . . . . . . . . . . . Review Questions . . . . . . . . . . . . . . . . . . Exercises . . . . . . . . . . . . . . . . . . . . . Debugging Exercise . . . . . . . . . . . . . . . . Game Zone . . . . . . . . . . . . . . . . . . . .
C H AP T E R 9
. . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
342 344 346 349 350 350 352 356 359 362 363 363 363 364 364 366
. . . . . . . . .
. . . . . . . . .
367 369 370 371 372 372 375 378 378
Advanced Array Concepts . . . . . . . . . 381 Sorting Array Elements . . . . . . . . . . . . . . . . . . 382 Sorting Arrays of Objects . . . . . . . . . . . . . . . . 385 Using Two-Dimensional and Other Multidimensional Arrays . . . 388
ix
CONTENTS
Passing a Two-Dimensional Array to a Method . . . . Using the length Field with a Two-Dimensional Array Understanding Ragged Arrays . . . . . . . . . . . Using Other Multidimensional Arrays . . . . . . . . Using the Arrays Class . . . . . . . . . . . . . . Using the ArrayList Class . . . . . . . . . . . . Understanding the Limitations of the ArrayList Class Creating Enumerations . . . . . . . . . . . . . . . You Do It . . . . . . . . . . . . . . . . . . . . . Using a Two-Dimensional Array . . . . . . . . . . . Using Arrays Class Methods . . . . . . . . . . . Creating Enumerations . . . . . . . . . . . . . . Don’t Do It . . . . . . . . . . . . . . . . . . . . Key Terms . . . . . . . . . . . . . . . . . . . . Chapter Summary . . . . . . . . . . . . . . . . . Review Questions . . . . . . . . . . . . . . . . . Exercises . . . . . . . . . . . . . . . . . . . . Debugging Exercise . . . . . . . . . . . . . . . Game Zone . . . . . . . . . . . . . . . . . . .
x
C H AP T E R 1 0
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
390 391 392 392 393 398 403 404 409 409 411 413 415 415 416 417 420 421 421
Introduction to Inheritance . . . . . . . . . 425 Learning About the Concept of Inheritance . . . . . . . . . . Inheritance Terminology . . . . . . . . . . . . . . . . . Extending Classes . . . . . . . . . . . . . . . . . . . . Overriding Superclass Methods . . . . . . . . . . . . . . Calling Constructors During Inheritance . . . . . . . . . . . Using Superclass Constructors That Require Arguments . . . Accessing Superclass Methods . . . . . . . . . . . . . . Comparing this and super . . . . . . . . . . . . . . Employing Information Hiding . . . . . . . . . . . . . . . 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 . You Do It . . . . . . . . . . . . . . . . . . . . . . . . Creating a Superclass and an Application to Use It . . . . . Creating a Subclass and an Application to Use It . . . . . . Understanding the Role of Constructors in Inheritance . . . . Inheritance When the Superclass Requires Constructor Arguments . . . . . . . . . . . . . . . . Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . Key Terms . . . . . . . . . . . . . . . . . . . . . . . Chapter Summary . . . . . . . . . . . . . . . . . . . .
426 429 430 432 434 436 438 440 441 443 443 446 448 450 450 452 454 456 458 458 459
Review Questions . . Exercises . . . . . Debugging Exercise Game Zone . . . . C H AP T E R 1 1
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
Advanced Inheritance Concepts
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
460 463 467 467
. . . . . . 469
Creating and Using Abstract Classes . . . . . . . Using Dynamic Method Binding . . . . . . . . . . Using a Superclass as a Method Parameter Type . Creating Arrays of Subclass Objects . . . . . . . Using the Object Class and Its Methods . . . . . Using the toString() Method . . . . . . . . Using the equals() Method . . . . . . . . . Using Inheritance to Achieve Good Software Design . Creating and Using Interfaces . . . . . . . . . . Creating Interfaces to Store Related Constants . . Creating and Using Packages . . . . . . . . . . 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 . . . . . . . . . . . Using an Interface . . . . . . . . . . . . . . Creating a Package . . . . . . . . . . . . . Don’t Do It . . . . . . . . . . . . . . . . . . Key Terms . . . . . . . . . . . . . . . . . . Chapter Summary . . . . . . . . . . . . . . . Review Questions . . . . . . . . . . . . . . . Exercises . . . . . . . . . . . . . . . . . . Debugging Exercise . . . . . . . . . . . . . Game Zone . . . . . . . . . . . . . . . . . C H AP T E R 1 2
. . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .
470 474 476 477 479 480 483 486 487 492 494 496 496 497 499 500 501 502 504 507 507 508 509 512 516 516
Exception Handling . . . . . . . . . . . . 519 Learning About Exceptions . . . . . . . . . . . Trying Code and Catching Exceptions . . . . . . Throwing and Catching Multiple Exceptions . . . Using the finally Block . . . . . . . . . . . . Understanding the Advantages of Exception Handling Specifying the Exceptions a Method Can Throw . . Tracing Exceptions Through the Call Stack . . . Creating Your Own Exceptions . . . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
520 525 530 534 537 539 544 548
xi
CONTENTS
Using Assertions . . . . . . . . . . . . . . . . . . . You Do It . . . . . . . . . . . . . . . . . . . . . . Throwing and Catching Exceptions . . . . . . . . . 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 . . . . . Creating an Exception Class . . . . . . . . . . . Using an Exception You Created . . . . . . . . . . Don’t Do It . . . . . . . . . . . . . . . . . . . . . Key Terms . . . . . . . . . . . . . . . . . . . . . Chapter Summary . . . . . . . . . . . . . . . . . . Review Questions . . . . . . . . . . . . . . . . . . Exercises . . . . . . . . . . . . . . . . . . . . . Debugging Exercise . . . . . . . . . . . . . . . . Game Zone . . . . . . . . . . . . . . . . . . . .
xii
C H AP T E R 1 3
File Input and Output
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
551 555 555 558 559 560 562 563 564 567 568 569 570 573 577 578
. . . . . . . . . . . 579
Understanding Computer Files . . . . . . . . . Using the Path Class . . . . . . . . . . . . Creating a Path . . . . . . . . . . . . . . Retrieving Information about a Path . . . . . . Converting a Relative Path to an Absolute One . Checking File Accessibility . . . . . . . . . . Deleting a Path . . . . . . . . . . . . . . Determining File Attributes . . . . . . . . . . File Organization, Streams, and Buffers . . . . . Using Java's IO Classes . . . . . . . . . . . . Writing to a File . . . . . . . . . . . . . . Reading from a File . . . . . . . . . . . . Creating and Using Sequential Data Files . . . . . Learning about Random Access Files . . . . . . Writing Records to a Random Access Data File . . Reading Records from a Random Access Data File Accessing a Random Access File Sequentially . Accessing a Random Access File Randomly . . You Do It . . . . . . . . . . . . . . . . . . Creating Multiple Random Access Files . . . . Writing a Method to Create an Empty File . . . Adding Data Entry Capability to the Program . . Setting Up a Program to Read the Created Files Displaying File Statistics . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
580 581 582 583 584 585 587 588 591 594 597 599 601 607 611 618 618 620 622 622 624 625 628 629
Reading a File Sequentially Reading a File Randomly . Don’t Do It . . . . . . . . Key Terms . . . . . . . . Chapter Summary . . . . . Review Questions . . . . . Exercises . . . . . . . . Debugging Exercise . . . Game Zone . . . . . . .
C H AP T E R 1 4
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
630 632 633 633 635 636 639 641 641
Introduction to Swing Components . . . . . 643 Understanding Swing Components . . . . . . . . . . . . . Using the JFrame Class . . . . . . . . . . . . . . . . . Customizing a JFrame’s Appearance . . . . . . . . . . . Using the JLabel Class . . . . . . . . . . . . . . . . . Changing a JLabel’s Font . . . . . . . . . . . . . . . Using a Layout Manager . . . . . . . . . . . . . . . . . Extending the JFrame Class . . . . . . . . . . . . . . . Adding JTextFields, JButtons, and Tool Tips to a JFrame . . . Adding JTextFields . . . . . . . . . . . . . . . . . Adding JButtons . . . . . . . . . . . . . . . . . . . Using Tool Tips . . . . . . . . . . . . . . . . . . . . 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 . . . . . . . . . . . . Understanding Swing Event Listeners . . . . . . . . . . . . Using the JCheckBox, ButtonGroup, and JComboBox Classes . . . . . . . . . . . . . . . . . . . . . . . The JCheckBox Class . . . . . . . . . . . . . . . . . The ButtonGroup Class . . . . . . . . . . . . . . . . The JComboBox Class . . . . . . . . . . . . . . . . . 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 . . . . . . . . . Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . Key Terms . . . . . . . . . . . . . . . . . . . . . . .
644 645 648 650 652 654 656 659 659 661 663 664 665 665 665 669 669 672 672 676 677 679 679 681 681 682 684 685 688 689
xiii
CONTENTS
Chapter Summary . . Review Questions . . Exercises . . . . . Debugging Exercise Game Zone . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
691 692 695 696 696
xiv
C H AP T E R 1 5
Advanced GUI Topics . . . . . . . . . . . 699 Understanding the Content Pane . . . . . . . . . . . . . . Using Color . . . . . . . . . . . . . . . . . . . . . . . Learning More About Layout Managers . . . . . . . . . . . Using BorderLayout . . . . . . . . . . . . . . . . . Using FlowLayout . . . . . . . . . . . . . . . . . . Using GridLayout . . . . . . . . . . . . . . . . . . Using CardLayout . . . . . . . . . . . . . . . . . . Using Advanced Layout Managers . . . . . . . . . . . . Using the JPanel Class . . . . . . . . . . . . . . . . . Creating JScrollPanes . . . . . . . . . . . . . . . . . A Closer Look at Events and Event Handling . . . . . . . . . An Event-Handling Example: KeyListener . . . . . . . . Using AWTEvent Class Methods . . . . . . . . . . . . . . Understanding x- and y-Coordinates . . . . . . . . . . . . Handling Mouse Events . . . . . . . . . . . . . . . . . . Using Menus . . . . . . . . . . . . . . . . . . . . . . Using JCheckBoxMenuItem and JRadioButtonMenuItem Objects . . . . . . . . . . . . . . . . . . . . . . . . . Using addSeparator() . . . . . . . . . . . . . . . . Using setMnemonic() . . . . . . . . . . . . . . . . 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 . . . . . . . . . . . . . Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . Key Terms . . . . . . . . . . . . . . . . . . . . . . . Chapter Summary . . . . . . . . . . . . . . . . . . . . Review Questions . . . . . . . . . . . . . . . . . . . . Exercises . . . . . . . . . . . . . . . . . . . . . . . Debugging Exercise . . . . . . . . . . . . . . . . . . Game Zone . . . . . . . . . . . . . . . . . . . . . .
700 702 705 706 708 710 712 714 714 722 725 728 730 732 733 738 741 743 743 744 744 746 747 748 749 750 751 755 756 757 759 761 763 763
C H AP T E R 1 6
Graphics
. . . . . . . . . . . . . . . . 769
Learning About the paint() and repaint() Methods . Using the setLocation() Method . . . . . . . . Creating Graphics Objects . . . . . . . . . . . Using the drawString() Method . . . . . . . . . . Using the setFont() and setColor() Methods . . Using Color . . . . . . . . . . . . . . . . . . . Drawing Lines and Shapes . . . . . . . . . . . . . Drawing Lines . . . . . . . . . . . . . . . . . . Drawing Rectangles . . . . . . . . . . . . . . . Creating Shadowed Rectangles . . . . . . . . . . Drawing Ovals . . . . . . . . . . . . . . . . . . Drawing Arcs . . . . . . . . . . . . . . . . . . Creating Polygons . . . . . . . . . . . . . . . . Copying an Area . . . . . . . . . . . . . . . . . Learning More About Fonts . . . . . . . . . . . . . Discovering Screen Statistics Using the Toolkit Class Discovering Font Statistics . . . . . . . . . . . . Drawing with Java 2D Graphics . . . . . . . . . . . . Specifying the Rendering Attributes . . . . . . . . . Setting a Drawing Stroke . . . . . . . . . . . . . Creating Objects to Draw . . . . . . . . . . . . . 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 . . . . . . . . . . . . . . . Don’t Do It . . . . . . . . . . . . . . . . . . . . Key Terms . . . . . . . . . . . . . . . . . . . . Chapter Summary . . . . . . . . . . . . . . . . . Review Questions . . . . . . . . . . . . . . . . . Exercises . . . . . . . . . . . . . . . . . . . . Debugging Exercise . . . . . . . . . . . . . . . Game Zone . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
770 772 774 775 776 777 778 778 779 781 782 783 784 786 787 789 790 792 792 794 795 798 798 799 800 801 802 803 805
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
807 809 810 812 812 814 815 818 821 821
xv
CONTENTS
C H AP T E R 1 7
Applets, Images, and Sound . . . . . . . . 825 Introducing Applets . . . . . . . . . . . . . . . . Understanding the JApplet Class . . . . . . . . Running an Applet . . . . . . . . . . . . . . . Writing an HTML Document to Host an Applet . . . . . Creating a JApplet that Contains an init() Method Working with JApplet Components . . . . . . . . Understanding the JApplet Life Cycle . . . . . . . The init() Method . . . . . . . . . . . . . . The start() Method . . . . . . . . . . . . . The stop() Method . . . . . . . . . . . . . . The destroy() Method . . . . . . . . . . . . Understanding Multimedia and Using Images . . . . . Adding Images to JApplets . . . . . . . . . . Using ImageIcons . . . . . . . . . . . . . . Adding Sound to JApplets . . . . . . . . . . . . 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 . . . . . . . . . . . . . . . . Don’t Do It . . . . . . . . . . . . . . . . . . . Key Terms . . . . . . . . . . . . . . . . . . . Chapter Summary . . . . . . . . . . . . . . . . Review Questions . . . . . . . . . . . . . . . . Exercises . . . . . . . . . . . . . . . . . . . Debugging Exercise . . . . . . . . . . . . . . Game Zone . . . . . . . . . . . . . . . . . .
xvi
A PP E N D I X A
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
826 826 827 828 830 832 835 836 836 836 836 837 838 841 844 846 846 846 847 848 849 850 854 855 857 857 858 859 861 864 864
Working with the Java Platform . . . . . . . 869 Configuring Windows to Work with the Java SE Development Kit Finding the Command Prompt . . . . . . . . . . . . . Command Prompt Anatomy . . . . . . . . . . . . . . Changing Directories . . . . . . . . . . . . . . . . . Setting the class and classpath Variables . . . . . . Changing a File’s Name . . . . . . . . . . . . . . . . Compiling and Executing a Java Program . . . . . . . .
. . . . . . .
870 871 871 871 872 873 873
Using Notepad to Save and Edit Source Code . . . . . . . . 874 Using TextPad to Work with Java . . . . . . . . . . . . . . 874 Key Terms . . . . . . . . . . . . . . . . . . . . . . . 875 A PP E N D I X B
Learning About Data Representation Understanding Numbering Systems Representing Numeric Values . . Representing Character Values . . Key Terms . . . . . . . . . .
A PP E N D I X C
Formatting Output
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . . 877 . . . .
. . . .
Generating Random Numbers
. . . .
. . . .
. . . .
878 880 881 883
. . . . . 886 . . . . . 887 . . . . .
. . . . .
. . . . .
. . . . .
. . . . .
891 891 892 893 894
. . . . . . . 897
Understanding Random Numbers Generated by Using the Math.random() Method . . . . Using the Random Class . . . . . . . . . Key Terms . . . . . . . . . . . . . . . A PP E N D I X E
. . . .
. . . . . . . . . . . . 885
Rounding Numbers . . . . . . . . . . . . . . . Using the printf() Method . . . . . . . . . . Specifying a Number of Decimal Places to Display with printf() . . . . . . . . . . . . . . Specifying a Field Size with printf() . . . . . Using the Optional Argument Index with printf() Using the DecimalFormat Class . . . . . . . . Key Terms . . . . . . . . . . . . . . . . . . A PP E N D I X D
. . . .
Computers . . . . . . . . . . . . . . .
. . . .
. . . .
. . . .
898 899 900 903
Javadoc . . . . . . . . . . . . . . . . . 905 The Javadoc Documentation Generator . . . . Javadoc Comment Types . . . . . . . . . . Generating Javadoc Documentation . . . . . . Specifying Visibility of Javadoc Documentation Key Terms . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
906 906 908 911 912
Glossary . . . . . . . . . . . . . . . . . 913 Index
. . . . . . . . . . . . . . . . . . 937
xvii
Preface xviii
Java Programming, Sixth 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 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, making it easier for native and nonnative English speakers alike to master the programming concepts. Complete, working code examples appear frequently in each chapter; these examples help students make the transition from the theoretical to the practical. The code presented in each chapter can also be downloaded from the publisher’s Web site, so that students can easily run the programs and experiment with changes to them.
Organization and Coverage Java Programming, Sixth Edition presents Java programming concepts, enforcing good style, logical thinking, and the object-oriented paradigm. Objects are covered right from the beginning, earlier than in many other textbooks. You create your first Java program in Chapter 1. Chapters 2, 3, and 4 increase your understanding of how data, classes, objects, and methods interact in an object-oriented environment. Chapters 5 and 6 explore input and repetition structures, which are the backbone of programming logic and essential to creating useful programs in any language. You learn the special considerations of string and array manipulation in Chapters 7, 8, and 9. Chapters 10, 11, and 12 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 13 provides information on handling files so you can permanently store and retrieve program output.
Features of the Text
Chapters 14 and 15 introduce GUI Swing components—Java’s visually pleasing, user-friendly widgets—and their layout managers. Chapters 16 and 17 show you ways to provide interactive excitement using graphics, applets, images, and sound. In every chapter, Java Programming, Sixth 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 promoting concept retention. Creating the programs in the step-by-step examples also provides students with successful experiences using the language; finishing the examples provides them with models for their own creations. The student using Java Programming, Sixth Edition builds applications from the bottom up, rather than starting with existing objects. This facilitates a deeper understanding of the concepts used in object-oriented programming, and engenders appreciation for the existing objects students use as their knowledge of the language advances. When students complete this book, they will know how to modify and create simple Java programs and 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 of the Text Java Programming, Sixth Edition is a superior textbook because it includes the following features: OBJECTIVES: Each chapter begins with a list of objectives so you know the topics that will be presented in the chapter. In addition to providing a quick reference to topics covered, this feature provides a useful study aid. 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 fewer, illustrating one concept at a time. Frequent screen shots show exactly how program output appears. Callouts appear where needed to emphasize a point. COLOR: The code figures in each chapter contain all Java keywords in blue. This helps students identify keywords more easily, distinguishing them from programmer-selected names. FILES: More than 200 student files can be downloaded from the publisher’s Web site. Most
files contain the code presented in the figures in each chapter; students can run the code for themselves, view the output, and make changes to the code to observe the effects. Other files include debugging exercises that help students improve their programming skills. TWO TRUTHS AND A LIE: A short 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
xix
PREFACE
Features of the Text
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 questions and programming problems. xx
YOU DO IT: In each chapter, step-by-step exercises help students create multiple working
programs that emphasize the logic a programmer uses in choosing statements to include. 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. 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. SUMMARY: Following each chapter is a summary that recaps the programming concepts and
techniques covered in the chapter. This feature provides a concise means for students to check their understanding of the main points in each chapter. REVIEW QUESTIONS: Each chapter includes 20 multiple-choice questions that serve as a review of chapter topics. 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 students create
interactive games using the programming techniques learned up to that point; 70 game programs are suggested in the book. The games are fun to create and play; writing them motivates students to master the necessary programming techniques. Students might exchange completed game programs with each other, suggesting improvements and discovering alternate ways to accomplish tasks. APPENDICES: This edition includes useful appendices on working with the Java platform,
data representation, formatting output, generating random numbers, and creating Javadoc comments. GLOSSARY: A glossary contains definitions for all key terms in the book, presented in alphabetical order. QUALITY: Every program example, exercise, and game solution was tested by the author
and then tested again by a Quality Assurance team using a prerelease snapshot version of Java Standard Edition (SE) 7, the most recent version available. (The external version number used by Sun Microsystems is 7.0; the internal version number is 1.7.0. For more information on the features of the JDK, visit http://www.oracle.com/technetwork/java/ index.html.)
Instructor Resources
New to This Edition! This edition introduces the following pedagogical improvements: l
Programs are written and tested using Java 7, the newest edition of the Java platform.
l
Video lessons accompany each chapter. The author created and narrated these videos, which enhance explanations in the text and help to clarify difficult topics. The videos are a great supplement to online classes.
l
Array coverage is split into two chapters, allowing instructors to cover introductory and advanced array topics separately, and providing more detail and exercises using arrays.
l
This book covers the Path class, which is new in Java 7 and replaces the functionality of the File class. The File Input and Output chapter has been completely rewritten to describe state-of-the-art file handling techniques.
l
This book covers using Strings in switch statements, which is a new feature in Java 7.
l
This book covers catching multiple Exception types in a single catch block, which is a new feature of Java 7.
CourseMate The more you study, the better the results. Make the most of your study time by accessing everything you need to succeed in one place. Read your textbook, take notes, review flashcards, watch videos, and take practice quizzes online. CourseMate goes beyond the book to deliver what you need! Learn more at www.cengage.com/coursemate. The Java Programming CourseMate includes: l
Debugging Exercises: Four error-filled programs accompany each chapter. By debugging these programs, students can gain expertise in program logic in general and the Java programming language in particular.
l
Video Lessons: Each chapter is accompanied by at least three video lessons that help to explain important chapter concepts. These videos were created and narrated by the author.
l
An interactive eBook, quizzes, flashcards, and more!
Instructors may add CourseMate to the textbook package, or students may purchase CourseMate directly at www.cengagebrain.com.
Instructor Resources The following supplemental materials are available when this book is used in a classroom setting. ELECTRONIC INSTRUCTOR’S MANUAL: The Instructor’s Manual that accompanies this textbook contains additional instructional material to assist in class preparation, including items such as Sample Syllabi, Chapter Outlines, Technical Notes, Lecture Notes, Quick
xxi
PREFACE
Instructor Resources
Quizzes, Teaching Tips, Discussion Topics, and Key Terms. Additional exercises in the Instructor’s Manual include: l
Tough Questions: Each chapter is accompanied by two or more fairly difficult questions that are typical of what an applicant might encounter in a technical job interview. These questions are often open-ended; some involve coding, and others might involve research.
l
Up for Discussion: Each chapter is supported by 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.
xxii
®
EXAMVIEW : This textbook is accompanied by ExamView, a powerful testing software
package that allows instructors to create and administer printed, computer (LAN-based), and Internet-based 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: Microsoft PowerPoint slides are available for each chapter. These slides are provided 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 to instructors on the Instructor Resources CD and on the Course Technology Web site at login.cengage.com. The solutions are password protected. Annotated solutions are provided for some of the multiple-choice Review Questions. For example, if students are likely to debate answer choices, or not understand the choice deemed to be the correct one, a rationale is provided. 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 Cengage sales representative.
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 have improved this book over multiple editions. He is a master at ferreting out inconsistencies and has made this a superior book. Thanks also to Alyssa Pratt, Senior Product Manager; Jill Braiewa, Senior Content Project Manager; and Chris Scriver and Serge Palladino, Quality Assurance. I am lucky to work with these professionals, who are dedicated to producing excellent instructional materials. I am also grateful to the reviewers who provided comments and encouragement during this book’s development, including Saleem Abuleil, Chicago State University; Valorie Branstool, Oklahoma State University; Robert Madison, Ivy Tech; Lori Nicholson, Wayne State College; and Susan Taylor, Mount Wachusett Community College. Thanks, too, to my husband, Geoff, for his support. Finally, this book is dedicated to Eli Anthony Farrell-Ortiz.
Joyce Farrell
xxiii
xxiv
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 www.cengagebrain.com. Find the ISBN of your title on the back cover of your book, then enter the ISBN in the search box at the top of the CengageBrain home page. You can find the data files on the product page that opens. Note that you can use a computer in your school lab or your own computer to complete the exercises in this book.
Using Your Own Computer To use your own computer to complete the steps and exercises, you need the following: l
Software: Java SE 7, available from http://www.oracle.com/technetwork/java/index.html. Although almost all of the examples in this book will work with earlier versions of Java, this book was created using Java 7. The book clearly points out the few cases when an example is based on Java 7 and will not work with earlier versions of Java. You also need a text editor, such as Notepad. A few exercises ask you to use a browser, such as Internet Explorer.
l
Hardware: If you are using Windows 7, the Java Web site suggests at least 128 MB of memory and at least 98 MB of disk space. For other operating system requirements, see http://java.com/en/download/help.
l
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 www.cengagebrain.com.
Special Note At the time of publication, both of the following URLs direct you to online Java documentation: http://java.sun.com and http://www.oracle.com/technetwork/java/index.html. For convenience, this book most frequently directs you to the shorter URL, but there is no guarantee how long it will continue to be functional. Therefore, use the longer URL if needed, or simply use a search engine to locate the current location of the official Java documentation.
CHAPTER
Creating Your First Java Classes
1
In this chapter, you will: Define basic programming terminology Describe procedural and object-oriented programming concepts Describe the features of the Java programming language Analyze a Java application that produces console output Add comments to a Java class Save, compile, run, and modify a Java application Create a Java application that produces GUI output Correct errors and find help
CHAPTER 1
Creating Your First Java Classes
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: 2
first switch—on second switch—off third switch—off fourth switch—on
The logic behind a computer program determines the exact order of switches that perform the desired tasks to produce desired output. A program written in the style that refers to switch settings is written in machine language, which is the most basic circuitry-level language. 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 need to customize a machine language program for every type of machine on which you want the program to run. 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.
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 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 highlevel programming language. In every high-level programming language, the names of memory locations cannot include spaces.
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,
Learning About Programming
whereas an interpreter translates one program statement at a time, executing a statement as soon as it is translated. Program statements are also known as commands because they are commands to the computer such as “write this statement” or “add these two numbers.”
3 Whether you use a compiler or interpreter often depends on the programming language you use. For example, C++ is a compiled language, and Visual Basic is an interpreted language. Each type of translator has its supporters; programs written in compiled languages execute more quickly, whereas programs written in interpreted languages 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 when the program executes (also called at run time).
Compilers and interpreters issue one or more error messages each time they encounter an invalid program statement—that is, a statement containing a syntax error, or misuse of the language. 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 the first part of the process of debugging a program—freeing the program of all errors. Figure 1-1 illustrates the steps a programmer takes while developing an executable program. You will learn more about debugging Java programs later in this chapter.
As Figure 1-1 shows, you might be able to use a computer language’s syntax correctly, but still have errors to correct. In addition to learning the correct syntax for a particular language, a programmer must also understand computer programming logic. When you develop a program of any significant size, you should plan its logic before you write any program statements. Correct logic requires that all the right commands be issued in the appropriate order. Examples of logical errors include multiplying two values when you meant to divide them, or producing output prior to obtaining the appropriate input. Syntax errors are discovered when you compile a program, but often you can identify logical errors only when you examine a program’s first output. For example, if you know an employee’s paycheck should contain the value $5,000, but you see that it holds $50 or $50,000 after you execute a payroll program, a logical error has occurred. Correcting logic errors is the second part of the debugging process. Tools that help you visualize and understand logic are presented in Chapter 5. 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.
CHAPTER 1
Creating Your First Java Classes
Plan program logic 4
Use translating software (a compiler or interpreter) that translates programming language statements to machine language
Can all statements be successfully translated?
No
Yes Execute the program
Examine program output
Are there runtime errors or errors in the output?
Yes
No
Figure 1-1
The program development process
Examine list of syntax errors
Debugging process
Debugging process
Write program language statements that correspond to the logic
Comparing Procedural and Object-Oriented Concepts
TWO TRUTHS & 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.
Comparing Procedural and Object-Oriented Programming Concepts Two popular approaches to writing computer programs are procedural programming and object-oriented programming.
Procedural Programming Procedural programming is a style of programming in which operations are executed one
after another in sequence. It involves using your knowledge of a programming language to create applications, which are programs that perform a task for a user. In procedural applications, you create names for computer memory locations that can hold values—for example, numbers and text—in electronic form. The named computer memory locations are called variables because they hold values that might vary. For example, a payroll program 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
5
CHAPTER 1
Creating Your First Java Classes
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. 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.
6
Object-Oriented Programming Object-oriented programming is an extension of procedural programming in which you take a slightly different approach to writing computer programs. Writing object-oriented programs involves creating classes, which are blueprints for objects; creating objects from those classes; and creating applications that use those objects. After creation, classes can 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 that 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. Programmers use OO as an abbreviation for object-oriented; it is pronounced “oh oh.” Object-oriented programming is abbreviated OOP, and pronounced to rhyme with soup.
Originally, object-oriented programming was used most frequently for two major types of applications: l
Computer simulations, which attempt to mimic real-world activities so that their
processes can be improved or so that users can better understand how the real-world processes operate l
Graphical user interfaces, or GUIs (pronounced “gooeys”), which allow users to interact
with a program in a graphical environment Thinking about objects in these two types of applications makes sense. For example, a city might want to develop a program that simulates traffic patterns to better prevent traffic tieups. By creating a model with objects such as cars and pedestrians that contain their own data and rules for behavior, the simulation can be set in motion. For example, each car object has a specific current speed and a procedure for changing that speed. By creating a model of city traffic using objects, a computer can create a simulation of a real city at rush hour. Creating a GUI environment for users also is a natural use for object orientation. It is easy to think of the components a user manipulates on a computer screen, such as buttons and scroll bars, as similar to real-world objects. Each GUI object contains data—for example, a button on a screen has a specific size and color. Each object also contains behaviors—for example, each button can be clicked and reacts in a specific way when clicked. Some people consider the term object-oriented programming to be synonymous with GUI programming, but objectoriented programming means more. Although many GUI programs are object-oriented, one
Comparing Procedural and Object-Oriented Concepts
does not imply the other. Modern businesses use object-oriented design techniques when developing all sorts of business applications, whether they are GUI applications or not. 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: l
Polymorphism
l
Inheritance
l
Encapsulation as it applies to classes as objects You can remember the three concepts polymorphism, inheritance, and encapsulation by remembering the acronym PIE.
Understanding Classes, Objects, and Encapsulation In object-oriented terminology, a class is a term that describes a group or collection of objects with common properties. A class definition describes what attributes its objects will have and what those objects will be able to do. Attributes are the characteristics that define an object; they are properties of the object. The values contained in an object’s properties differentiate objects of the same class from one another. An object is a specific, concrete instance of a class. When you create an object instance, you instantiate it.
For example, the class Automobile describes what Automobile objects are like. Some properties of the Automobile class are make, model, year, and color. Each Automobile object possesses the same attributes, but not, of course, the same values for those attributes. One Automobile might be a 2009 white Ford Taurus and another might be a 2011 red Chevrolet Camaro. Similarly, your dog has the properties of all Dogs, including a breed, name, age, and whether his shots are current. The values of the properties of an object are also referred to as the object’s state. In object-oriented programming grammar, an object is equivalent to a noun, and an attribute is an adjective. Methods are similar to verbs.
When you understand an object’s class, you understand a lot about the object. If your friend purchases an Automobile, you know it has a model name, and if your friend gets a Dog, you know the dog has a breed. Knowing what attributes exist for classes allows you to ask appropriate questions about the states or values of those attributes. Similarly, in a GUI
7
CHAPTER 1
Creating Your First Java Classes
operating environment, you expect each component to have specific, consistent attributes and methods, such as a window having a title bar and a close button, because each component gains these properties as a member of the general class of GUI components. Figure 1-2 shows the relationship of some Dog objects to the Dog class. By convention, programmers using Java begin their class names with an uppercase letter. Thus, the class that defines the attributes and methods of an automobile would probably be named Automobile, and the class for dogs would probably be named Dog. However, following this convention is not required to produce a workable program.
8
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.
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.
Dog class definition
Dog class instances (objects)
Every Dog that is created will have a: Name Age Breed Shot status
Figure 1-2
Ginger 6 Akita Up to date
Bowser 2 Retriever Up to date
Roxy 1 Beagle Up to date
A class definition and some objects created from it
Besides defining properties, classes define methods their objects can use. A method is a selfcontained block of program code that carries out some action, similar to a procedure in a procedural program. An Automobile, for example, might have methods for moving forward, moving backward, being filled with gasoline, and being 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.
Comparing Procedural and Object-Oriented Concepts
In object-oriented classes, 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 classes used in object-oriented programs— programs that use classes only need to work with interfaces.
Understanding Inheritance and Polymorphism An important feature of object-oriented 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 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. Chapters 10 and 11 provide more information about inheritance and polymorphism, and how they are implemented in Java.
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 example, although the classes Automobile, Sailboat, and Airplane all inherit from Vehicle, turn and stop methods work differently for instances of those classes. The advantages of polymorphism will become more apparent when you begin to create GUI
9
CHAPTER 1
Creating Your First Java Classes
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. Watch the video Object-Oriented Programming.
10
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.
TWO TRUTHS & A LIE Comparing Procedural and Object-Oriented Programming Concepts 1.
An instance of a class is a created object that possesses the attributes and methods described in the class definition.
2.
Encapsulation protects data by hiding it within an object.
3.
Polymorphism is the ability to create classes that share the attributes and methods of existing classes, but with more specific features.
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.
Features of the Java Programming Language Java was developed by Sun Microsystems as an object-oriented language for general-purpose
business applications and for interactive, World Wide Web-based Internet applications. 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 runs 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).
Features of the Java Programming Language
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.
Interactive applications are those in which a user communicates with a program by using an input device such as the keyboard or a mouse.
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
Java Source Code Source code is stored on a disk in a file with a name ending in .java
Java Compiler
Java Virtual Machine
Compiler creates bytecodes that are stored on a disk in a file with a name ending in .class
Java Interpreter
Computer Operating System
Figure 1-3
The Java environment
JVM (named java.exe) performs security checks and translates bytecodes to machine language, which executes
11
CHAPTER 1
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 also is insulated from the particular hardware on which it is run. Because of this insulation, the JVM provides security against intruders accessing your computer’s hardware through the operating system. Therefore, Java is more secure than other languages. Another advantage provided by the JVM means less work for programmers—when using other programming languages, software vendors usually have to produce multiple versions of the same product (a Windows version, Macintosh version, UNIX version, Linux version, and so on) so all users can run the program. With Java, one program version will run on all these platforms. “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.
Java also is simpler to use than many other object-oriented languages. Java is modeled after C++. Although neither language is easy to read or understand on first exposure, Java does eliminate some of the most difficult-to-understand features in C++, such as pointers and multiple inheritance.
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 & A LIE Features of the Java Programming Language 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.
12
Creating Your First Java Classes
Analyzing a Java Application that Produces Console Output
Analyzing a Java Application that Produces Console Output At first glance, even the simplest Java application involves a fair amount of confusing syntax. Consider the application in Figure 1-4. This program is written on seven lines, and its only task is to display “First Java application” on the screen. public class First { public static void main(String[] args) { System.out.println("First Java application"); } }
Figure 1-4
The First class
When you see program code in figures in this book, Java keywords as well as true, false, and null are blue, and all other program elements are black. A complete list of Java keywords is shown later in this chapter.
The code for every complete program shown in this book is available in a set of student files you can download so that you can execute the programs on your own computer.
Understanding the Statement that Produces 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. 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. 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.
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.
13
CHAPTER 1
System is a class.
14
Creating Your First Java Classes
out is an object defined in the System 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.
Figure 1-5
println() is a method. Method names are always followed by parentheses.
Every Java statement ends with a semicolon.
Anatomy of a Java statement
The dots (periods) in System.out.println are used to separate the names of the components in the statement. You will use this same format repeatedly in your Java programs.
The string “First Java application” appears within parentheses because the string is an argument to a method, and arguments to methods always appear within parentheses. Arguments are pieces of information that are sent into, 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 arguments. 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”. When you call a method, you always use parentheses following the method name. In this book you will learn about many methods that require arguments between their parentheses, and many others for which you leave the parentheses empty.
The println() method requires only one argument. Later in this chapter, you will learn about a method named showMessageDialog() that requires two arguments. Other methods require more.
You can use the println() method with no arguments when you want to output a blank line.
Analyzing a Java Application that Produces Console Output
Within the statement System.out.println("First Java application");, the method to which you are passing "First Java application" is named println(). The println() method displays 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. Method names usually are referenced followed by their parentheses, as in println(), so that you can distinguish method names from variable names.
Within the statement System.out.println("First Java application");, out is a property of the System class that refers to the standard output device for a system, normally the monitor. The out object itself is an instance of the PrintStream class, which contains several methods, including println(). Technically, you could create the out object and write the instructions within the println()method yourself, but it would be time consuming, and the creators of Java assumed you frequently would want to display output on a screen. Therefore, the System and PrintStream classes, the out object, and the println() method were created as a convenience to the programmer. The print() method is very similar to the println() method. With println(), after the message is displayed, 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 attributes for System objects, just as the Dog class defines the attributes for Dog objects. One of the System attributes is out. (You can probably guess that another attribute is in and that it represents an input device.) Java is case sensitive; the class named System is a completely different class from one named system, SYSTEM, or even sYsTeM.
The statement that displays 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 a Java class using any name or identifier you need, as long as it meets the following requirements: l
A Java identifier must begin with a letter of the English alphabet, a non-English letter (such as α or π), an underscore, or a dollar sign. A class name cannot begin with a digit.
l
A Java identifier can contain only letters, digits, underscores, or dollar signs. Java is based on Unicode, which is an international system of character representation. The term letter indicates English-language letters as well as characters from Arabic, Greek, and other alphabets. You can learn more about Unicode in Appendix B.
15
CHAPTER 1
Creating Your First Java Classes
l
A Java identifier cannot be a reserved keyword, such as public or class. (See Table 1-1 for a list of reserved keywords.)
l
A Java identifier cannot be one of the following values: true, false, or null. These are not keywords (they are primitive values), but they are reserved and cannot be used.
16 abstract
continue
for
new
switch
assert
default
goto
package
synchronized
boolean
do
if
private
this
break
double
implements
protected
throw
byte
else
import
public
throws
case
enum
instanceof
return
transient
catch
extends
int
short
try
char
final
interface
static
void
class
finally
long
strictfp
volatile
const
float
native
super
while
Table 1-1
Java reserved keywords
Although they are reserved as keywords, const and goto are not used in Java programs and they have no function. Both words are used in other languages and were reserved in case developers of future versions of Java wanted to implement them.
It is a Java standard, although not a requirement, to begin class identifiers with an uppercase letter and employ other uppercase letters as needed to improve readability. 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
Description
Employee
Begins with an uppercase letter
UnderGradStudent
Begins with an uppercase letter, contains no spaces, and emphasizes each new word with an initial uppercase letter
InventoryItem
Begins with an uppercase letter, contains no spaces, and emphasizes the second word with an initial uppercase letter
Budget2012
Begins with an uppercase letter and contains no spaces
Table 1-2
Some valid class names in Java
Analyzing a Java Application that Produces Console Output
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.
Using an uppercase letter to begin an identifier and to start each new word in an identifier is known as Pascal casing.
Class Name
Description
Undergradstudent
New words are not indicated with initial uppercase letters, making this identifier difficult to read
Inventory_Item
Underscore is not commonly used to indicate new words
BUDGET2012
Using all uppercase letters for class identifiers is not conventional
budget2012
Conventionally, class names do not begin with a lowercase letter
Table 1-3
Legal but unconventional and nonrecommended class names in Java
Class Name
Description
Inventory Item
Space character is illegal in an identifier
class
class is a reserved word
2012Budget
Class names cannot begin with a digit
phone#
The number symbol ( # ) is illegal in an identifier
Table 1-4
Some illegal class names in Java
In Figure 1-4 (and again in Figure 1-6), the line public class First is the class header; it contains the keyword class, which identifies First as a class. The reserved word public is an access specifier. An access specifier defines the circumstances under which a class can be accessed and the other classes that have the right to use a class. Public access is the most liberal type of access; you will learn about public and other types of access in Chapter 3. After the class header, you enclose the contents of a class within curly braces ( { and } ); any data items and methods between the curly braces make up the class body. A class body can be composed of any number of data items and methods. In Figure 1-4 (and again in Figure 1-6), the class First contains only one method within its curly braces. The name of the method is main(), and the main() method, like the println() method, includes its own set of parentheses. The main() method in the First class contains only one statement—the statement that uses the println() method.
17
CHAPTER 1
Creating Your First Java Classes
public is an access specifier.
18
This line is the class header. Everything between the braces is the class body.
Figure 1-6
The keyword class identifies First as a class.
First is the name of the class.
public class First { public static void main(String[] args) { System.out.println("First Java application"); } }
The parts of a typical class
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.
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.
Indent Style 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 class executes in exactly the same way as the one shown in Figure 1-4. The only difference is the layout of the braces—the line breaks occur in different locations. public class First{ public static void main(String[] args){ System.out.println("First Java application"); } } The indent style 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 opening braces are not on separate lines is known as the K & R style, named for Kernighan and Ritchie, who wrote the first book on the C programming language.
Analyzing a Java Application that Produces Console Output
Java programmers use a variety of indent styles, and all can produce workable Java programs. When you write your own code, you should develop a consistent style. In school, your instructor might have a preferred style, and when you get a job as a Java programmer, your organization most likely will have a preferred style. 19
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 specifier, 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. Figure 1-7 shows the parts of the main() method.
static means this method works without instantiating an object of the class. public is an access specifier.
void is the method’s return type.
public class First { This line is the method header.
public static void main(String[] args) {
Everything between the curly braces is the method body.
System.out.println("First Java application"); } }
String is a class. Any arguments to this method must be String objects.
Figure 1-7
The square brackets mean the argument to this method is an array of Strings. Chapters 8 and 9 provide more information about Strings and arrays.
args is the identifier of the array of Strings that is the argument to this method.
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.
CHAPTER 1
Creating Your First Java Classes
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. 20
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 display 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. 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. 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, 8, and 9.
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. Watch the video A Java Program.
public class AnyClassName { public static void main(String[] args) { /******/ } }
Figure 1-8
Shell code
Adding Comments to a Java Class
TWO TRUTHS & A LIE Analyzing a Java Application that Produces Console Output 1.
In the method header public static void main(String[] args), the word public is an access specifier.
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 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 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. 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.
Comments also can 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 it, and the JVM does not execute its command. This can help you pinpoint the location of errant statements in malfunctioning programs.
21
CHAPTER 1
Creating Your First Java Classes
There are three types of comments in Java: l
Line comments start with two forward slashes ( // ) and continue to the end of the current
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. 22
l
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 also can extend across as many lines as needed. l
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. The forward slash ( / ) and the backslash ( \ ) characters often are confused, but they are two distinct characters. You cannot use them interchangeably.
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.
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
Saving, Compiling, Running, and Modifying a Java Application
TWO TRUTHS & 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.
Saving, Compiling, Running, and Modifying a Java Application Saving a Java Class When you write a Java class, you must save it using a storage medium such as a disk, DVD, or USB device. In Java, if a class is public (that is, if you use the public access specifier 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. Appendix A contains important information on saving, compiling, and running a Java application.
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.
23
CHAPTER 1
Creating Your First Java Classes
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: 24
javac First.java
There will be one of three outcomes: l
You receive a message such as 'javac' is not recognized as an internal or external command, operable program or batch file.
l
You receive one or more program language error messages.
l
You receive no messages, which means that the application compiled successfully. 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: l
You misspelled the command javac.
l
You misspelled the filename.
l
You are not within the correct subfolder or subdirectory on your command line.
l
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. 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
Saving, Compiling, Running, and Modifying a Java Application
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. 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.
Figure 1-10
Output of the First application
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.
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
To produce the new output, first you must modify the text file that contains the existing class. You need to change the existing literal string, and then add an output statement for another text string. Figure 1-11 shows the class that changes the output.
25
CHAPTER 1
26
Creating Your First Java Classes
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
Watch the video Compiling and Executing a Program.
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.
Creating a Java Application that Produces GUI Output
TWO TRUTHS & 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 that Produces 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
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.
27
CHAPTER 1
Creating Your First Java Classes
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. 28
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.
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.
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 is displayed. Earlier in this chapter, you learned that true, false, and null are all reserved words that represent values.
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.
Whenever a method requires multiple arguments, the arguments are always separated with commas.
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.
Correcting Errors and Finding Help
29
Figure 1-14
Output of the FirstDialog application
TWO TRUTHS & A LIE Creating a Java Application that Produces 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.
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 FirstDialog class (shown in Figure 1-13), if you mistype the JOptionPane code in the sixth line using a lowercase j in JOptionPane, 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 (FirstDialog.java), the line number in which it was found (6), and the nature of the error (“cannot find symbol”). The next two lines identify the symbol that cannot be found (jOptionPane) and the name of the class (FirstDialog). The last line of the error message displays the line with the error, including a caret that points to the exact location where the error was first discovered. Then a count of the number of errors is displayed—in this case, there is just one error.
CHAPTER 1
Creating Your First Java Classes
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.
30
Figure 1-15
Error message generated when program contains case error
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 displays a test message { public static void main(String[] args) { System.out.println("Test"); } }
Figure 1-16
The ErrorTest class with an unclosed comment
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
Correcting Errors and Finding Help
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.
31
Figure 1-17
Error messages generated by ErrorTest application in Figure 1-16
You also will receive the error message “reached end of file while parsing” if you omit a program’s closing curly brace.
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 ErrorTest class in Figure 1-16, typing the executable statement as System.out.println("Tst"); does not produce an error. The compiler does not find the spelling error of Tst instead of Test; 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 emphasizes programming structure and development that helps minimize errors. 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. 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 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.
CHAPTER 1
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. The JDK is an SDK—a software development kit that includes tools used by programmers.
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 you can 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 & 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.
32
Creating Your First Java Classes
You Do It
You Do It Your First Application 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 text-processing program. 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.
To write your first Java application: 1. Start any text editor (such as Notepad), 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.
33
CHAPTER 1
34
Creating Your First Java Classes
public class Hello { public static void main(String[] args) { System.out.println("Hello, world!"); } }
Figure 1-19
Complete Hello class
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. Enter the following comments at the top of the Hello file, inserting your name and today’s date where indicated. // Filename Hello2.java // Written by // Written on
2. Change the class name to Hello2, and then type the following block comment after the class header: /* This class demonstrates the use of the println() method to print the message Hello, world! */
You Do It
3. Save the file as Hello2.java. The file must be named Hello2.java because the class name is Hello2. 4. Go to the command-line prompt for the drive and folder or subdirectory in which you saved Hello2.java, and type the following command to compile the program: 35
javac Hello2.java If you receive an error message when you compile or run the program, look in the section “Saving, Compiling, Running, and Modifying a Java Application” to find its cause and then make the necessary corrections. Save the file again, and then repeat Step 4 until your application compiles successfully.
5. When the compile is successful, execute your application by typing java Hello2 at the command line. The output should appear on the next line, as shown in Figure 1-21.
Figure 1-21 Successful compilation and execution of Hello2 application
After the application compiles successfully, a file named Hello2.class is created and stored in the same folder as the Hello2.java file. If your application compiled without error but you receive an error message, such as “Exception in thread ‘main’ java.lang.NoClassDefFoundError,” when you try to execute the application, you probably do not have your class path set correctly. See Appendix A for details.
When you run a Java application using the java command, do not add the .class extension to the filename. If you type java First, the interpreter looks for a file named First.class. If you type java First.class, the interpreter incorrectly looks for a file named First.class.class.
Modifying a Class Next, you modify your Hello2 class, but to retain the Hello2 file, you save the modified file as the Hello3 class. To change the Hello2 class to the Hello3 class and rerun the application: 1. Open the file Hello2.java in your text editor. Change both the comment name and the class name to Hello3. 2. Add the following statement below the statement that displays “Hello, world!”: System.out.println("I'm ready for Java programming!");
Be certain to type the semicolon at the end of the statement and use the correct case.
CHAPTER 1
Creating Your First Java Classes
3. Save the file as Hello3.java. Then, at the command line, compile the file by typing the following command: javac Hello3.java
36
If you receive compile errors, return to the Hello3.java file in the text editor, fix the errors, and then repeat Step 3 until the class compiles successfully.
4. Interpret and execute the class by typing the following command: java Hello3
Your output should look like Figure 1-22.
Figure 1-22
Output of Hello3 application
Creating a Dialog Box Next, you write a Java application that produces output in a dialog box. To create an application that produces a dialog box as output: 1. Open a new file in your text editor. Type comments similar to the following, inserting your own name and today’s date where indicated. // Filename HelloDialog.java // Written by // Written on
2. Enter the import statement that allows you to use the JOptionPane class: import javax.swing.JOptionPane;
3. Enter the HelloDialog class: public class HelloDialog { public static void main(String[] args) { JOptionPane.showMessageDialog(null, "Hello, world!"); } }
Don’t Do It
4. Save the file as HelloDialog.java. Compile the class using the following command: javac HelloDialog.java
If necessary, eliminate any syntax errors, resave the file, and recompile. Then execute the program using the following command: java HelloDialog
The output appears as shown in Figure 1-23.
Figure 1-23
Output of HelloDialog application
5. Click OK to dismiss the dialog box.
Don’t Do It At the end of each chapter, a Don’t Do It list will alert you to common mistakes made by beginning programmers. l
Don’t forget that in Java, a public file’s name must match the name of the class it contains. For example, if a file is named Program1.java, you can’t simply rename it Program1BackUp.java and expect it to compile unless you change the class name within the file.
l
Don’t confuse the terms parentheses, braces, brackets, curly braces, square brackets, and angle brackets. When you are writing a program or performing some other computerized task and someone tells you, “Now, type some braces,” you might want to clarify which term is meant. Table 1-5 summarizes these punctuation marks.
37
CHAPTER 1
38
Creating Your First Java Classes
Punctuation
Name
Typical use in Java
Alternate names
()
Parentheses
Follows method names as in println()
Parentheses can be called round brackets, but such usage is unusual
{}
Curly braces
A pair surrounds a class body, a method body, and a block of code; when you learn about arrays in Chapter 8, you will find that curly braces also surround lists of array values
Curly braces might also be called curly brackets
[]
Square brackets
A pair signifies an array; arrays are covered in Chapter 8
Square brackets might be called box brackets or square braces
Angle brackets
A pair of angle brackets surrounds HTML tags, as you will learn in Chapter 17; in Java, a pair also is used with generic arguments in parameterized classes
When angle brackets appear with nothing between them, they are called a chevron
Table 1-5
Braces and brackets used in Java
l
Don’t forget to end a block comment. Every /* must have a corresponding */, even if it is several lines later. It’s harder to make a mistake with line comments (those that start with // ), but remember that nothing on the line after the // will execute.
l
Don’t forget that Java is case sensitive.
l
Don’t forget to end every statement with a semicolon, but not to end class or method headers with a semicolon.
l
Don’t forget to recompile a program to which you have made changes. It can be very frustrating to fix an error, run a program, and not understand why you don’t see evidence of your changes. The reason might be that the .class file does not contain your changes because you forgot to recompile.
l
Don’t panic when you see a lot of compiler error messages. Often, fixing one will fix several.
l
Don’t think your program is perfect when all compiler errors are eliminated. Only by running the program multiple times and carefully examining the output can you be assured that your program is logically correct.
Key Terms
Key Terms A computer program is a set of instructions that you write to tell a computer what to do. The logic behind any program involves executing the various statements and procedures in the correct order to produce the desired results. Machine language is a circuitry-level language that represents a series of on and off switches.
A low-level programming language is written to correspond closely to a computer processor’s circuitry. 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. Syntax refers to the rules of a language. Program statements are similar to English sentences; they carry out the tasks that programs
perform. A compiler, or interpreter, is a program that translates language statements into machine code. Executing a statement or program means to carry it out. Commands are program statements. At run time is a phrase that describes the period of time during which a program executes.
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 containing syntax errors will not compile. The process of debugging a program frees it of all errors. Semantic errors occur when you use a correct word in the wrong context in program code. Procedural programming is a style of programming in which sets of operations are executed one after another in sequence.
An application is a program that performs a task for the user. Variables are named computer memory locations that hold values that might vary. Procedures are sets of operations performed by a computer program.
A procedural program calls a series of procedures to input, manipulate, and output values. Writing object-oriented programs involves creating classes, creating objects from those classes, and creating applications that use those objects. Thinking in an object-oriented manner involves envisioning program components as objects that are similar to concrete objects in the real world; then, you can manipulate the objects to achieve a desired result.
39
CHAPTER 1
Creating Your First Java Classes
Computer simulations are programs that attempt to mimic real-world activities so that their
processes can be improved or so that users can better understand how the real-world processes operate. Graphical user interfaces, or GUIs (pronounced “gooeys”) allow users to interact with a 40
program in a graphical environment. A class is 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. Attributes are the characteristics that define an object as part of a class. Properties are attributes of a class.
An object is an instance of a class. An instance of a class is an object. To instantiate is to create an instance. The state of an object is the set of values for its attributes. A method is a self-contained block of program code, similar to a procedure. Encapsulation refers to the hiding of data and methods within an object. Inheritance is the ability to create classes that share the attributes and methods of existing
classes, but with more specific features. Polymorphism describes the feature of languages that allows the same word to be interpreted
correctly in different situations based on the context. Java was developed by Sun Microsystems as an object-oriented language used both for
general-purpose business applications and for interactive, World Wide Web-based Internet applications. Architecturally neutral describes the feature of Java that allows you to write programs that run on any platform (operating system).
The Java Virtual Machine (JVM) is a hypothetical (software-based) computer on which Java runs. Interactive applications are those in which a user communicates with a program by using an
input device. Source code consists of programming statements written in a high-level programming
language. Bytecode consists of programming statements that have been compiled into binary format.
The Java interpreter is a program that checks bytecode and communicates with the operating system, executing the bytecode instructions line by line within the Java Virtual Machine.
Key Terms “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. Applets are Java programs that are embedded in a Web page. Java applications are stand-alone Java programs. Console applications support character output to a computer screen in a DOS window. Windowed applications create a graphical user interface (GUI) with elements such as menus, toolbars, and dialog boxes.
A literal string is a series of characters that appear exactly as entered. Any literal string in Java appears between double quotation marks. Arguments are information passed to a method so it can perform its task.
Sending arguments to a method is called passing them. The standard output device is normally the monitor. An identifier is a name of a program component such as a class, object, or variable. Unicode is an international system of character representation.
Using an uppercase letter to begin an identifier and to start each new word in an identifier is known as Pascal casing. An access specifier defines the circumstances under which a class can be accessed and the other classes that have the right to use a class. The class body is the set of data items and methods between the curly braces that follow the class header. Whitespace is any combination of nonprinting characters, such as spaces, tabs, and carriage
returns (blank lines). The Allman style is the indent style in which curly braces are aligned and each occupies its own line; it is named for Eric Allman, a programmer who popularized the style. The K & R style is the indent style in which the opening brace follows the header line; it is named for Kernighan and Ritchie, who wrote the first book on the C programming language. The keyword static means that a method is accessible and usable even though no objects of the class exist. The keyword void, when used in a method header, indicates that the method does not return any value when it is called. Program comments are nonexecuting statements that you add to a Java file for the purpose of
documentation. To comment out a statement is to turn it into a comment so the compiler will not execute its command.
41
CHAPTER 1
Creating Your First Java Classes
Line comments start with two forward slashes ( // ) and continue to the end of the current
line. Line comments can appear on a line by themselves or at the end of a line following executable code. Block comments start with a forward slash and an asterisk ( /* ) and end with an asterisk and 42
a forward slash ( */ ). Block comments can appear on a line by themselves, on a line before executable code, or on a line after executable code. Block comments also can extend across as many lines as needed. Javadoc comments are block comments that generate documentation. They begin with a forward slash and two asterisks ( /** ) and end with an asterisk and a forward slash ( */ ).
A clean build is created when you delete all previously compiled versions of a class before compiling again. JOptionPane is a Java class 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. An import statement accesses a built-in Java class that is contained in a package. A package contains a group of built-in Java classes. A compile-time error is one in which the compiler detects a violation of language syntax rules and is unable to translate the source code to machine code. Parsing is the process the compiler uses to divide source code into meaningful portions for
analysis. A logic error occurs when a program compiles successfully but produces an error during execution. A run-time error occurs when a program compiles successfully but does not execute. The Java API is the application programming interface, a collection of information about how to use every prewritten Java class. FAQs are frequently asked questions.
The JDK is the Java Development Kit. An SDK is a software development kit, or a set of tools useful to programmers.
Chapter Summary l
A computer program is a set of instructions that tells a computer what to do. You can write a program using a high-level programming language, which has its own syntax, or rules of the language. After you write a program, you use a compiler or interpreter to translate the language statements into machine code.
Review Questions l
Writing object-oriented programs involves creating classes, creating objects from those classes, and creating applications—stand-alone executable programs that use those objects, which are similar to concrete objects in the real world. Object-oriented programming languages support encapsulation, inheritance, and polymorphism.
l
A program written in Java is run on a standardized hypothetical computer called the Java Virtual Machine (JVM). When your class is compiled into bytecode, an interpreter within the JVM subsequently interprets the bytecode and communicates with your operating system to produce the program results.
l
Everything that you use within a Java program must be part of a class; the contents of all classes are contained within opening and closing curly braces. Methods within classes hold statements. All Java programming statements end with a semicolon. Periods (called dots) are used to separate classes, objects, and methods in program code. All Java applications must have a method named main(). Most Java applications have additional methods.
l
Program comments are nonexecuting statements that you add to a file for the purpose of documentation. Java provides you with three types of comments: line comments, block comments, and javadoc comments.
l
To compile your source code from the command line, type javac followed by the name of the file that contains the source code. When you compile your source code, the compiler creates a file with a .class extension. You can run the .class file on any computer that has a Java language interpreter by entering the java command followed by the name of the class file. When you modify a class, you must recompile it for the changes to take effect.
l
Java provides you with built-in classes that produce GUI output. For example, Java contains a class named JOptionPane that allows you to produce dialog boxes.
l
To avoid and minimize syntax and logic errors, you must enter code carefully and closely examine your program’s output.
Review Questions 1.
The most basic circuitry-level computer language, which consists of on and off switches, is _____________. a. a high-level language b. machine language
2.
c. Java d. C++
Languages that let you use a vocabulary of descriptive terms, such as read, write, or add, are known as _____________ languages. a. high-level b. machine
c. procedural d. object-oriented
43
CHAPTER 1
3.
Creating Your First Java Classes
The rules of a programming language constitute its _____________. a. objects b. logic
44
4.
A _____________ translates high-level language statements into machine code. a. programmer b. syntax detector
5.
c. addresses d. appellations
The individual operations used in a computer program are often grouped into logical units called _____________. a. procedures b. variables
7.
c. compiler d. decipherer
Named computer memory locations are called _____________. a. compilers b. variables
6.
c. format d. syntax
c. constants d. logistics
Envisioning program components as objects that are similar to concrete objects in the real world is the hallmark of _____________. a. command-line operating systems b. procedural programming c. object-oriented programming d. machine languages
8.
The values of an object’s attributes also are known as its _____________. a. state b. orientation
9.
c. methods d. condition
An instance of a class is a(n) _____________. a. object b. procedure
c. method d. class
10. Java is architecturally _____________. a. specific b. oriented
c. neutral d. abstract
11. You must compile classes written in Java into _____________. a. bytecode b. source code
c. javadoc statements d. object code
Review Questions
12. All Java programming statements must end with a _____________. a. period b. comma
c. semicolon d. closing parenthesis
13. Arguments to methods always appear within _____________. a. parentheses b. double quotation marks
c. single quotation marks d. curly braces
14. In a Java program, you must use _____________ to separate classes, objects, and methods. a. commas b. semicolons
c. dots d. forward slashes
15. All Java applications must have a method named _____________. a. method() b. main()
c. java() d. Hello()
16. Nonexecuting program statements that provide documentation are called _____________. a. classes b. notes
c. comments d. commands
17. Java supports three types of comments: _____________, _____________, and javadoc. a. line, block b. string, literal
c. constant, variable d. single, multiple
18. After you write and save a Java application file, you _____________ it. a. interpret and then compile b. interpret and then execute
c. compile and then resave d. compile and then interpret
19. The command to execute a compiled Java application is _____________. a. run b. execute
c. javac d. java
20. You save text files containing Java source code using the file extension _____________. a. .java b. .class
c. .txt d. .src
45
CHAPTER 1
Creating Your First Java Classes
Exercises 1. For each of the following Java identifiers, note whether it is legal or illegal: a. b. c. d. e. f.
46
2.
weeklySales last character class MathClass myfirstinitial phone#
g. h. i. j. k. l.
abcdefghijklmnop 23jordan my_code 90210 year2013budget abffraternity
Name at least three attributes that might be appropriate for each of the following classes: a. TelevisionSet b. EmployeePaycheck c. PatientMedicalRecord
3.
Name at least three objects that are members of each of the following classes: a. Politician b. SportingEvent c. Book
4.
Name at least three classes to which each of these objects might belong: a. mickeyMouse b. myDogSpike c. bostonMassachusetts
5.
Write, compile, and test a class that displays your first name on the screen. Save the class as Name.java. As you work through the programming exercises in this book, you will create many files. To organize them, you might want to create a separate folder in which to store the files for each chapter.
6.
Write, compile, and test a class that displays your full name, street address, city, state, and zip code on three separate lines on the screen. Save the class as Address.java.
7.
Write, compile, and test a class that displays the following pattern on the screen: X XXX XXXXX XXXXXXX X
Save the class as Tree.java.
Exercises
8.
Write, compile, and test a class that displays your initials on the screen. Compose each initial with five lines of initials, as in the following example: J J J J J JJJJJJ
FFFFFF F FFFF F F
Save the class as Initial.java. 9. 10.
Write, compile, and test a class that displays all the objectives listed at the beginning of this chapter. Save the class as Objectives.java. Write, compile, and test a class that displays the following pattern on the screen: * * * * * * * * *
Save the class as Diamond.java. 11.
Write, compile, and test a class that uses the command window to display the following statement about comments: “Program comments are nonexecuting statements you add to a file for the purpose of documentation.” Also include the same statement in three different comments in the class; each comment should use one of the three different methods of including comments in a Java class. Save the class as Comments.java.
12.
Modify the Comments.java program in Exercise 11 so that the statement about comments is displayed in a dialog box. Save the class as CommentsDialog.java.
13.
From 1925 through 1963, Burma Shave advertising signs appeared next to highways all across the United States. There were always four or five signs in a row containing pieces of a rhyme, followed by a final sign that read “Burma Shave.” For example, one set of signs that has been preserved by the Smithsonian Institution reads as follows: Shaving brushes You'll soon see 'em On a shelf In some museum Burma Shave
Find a classic Burma Shave rhyme on the Web. Write, compile, and test a class that produces a series of four dialog boxes so that each displays one line of a Burma Shave slogan in turn. Save the class as BurmaShave.java.
47
CHAPTER 1
14.
48
Creating Your First Java Classes
Write a Java application to display an attractive layout of the information in a typical business card. Data items in a typical business card include a name, address, city, state, zip code, home phone number, and work phone number. Save the class as CardLayout.java.
Debugging Exercise 15.
Each of the following files in the Chapter.01 folder in your downloadable student files has syntax and/or logic errors. In each case, determine the problem and fix the errors. After you correct the errors, save each file using the same filename preceded with Fix. For example, DebugOne1.java will become FixDebugOne1.java. a. DebugOne1.java
c. DebugOne3.java
b. DebugOne2.java
d. DebugOne4.java
When you change a filename, remember to change every instance of the class name within the file so that it matches the new filename. In Java, the filename and class name must always match.
Game Zone 16.
In 1952, A. S. Douglas wrote his University of Cambridge Ph.D. dissertation on human-computer interaction, and created the first graphical computer game—a version of Tic-Tac-Toe. The game was programmed on an EDSAC vacuum-tube mainframe computer. The first computer game is generally assumed to be “Spacewar!”, developed in 1962 at MIT; the first commercially available video game was “Pong,” introduced by Atari in 1973. In 1980, Atari’s “Asteroids” and “Lunar Lander” became the first video games to be registered in the U. S. Copyright Office. Throughout the 1980s, players spent hours with games that now seem very simple and unglamorous; do you recall playing “Adventure,” “Oregon Trail,” “Where in the World is Carmen Sandiego?,” or “Myst”? Today, commercial computer games are much more complex; they require many programmers, graphic artists, and testers to develop them, and large management and marketing staffs are needed to promote them. A game might cost many millions of dollars to develop and market, but a successful game might earn hundreds of millions of dollars. Obviously, with the brief introduction to programming you have had in this chapter, you cannot create a very sophisticated game. However, you can get started. For games to hold your interest, they almost always include some random, unpredictable behavior. For example, a game in which you shoot asteroids loses some of its fun if the asteroids follow the same, predictable path each time you play the game. Therefore, generating random values is a key component in creating most interesting computer games.
Exercises
Appendix D contains information on generating random numbers. To fully understand the process, you must learn more about Java classes and methods. However, for now, you can copy the following statement to generate and use a dialog box that displays a random number between 1 and 10: JOptionPane.showMessageDialog(null,"The number is " + (1 + (int)(Math.random() * 10)));
Write a Java application that displays two dialog boxes in sequence. The first asks you to think of a number between 1 and 10. The second displays a randomly generated number; the user can see whether his or her guess was accurate. (In future chapters you will improve this game so that the user can enter a guess and the program can determine whether the user was correct. If you wish, you also can tell the user how far off the guess was, whether the guess was high or low, and provide a specific number of repeat attempts.) Save the file as RandomGuess.java.
49
This page intentionally left blank
CHAPTER
Using Data In this chapter, you will: Use constants and variables Use integer data types Use the boolean data type Use floating-point data types Use the char data type Display data and perform arithmetic Understand numeric type conversion Use the Scanner class to accept keyboard input Use the JOptionPane class for GUI input
2
CHAPTER 2
Using Data
Using Constants and Variables You can categorize data items as constant or variable. A data item is constant when its value cannot be changed while a program is running; a data item is variable when its value might change. For example, when you include the following statement in a Java class, the number 459 is a constant: 52
System.out.println(459);
Every time an application containing the constant 459 is executed, the value 459 is displayed. Programmers refer to the number 459 as a literal constant because its value is taken literally at each use. The number 459 is also a numeric constant as opposed to a character or string constant. Additionally, it is an unnamed constant as opposed to a named one, because no identifier is associated with it. A literal numeric constant contains digits and an optional sign that indicates whether the constant is positive or negative. Floating-point constants also contain a decimal point. In the new Java 7, an int or long can contain underscores to improve readability. For example, you can write the value one million as either 1000000 or 1_000_000.
On the other hand, you can set up a data item as a variable. A variable is a named memory location that you can use to store a value. A variable can hold only one value at a time, but the value it holds can change. For example, if you create a variable named ovenTemperature, it might hold 0 when the application starts, later be altered to hold 350, and still later be altered to hold 400. Whether a data item is variable or constant, in Java it always has a data type. 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. Java provides for eight primitive types of data. A primitive type is a simple data type. The eight types are described in Table 2-1. Keyword
Description
byte
Byte-length integer
short
Short integer
int
Integer
long
Long integer
float
Single-precision floating point
double
Double-precision floating point
char
A single character
boolean
A Boolean value (true or false)
Table 2-1
Java primitive data types
The eight primitive data types are called “primitive” because they are simple and uncomplicated. Primitive types also serve as the building blocks for more complex data types, called reference types. The value of a reference type is a memory address. The classes you will begin creating in Chapter 3 are examples of reference types, as is the Scanner class you will use later in this chapter.
Using Constants and Variables
Declaring Variables A variable declaration is a statement that reserves a named memory location and includes the following: l
A data type that identifies the type of data that the variable will store
l
An identifier that is the variable’s name
l
An optional assignment operator and assigned value, if you want a variable to contain an initial value
l
An ending semicolon
You name variables using the same naming rules as you do for legal class identifiers. Basically, variable names must start with a letter and cannot be a reserved keyword. You must declare all variables you want to use in a class, and you must declare them before you can use them. Java is a strongly typed language, or one in which all variables must be declared before they can be used. Variable names conventionally begin with lowercase letters to distinguish them from class names. However, as with class names, a program can compile without error even if names are constructed unconventionally. Beginning an identifier with a lowercase letter and capitalizing subsequent words within the identifier is a style known as camel casing. An identifier such as lastName resembles a camel because of the uppercase “hump” in the middle.
For example, the following declaration creates a variable of type int named myAge and assigns it an initial value of 25: int myAge = 25;
This declaration is a complete statement that ends in a semicolon. The equal sign ( = ) is the assignment operator. Any value to the right of the equal sign is assigned to the variable on the left of the equal sign. An assignment made when you declare a variable is an initialization; an assignment made later is simply an assignment. Thus, the first statement that follows is an initialization, and the second is an assignment: int myAge = 25; myAge = 42;
You declare a variable just once, but you might assign new values to it any number of times. The assignment operator means “is assigned the value of the following expression.” In other words, the statement myAge = 25 can be read as “myAge is assigned the value of the following expression: 25.”
Note that an expression with a literal to the left of the assignment operator (such as 25 = myAge) is illegal. The assignment operator has right-to-left associativity. Associativity refers to the order
53
CHAPTER 2
Using Data
in which values are used with operators. The associativity of every operator is either right-to-left or left-to-right.
54
An identifier that can appear on the left side of an assignment statement sometimes is referred to as an lvalue. A numeric constant like 25 is not an lvalue; it is only an rvalue, or an item that can appear only on the right side of an assignment statement. A variable can be used as an lvalue or an rvalue, but a literal number can only be an rvalue.
The following variable declaration also declares a variable of type int named myAge, but no value is assigned at the time of creation: int myAge;
If you attempt to display a variable that has not been assigned a value, or use it as part of a calculation, you receive an error message stating that the variable might not have been initialized. Java protects you from inadvertently using the unknown value (known as a garbage value) that is stored in an uninitialized variable. When you learn about creating classes in the chapter Using Methods, Classes, and Objects, you will discover that variables declared in a class, but outside any method, are automatically initialized for you.
You can declare multiple variables of the same type in separate statements. You also can declare two (or more) variables of the same type in a single statement by separating the variable declarations with a comma, as shown in the following statement: int myAge = 25, yourAge = 19;
By convention, programmers declare most variables in separate statements. You might declare multiple variables in the same statement only if they are closely related. Remember that even if a statement occupies multiple lines, the statement is not complete until the semicolon is reached. You can declare as many variables in a statement as you want, as long as the variables are the same data type. However, if you want to declare variables of different types, you must use a separate statement for each type.
Declaring Named Constants A variable is a named memory location for which the contents can change. If a named location’s value should not change during the execution of a program, you can create it to be a named constant. A named constant is also known as a symbolic constant. A named constant is similar to a variable in that it has a data type, a name, and a value. A named constant differs from a variable in several ways:
Using Constants and Variables l
In its declaration statement, the data type of a named constant is preceded by the keyword final.
l
A named constant can be assigned a value only once, and then it can never be changed. Usually you initialize a named constant when you declare it; if you do not initialize the constant at declaration, it is known as a blank final, and you can assign a value later. You can assign a value to a final variable only once, and you must assign a value before the variable is used.
l
Although it is not a requirement, named constants conventionally are given identifiers using all uppercase letters, using underscores as needed to separate words.
For example, each of the following defines a named constant: final final final final
int NUMBER_OF_DEPTS = 20; double PI = 3.14159; double TAX_RATE = 0.015; string COMPANY = "ABC Manufacturing";
You can use each of these named constants anywhere you can use a variable of the same type, except on the left side of an assignment statement. In other words, after they receive their initial values, named constants are rvalues. A constant always has the same value within a program, so you might wonder why you cannot use the actual, literal value. For example, why not code 20 when you need the number of departments instead of going to the trouble of creating the NUMBER_OF_DEPTS named constant? There are several good reasons to use the named constant rather than the literal one: l
The number 20 is more easily recognized as the number of departments if it is associated with an identifier. Using named constants makes your programs easier to read and understand. Some programmers refer to the use of a literal numeric constant, such as 20, as using a magic number—a value that does not have immediate, intuitive meaning or a number that cannot be explained without additional knowledge. These programmers prefer that you use a named variable or constant in place of every numeric value. For example, you might write a program that uses the value 7 several times, or you might use constants such as DAYS_IN_WEEK and NUM_RETAIL_OUTLETS that both hold the value 7 but more clearly describe its purpose. Avoiding magic numbers helps provide internal documentation for your programs.
l
If the number of departments in your organization changes, you would change the value of NUMBER_OF_DEPTS at one location within your program—where the constant is defined— rather than searching for every use of 20 to change it to a different number. Being able to make the change at one location saves you time, and prevents you from missing a reference to the number of departments.
l
Even if you are willing to search for every instance of 20 in a program to change it to the new department number value, you might inadvertently change the value of one instance of 20 that is being used for something else, such as a payroll deduction value.
55
CHAPTER 2
56
Using Data
l
Using named constants reduces typographical errors. For example, if you must include 20 at several places within a program, you might inadvertently type 10 for one of the instances.
l
When you use a named constant in an expression, it stands out as separate from a variable. For example, in the following arithmetic statement, it is easy to see which elements are variable and which are constant because the constants have been named conventionally: double payAmount = hoursWorked * STD_PAY_RATE – numDependents * DEDUCTION; Although many programmers use named constants to stand for most of the constant values in their programs, many make an exception when using 0 or 1.
The Scope of Variables and Constants A data item’s scope is the area in which it is visible to a program and in which you can refer to it using its simple identifier. A variable or constant is in scope from the point it is declared until the end of the block of code in which the declaration lies. Frequently, this means a variable or constant can be used from its declaration until the end of the method in which it is declared. However, if a method contains multiple sets of curly braces, then a data item is usable only until the end of the block that holds the declaration. In the chapter Using Methods, Classes, and Objects you will start to create classes that contain multiple sets of curly braces. In the chapter More Object Concepts you will learn some techniques for using variables that are not currently in scope.
Pitfall: Forgetting That a Variable Holds One Value at a Time Each constant can hold only one value for the duration of its program; each variable can hold just one value at a time. Suppose you have two variables, x and y, and x holds 2 and y holds 10. Suppose further that you want to switch their values so that x holds 10 and y holds 2. You cannot simply make an assignment such as x = y because then both variables will hold 10, and the 2 will be lost. Similarly, if you make the assignment y = x, then both variables will hold 2, and the 10 will be lost. The solution is to declare and use a third variable, as in the following sequence of events: int z = x = y =
x = 2, y = 10, z; x; y; z;
In this example, the third variable, z, is used as a temporary holding spot for one of the original values. The variable z is assigned the value of x, so z becomes 2. Then the value of y, 10, is assigned to x. Finally, the 2 held in z is assigned to y. The extra variable is used because as soon as you assign a value to a variable, any value that was previously in the memory location is gone. Watch the video Declaring Variables and Constants.
Learning About Integer Data Types
TWO TRUTHS & A LIE Using Constants and Variables 1. A variable is a named memory location that you can use to store a value; it can hold only one value at a time, but the value it holds can change. 2. An item’s data type determines what legal identifiers can be used to describe variables and whether the variables can occupy memory. 3. A variable declaration is a statement that reserves a named memory location and includes a data type, an identifier, an optional assignment operator and assigned value, and an ending semicolon. The false statement is #2. An item’s data type describes the type of data that can be stored, how much memory the item occupies, and what types of operations can be performed on the data. The data type does not alter the rules for a legal identifier, and the data type does not determine whether variables can occupy memory—all variables occupy memory.
Learning About Integer Data Types In Java, you can use variables of types byte, short, int, and long to store (or hold) integers; an integer is a whole number without decimal places. The int data type is the most commonly used integer type. A variable of type int can hold any whole number value from –2,147,483,648 to +2,147,483,647. When you assign a value to an int variable, you do not type any commas or periods; you type only digits and an optional plus or minus sign to indicate a positive or negative integer. The legal integer values are –231 through 231–1. These are the highest and lowest values that you can store in four bytes of memory, which is the size of an int variable.
The types byte, short, and long are all variations of the integer type. The byte and short types occupy less memory and can hold only smaller values; the long type occupies more memory and can hold larger values. Table 2-2 shows the upper and lower value limits for each of these types.
57
CHAPTER 2
58
Using Data
Type
Minimum Value
Maximum Value
Size in Bytes
byte
−128
127
1
short
−32,768
32,767
2
int
−2,147,483,648
2,147,483,647
4
long
−9,223,372,036,854,775,808
9,223,372,036,854,775,807
8
Table 2-2
Limits on integer values by type
In other programming languages, the format and size of primitive data types might depend on the platform on which a program is running. In contrast, Java consistently specifies the size and format of its primitive data types.
It is important to choose appropriate types for the variables you will use in an application. If you attempt to assign a value that is too large for the data type of the variable, the compiler issues an error message and the application does not execute. If you choose a data type that is larger than you need, you waste memory. For example, a personnel application might use a byte variable for number of dependents (because a limit of 127 is more than enough), a short for hours worked in a month (because 127 isn’t enough), and an int for an annual salary (because even though a limit of 32,000 might be large enough for your salary, it isn’t enough for the CEO’s). Some famous glitches have occurred because programmers did not pay attention to the limits of various data types. For example, a hospital computer system in Washington, D.C. used the equivalent of a short to count days elapsed since January 1, 1900. The system collapsed on the 32,768th day (which was in 1989), requiring manual operations for a lengthy period.
If an application uses a literal constant integer, such as 932, the number is an int by default. If you need to use a constant higher than 2,147,483,647, you must follow the number with the letter L to indicate long. For example, the following statement stores a number that is greater than the maximum limit for the int type. long mosquitosInTheNorthWoods = 2444555888L;
You can type either an uppercase or lowercase L after the digits to indicate the long type, but the uppercase L is preferred to avoid confusion with the number 1. You need no special notation to store a numeric constant in a byte or a short. Because integer constants, such as 18, are type int by default, the examples in this book almost always declare a variable as type int when the variable’s purpose is to hold a whole number. That is, even if the expected value is less than 127, such as hoursWorkedToday, this book will declare the variable to be an int. If you are writing an application in which saving memory is important, you might choose to declare the same variable as a byte.
Using the boolean Data Type
TWO TRUTHS & A LIE Learning About Integer Data Types 1. A variable of type int can hold any whole number value from approximately negative two billion to positive two billion. 2. When you assign a value to an int variable, you do not type any commas; you type only digits and an optional plus or minus sign to indicate a positive or negative integer. 3. You can use the data types byte or short to hold larger values than can be accommodated by an int. The false statement is #3. You use a long if you know you will be working with very large values; you use a byte or a short if you know a variable will need to hold only small values.
Using the boolean Data Type Boolean logic is based on true-or-false comparisons. Whereas an int variable can hold millions of different values (at different times), a boolean variable can hold only one of two values—true or false. The following statements declare and assign appropriate values to Boolean variables: boolean isItPayday = false; boolean areYouBroke = true;
You also can assign values based on the result of comparisons to Boolean variables. Java supports six relational operators that are used to make comparisons. A relational operator compares two items; it is sometimes called a comparison operator. An expression that contains a relational operator has a Boolean value. Table 2-3 describes the relational operators. When you use Boolean as an adjective, as in Boolean operators, you usually begin with an uppercase B because the data type is named for Sir George Boole, the founder of symbolic logic, who lived from 1815 to 1864. The Java data type boolean, however, begins with a lowercase b.
59
CHAPTER 2
60
Using Data
Operator
Description
True Example
False Example
4
==
Equal to
7 == 7
3 == 9
= 2
!=
Not equal to
5 != 6
3 != 3
Table 2-3
Relational operators
When you use any of the operators that have two symbols ( ==, =, or != ), you cannot place any whitespace between the two symbols. You also cannot reverse the order of the symbols. That is, =, and =! are all invalid operators. Legal declaration statements might include the following statements, which compare two values directly: boolean isSixBigger = (6 > 5); // Value stored would be true boolean isSevenSmallerOrEqual = (7 40); boolean isTaxBracketHigh = (income > 100000); boolean isFirstScoreHigher = (score1 > score2);
Learning About Floating-Point Data Types
TWO TRUTHS & A LIE Using the boolean Data Type 1. A Boolean variable can hold only one of two values—true or false. 2. Java supports six relational operators that are used to make comparisons: =, , =, and =!. 3. An expression that contains a relational operator has a Boolean value. The false statement is #2. The six relational operators used to make comparisons are == (two equal signs), , = (the greater-than sign precedes the equal sign), and != (the exclamation point precedes the equal sign).
Learning About Floating-Point Data Types A floating-point number contains decimal positions. Java supports two floating-point data types: float and double. A float data type can hold floating-point values of up to six or seven significant digits of accuracy. A double data type requires more memory than a float, and can hold 14 or 15 significant digits of accuracy. The term significant digits refers to the mathematical accuracy of a value. For example, a float given the value 0.324616777 displays as 0.324617 because the value is accurate only to the sixth decimal position. Table 2-4 shows the minimum and maximum values for each floating-point data type. A float given the value 324616777 displays as 3.24617e+008, which means approximately 3.24617 times 10 to the 8th power, or 324617000. The e in the displayed value stands for exponent; the +008 means the true decimal point is eight positions to the right of where it is displayed, indicating a very large number. (A negative number would indicate that the true decimal point belongs to the left, indicating a very small number.) This format is called scientific notation. The large value contains only six significant digits.
A programmer might choose to store a value as a float instead of a double to save memory. However, if high levels of accuracy are needed, such as in graphics-intensive software, the programmer might choose to use a double, opting for high accuracy over saved memory.
Type float double
Table 2-4
Minimum –3.4 * 10
38
–1.7 * 10
308
Limits on floating-point values
Maximum
Size in Bytes
3.4 * 10
38
4
1.7 * 10
308
8
61
CHAPTER 2
Using Data
A value written as 3.4 * 1038 indicates that the value is 3.4 multiplied by 10 to the 38th power, or 10 with 38 trailing zeros—a very large number.
A value stored in a double is a double-precision floating-point number; a value in a float is a single-precision floating-point number.
Just as an integer constant, such as 178, is a value of type int by default, a floating-point constant, such as 18.23, is a double by default. To store a value explicitly as a float, you can type the letter F after the number, as in the following: float pocketChange = 4.87F;
You can type either a lowercase or an uppercase F. You also can type D (or d) after a floatingpoint constant to indicate it is a double, but even without the D, the value will be stored as a double by default. Floating-point numbers can be imprecise, as you will see later in this chapter.
TWO TRUTHS & A LIE Learning About Floating-Point Data Types 1. Java supports two floating-point data types: float and double. The double data type requires more memory and can hold more significant digits. 2. A floating-point constant, such as 5.6, is a float by default. 3. As with integers, you can perform the mathematical operations of addition, subtraction, multiplication, and division with floating-point numbers. The false statement is #2. A floating-point constant, such as 5.6, is a double by default.
62
Working with the char Data Type You use the char data type to hold any single character. You place constant character values within single quotation marks because the computer stores characters and integers differently. For example, the following are typical character declarations: char middleInitial = 'M'; char gradeInChemistry = 'A'; char aStar = '*';
Working with the char Data Type
Some programmers prefer to pronounce char as care because it represents the first syllable in the word character. Others prefer to pronounce the word as char to rhyme with car. You should use the preferred pronunciation in your organization.
A character can be any letter—uppercase or lowercase. It might also be a punctuation mark or digit. A character that is a digit is represented in computer memory differently than a numeric value represented by the same digit. For example, the following two statements are legal: char aCharValue = '9'; int aNumValue = 9;
If you display each of these values using a println() statement, you see a 9. However, only the numeric value, aNumValue, can be used to represent the value 9 in arithmetic statements. A numeric constant can be stored in a character variable and a character that represents a number can be stored in a numeric variable. For example, the following two statements are legal, but unless you understand their meanings, they might produce undesirable results: char aCharValue = 9; int aNumValue = '9';
If these variables are used in the following println() statement, then the resulting output produces a blank for aCharValue and the number 57 for aNumValue: System.out.println("aCharValue is " + aCharValue + "aNumValue is " + aNumValue);
The unexpected values are Unicode values. Every computer stores every character it uses as a number; every character is assigned a unique numeric code using Unicode. Table 2-5 shows some Unicode decimal values and their character equivalents. For example, the character ‘A’ is stored using the value 65 and the character ‘B’ is stored using the value 66. Appendix B contains more information on Unicode. Dec
Char
Dec
0
nul
32
1
soh^A
33
2
stx^B
3
Dec
Char
Dec
Char
64
@
96
`
!
65
A
97
a
34
“
66
B
98
b
etx^C
35
#
67
C
99
c
4
eot^D
36
$
68
D
100
d
5
enq^E
37
%
69
E
101
e
6
ask^F
38
&
70
F
102
f
7
bel^G
39
‘
71
G
103
g
8
bs^H
40
(
72
H
104
h
Table 2-5
Char
Unicode values 0 through 127 and their character equivalents (continues )
63
CHAPTER 2
Using Data
(continued)
64
Dec
Char
Dec
Char
Dec
Char
Dec
Char
9
ht^I
41
)
73
I
105
i
10
lf^J
42
*
74
J
106
j
11
vt^K
43
+
75
K
107
k
12
ff^L
44
,
76
L
108
l
13
cr^M
45
-
77
M
109
m
14
so^N
46
.
78
N
110
n
15
si^O
47
/
79
O
111
o
16
dle^P
48
0
80
P
112
p
17
dc1^Q
49
1
81
Q
113
q
18
dc2^R
50
2
82
R
114
r
19
dc3^S
51
3
83
S
115
s
20
dc4^T
52
4
84
T
116
t
21
nak^U
53
5
85
U
117
u
22
syn^V
54
6
86
V
118
v
23
etb^W
55
7
87
W
119
w
24
can^X
56
8
88
X
120
x
25
em^Y
57
9
89
Y
121
y
26
sub^Z
58
:
90
Z
122
z
27
esc
59
;
91
[
123
{
28
fs
60
94
^
126
~
31
us
63
?
95
_
127
del
Table 2-5
Unicode values 0 through 127 and their character equivalents
A variable of type char can hold only one character. To store a string of characters, such as a person’s name, you must use a data structure called a String. In Java, String is a built-in class that provides you with the means for storing and manipulating character strings. Unlike single characters, which use single quotation marks, string constants are written between double quotation marks. For example, the expression that stores the name Audrey as a string in a variable named firstName is: String firstName = "Audrey";
Working with the char Data Type
You will learn more about strings and the String class in the chapter Characters, Strings, and the StringBuilder.
You can store any character—including nonprinting characters such as a backspace or a tab— in a char variable. To store these characters, you can use an escape sequence, which always begins with a backslash followed by a character—the pair represents a single character. For example, the following code stores a newline character and a tab character in the char variables aNewLine and aTabChar: char aNewLine = '\n'; char aTabChar = '\t';
In the declarations of aNewLine and aTabChar, the backslash and character pair acts as a single character; the escape sequence serves to give a new meaning to the character. That is, the literal characters in the preceding code have different values from the “plain” characters ‘n’ or ‘t’. Table 2-6 describes some common escape sequences that you can use with command window output in Java.
Escape Sequence
Description
\b
Backspace; moves the cursor one space to the left
\t
Tab; moves the cursor to the next tab stop
\n
Newline or linefeed; moves the cursor to the beginning of the next line
\r
Carriage return; moves the cursor to the beginning of the current line
\"
Double quotation mark; displays a double quotation mark
\'
Single quotation mark; displays a single quotation mark
\\
Backslash; displays a backslash character
Table 2-6
Common escape sequences
When you display values within JOptionPane dialog boxes rather than in a command window, the escape sequences ‘ \n’ (newline), ‘ \"’ (double quote), and ‘ \\’ (backslash) operate as expected within a JOptionPane object, but ‘ \t ’, ‘ \b’, and ‘ \r ’ do not work in the GUI environment.
When you want to produce console output on multiple lines in the command window, you have two options: You can use the newline escape sequence, or you can use the println() method multiple times. For example, Figures 2-1 and 2-2 both show classes that produce the same output: “Hello” on one line and “there” on another. The version you choose to use is up to you. The example in Figure 2-1 is more efficient—from a typist’s point of view because the text System.out.println appears only once, and from the compiler’s point of view because the println() method is called only once. The example in Figure 2-2, however, might be easier to read and understand. When programming in Java, you will find occasions when each of these approaches makes sense.
65
CHAPTER 2
public class HelloThereNewLine { public static void main(String[] args) { System.out.println("Hello\nthere"); } }
Figure 2-1
HelloThereNewLine class
public class HelloTherePrintlnTwice { public static void main(String[] args) { System.out.println("Hello"); System.out.println("there"); } }
Figure 2-2
HelloTherePrintlnTwice class
The println() method uses the local platform’s line terminator character, which might or might not be the newline character ‘ \n’.
TWO TRUTHS & A LIE Working with the char Data Type 1. You use the char data type to hold any single character; you place constant character values within single quotation marks. 2. To store a string of characters, you use a data structure called a Text; string constants are written between parentheses. 3. An escape sequence always begins with a backslash followed by a character; the pair represents a single character. The false statement is #2. To store a string of characters, you use a data structure called a String; string constants are written between double quotation marks.
66
Using Data
Displaying Data and Performing Arithmetic
Displaying Data and Performing Arithmetic You can display a variable or a constant in a print() or println() statement alone or in combination with a string. For example, the NumbersPrintln class shown in Figure 2-3 declares an integer billingDate, which is initialized to 5. In the first shaded statement, the value of billingDate is sent alone to the print() method; in the second shaded statement, billingDate is combined with, or concatenated to, a String. In Java, when a numeric variable is concatenated to a String using the plus sign, the entire expression becomes a String. The println() method can accept either a number or a String, so both statements work. The output of the application shown in Figure 2-3 appears in Figure 2-4. When a method like println() can accept different argument types, the method is overloaded. When a method is overloaded, it means there are multiple versions with the same name that can be used with a variety of options. You will learn about overloaded methods in the chapter More Object Concepts.
public class NumbersPrintln { public static void main(String[] args) { int billingDate = 5; System.out.print("Bills are sent on day "); System.out.print(billingDate); System.out.println(" of the month"); System.out.println("Next bill: October " + billingDate); } }
Figure 2-3
NumbersPrintln class
Figure 2-4
Output of NumbersPrintln application
67
CHAPTER 2
Using Data
Later in this chapter, you will learn that a plus sign ( + ) between two numeric values indicates an addition operation. However, when you place a string on one or both sides of a plus sign, concatenation occurs. In Chapter 1, you learned that polymorphism describes the feature of languages that allows the same word or symbol to be interpreted correctly in different situations based on the context. The plus sign is polymorphic in that it indicates concatenation when used with strings but addition when used with numbers.
68
The program in Figure 2-3 uses the command line to display values, but you also can use a dialog box. Recall from Chapter 1 that you can use the showMessageDialog() method with two arguments: null, which indicates the box should appear in the center of the screen, and the String to be displayed in the box. Figure 2-5 shows a NumbersDialog class that uses the showMessageDialog() method twice to display an integer declared as creditDays and initialized to 30. In each shaded statement in the class, the numeric variable is concatenated to a String, making the entire second argument a String. In the first shaded statement, the concatenated String is an empty String (or null String), created by typing a set of quotes with nothing between them. The application produces the two dialog boxes shown in Figures 2-6 and 2-7. The first dialog box shows just the value 30; after it is dismissed by clicking OK, the second dialog box appears. import javax.swing.JOptionPane; public class NumbersDialog { public static void main(String[] args) { int creditDays = 30; JOptionPane.showMessageDialog(null, "" + creditDays); JOptionPane.showMessageDialog (null, "Every bill is due in " + creditDays + " days"); } }
Figure 2-5
NumbersDialog class
Figure 2-6
First dialog box created by NumbersDialog application
Displaying Data and Performing Arithmetic
69
Figure 2-7
Second dialog box created by NumbersDialog application
Performing Arithmetic Table 2-7 describes the five standard arithmetic operators. You use arithmetic operators to perform calculations with values in your programs. A value used on either side of an operator is an operand. For example, in the expression 45 + 2, the numbers 45 and 2 are operands. The arithmetic operators are examples of binary operators, so named because they require two operands. You will learn about the Java shortcut arithmetic operators in the chapter Looping.
Operator
Description
Example
+
Addition
45 + 2, the result is 47
–
Subtraction
45 – 2, the result is 43
*
Multiplication
45 * 2, the result is 90
/
Division
45.0 / 2, the result is 22.5 45 / 2, the result is 22 (not 22.5)
%
Remainder (modulus)
45 % 2, the result is 1 (that is, 45 / 2 = 22 with a remainder of 1)
Table 2-7
Arithmetic operators
When you perform paper-and-pencil division, you divide first to determine a remainder. In Java, you do not need to perform a division operation before you can perform a remainder operation. A remainder operation can stand alone.
CHAPTER 2
Using Data
The operators / and % deserve special consideration. Java supports two types of division: l
Floating-point division occurs when either or both of the operands are floating-point values. For example, 45.0 / 2 is 22.5.
l
Integer division occurs when both of the operands are integers. The result is an integer,
and any fractional part of the result is lost. For example, the result of 45 / 2 is 22. As another example, 39 / 5 is 7 because 5 goes into 39 seven whole times; 38 / 5, 37 / 5, 36 / 5, and 35 / 5 all evaluate to 7.
70
The percent sign is the remainder operator. The remainder operator is most often used with two integers, and the result is an integer with the value of the remainder after division takes place. For example, the result of 45 % 2 is 1 because 2 goes into 45 twenty-two times with a remainder of 1. Other examples of remainder operations include the following: l
39 % 5 is 4 because 5 goes into 39 seven times with a remainder of 4.
l
20 % 3 is 2 because when 20 is divided by 3, the remainder is 2. 36 % 4 is 0 because there is no remainder when 4 is divided into 36. The remainder operator is also called the modulus operator, or sometimes just mod. Mathematicians would argue that remainder is the better term because in Java, the result of using the remainder operator can be negative, but in mathematics, the result of a modulus operation can never be negative. You also can perform remainder operations using floating-point values, but it is seldom useful to do so. In Java, when you use the % operator with floating-point values, the result is the remainder from a rounded division.
When you combine mathematical operations in a single statement, you must understand both associativity and precedence. The associativity of arithmetic operators with the same precedence is left to right. In a statement such as answer = x + y + z;, the x and y are added first, producing a temporary result, and then z is added to the temporary sum. After the sum is computed, the result is assigned to answer. Operator precedence refers to the rules for the order in which parts of a mathematical expression are evaluated. The multiplication, division, and remainder operators have the same precedence. Their precedence is higher than that for the addition and subtraction operators. Addition and subtraction have the same precedence. In other words, multiplication, division, and remainder always take place from left to right prior to addition or subtraction in an expression. For example, the following statement assigns 14 to result: int result = 2 + 3 * 4;
The multiplication operation (3 * 4) occurs before adding 2. You can override normal operator precedence by putting the operation to perform first in parentheses. The following statement assigns 20 to result: int result = (2 + 3) * 4;
The addition within the parentheses takes place first, and then the intermediate result (5) is multiplied by 4. When multiple pairs of parentheses are used in a statement, the innermost expression surrounded by parentheses is evaluated first. For example, the value of the following expression is 46: 2 * (3 + (4 * 5))
Displaying Data and Performing Arithmetic
First, 4 * 5 evaluates to 20, and then 3 is added, giving 23. Finally, the value is multiplied by 2, giving 46. Remembering that *, /, and % have the same precedence is important in arithmetic calculations. These operations are performed from left to right, regardless of the order in which they appear. For example, the value of the following expression is 9: 25 / 8 * 3
First, 25 is divided by 8. The result is 3 because with integer division, you lose any remainder. Then 3 is multiplied by 3, giving 9. If you assumed that * was performed before /, you would calculate an incorrect answer. You will learn more about operator precedence in the chapter Making Decisions.
Writing Arithmetic Statements Efficiently You can make your programs operate more efficiently if you avoid unnecessary repetition of arithmetic statements. For example, suppose you know the values for an employee’s hourly pay and pay rate and you want to compute state and federal withholding tax based on known rates. You could write two statements as follows: stateWithholding = hours * rate * STATE_RATE; federalWithholding = hours * rate * FED_RATE;
With this approach, you perform the multiplication of hours * rate twice. It is more efficient to perform the calculation once, as follows: grossPay = hours * rate; stateWithholding = grossPay * STATE_RATE; federalWithholding = grossPay * FED_RATE;
The time saved is very small, but these savings would be more important if the calculation was more complicated or if it was repeated many times in a program. As you think about the programs you write, remain on the lookout for ways to improve efficiency by avoiding duplication of operations.
Pitfall: Not Understanding Imprecision in Floating-Point Numbers Integer values are exact, but floating-point numbers frequently are only approximations. For example, when you divide 1.0 by 3.0, the mathematical result is 0.3333333..., with the 3s continuing infinitely. No matter how many decimal places you can store, the result is only an approximation. Even values that don’t repeat indefinitely in our usual numbering system, such as 0.1, cannot be represented precisely in the binary format used by computers. Imprecision leads to several problems: Appendix B provides a more thorough explanation of numbering systems and why fractional values cannot be represented accurately.
71
CHAPTER 2
72
Using Data
l
When you produce floating-point output, it might not look like what you expect or want.
l
When you make comparisons with floating-point numbers, the comparisons might not be what you expect or want.
For example, Figure 2-8 shows a class in which an answer is computed as 2.20 – 2.00. Mathematically, the result should be 0.20. But, as the output in Figure 2-9 shows, the result is calculated as a value that is slightly more than 0.20, and when answer is compared to 0.20, the result is false. public class ImprecisionDemo { public static void main(String[] args) { double answer = 2.20 - 2.00; boolean isEqual = answer == 0.20; System.out.println("answer is " + answer); System.out.println("isEqual is " + isEqual); } }
Figure 2-8
The ImprecisionDemo program
Figure 2-9
Execution of the ImprecisionDemo program
For now, you might choose to accept the slight imprecisions generated when you use floating-point numbers. However, if you want to eliminate the imprecisions, you can use one of several techniques to round values. Appendix C contains directions on how to round numbers and how to format a floating-point number so it displays the desired number of decimal positions. Several movies have used the fact that floating-point numbers are not precise as a plot element. For example, in the movies Superman III and Office Space, thieves round currency values and divert the remaining fractions of cents to their own accounts.
Watch the video Arithmetic.
Understanding Numeric Type Conversion
TWO TRUTHS & A LIE Displaying Data and Performing Arithmetic 1. In Java, when a numeric value is concatenated to a String using the plus sign, the entire expression becomes a String. 2. The arithmetic operators are examples of unary operators, which are so named because they perform one operation at a time. 3. In Java, operator precedence dictates that multiplication, division, and remainder always take place prior to addition or subtraction in an expression. The false statement is #2. The arithmetic operators are examples of binary operators, which are so named because they require two operands.
Understanding Numeric Type Conversion When you perform arithmetic with variables or constants of the same type, the result of the operation retains the same type. For example, when you divide two ints, the result is an int, and when you subtract two doubles, the result is a double. Often, however, you might want to perform mathematical operations on operands with unlike types. When you perform arithmetic operations with operands of unlike types, Java chooses a unifying type for the result. The unifying type is the type to which all operands in an expression are converted so that they are compatible with each other. Java performs an implicit conversion; that is, it automatically converts nonconforming operands to the unifying type. Implicit conversions also are called promotions. The following list shows the order for establishing unifying types between values: 1.
double
2.
float
3.
long
4.
int
When two unlike types are used in an expression, the unifying type is the one with the lower number in this list. In other words, the operand that is a type with a higher number in this list is converted to the type of the one that has a lower number. For example, the addition of a double and an int results in a double, and the subtraction of a long from a float results in a float. Boolean values cannot be converted to another type. In some languages, such as C++, Boolean values are actually numbers. However, this is not the case in Java.
73
CHAPTER 2
Using Data
For example, assume that an int, hoursWorked, and a double, payRate, are defined and then multiplied as follows: int hoursWorked = 37; double payRate = 6.73; double grossPay = hoursWorked * payRate;
74
The result of the multiplication is a double because when a double and an int are multiplied, the int is promoted to the higher-ranking unifying type double—the type with the lower number in the preceding list. Therefore, assigning the result to grossPay is legal. The following code will not compile because Java does not allow the loss of precision that occurs if you try to store the calculated double result in an int. int hoursWorked = 37; double payRate = 6.73; int grossPay = hoursWorked * payRate; The data types char, short, and byte all are promoted to int when used in statements with unlike types. If you perform a calculation with any combination of char, short, and byte values, the result is an int by default. For example, if you add two bytes, the result is an int, not a byte.
You can explicitly (or purposely) override the unifying type imposed by Java by performing a type cast. Type casting forces a value of one data type to be used as a value of another type. To perform a type cast, you use a cast operator, which is created by placing the desired result type in parentheses. Using a cast operator is an explicit conversion. The cast operator is followed by the variable or constant to be cast. For example, a type cast is performed in the following code: double bankBalance = 189.66; float weeklyBudget = (float) (bankBalance / 4); // weeklyBudget is 47.415, one-fourth of bankBalance The cast operator is more completely called the unary cast operator. Unlike a binary operator that requires two operands, a unary operator uses only one operand. The unary cast operator is followed by its operand.
In this example, the double value bankBalance is divided by the integer 4, and the result is a double. Then the double result is converted to a float before it is stored in weeklyBudget. Without the conversion, the statement that assigns the result to weeklyBudget would not compile. Similarly, a cast from a float to an int occurs in this code segment: float myMoney = 47.82f; int dollars = (int) myMoney; // dollars is 47, the integer part of myMoney
In this example, the float value myMoney is converted to an int before it is stored in the integer variable named dollars. When the float value is converted to an int, the decimal place values are lost. The cast operator does not permanently alter any variable’s data type; the alteration is only for the duration of the current operation.
Understanding Numeric Type Conversion
The word cast is used in a similar fashion when referring to molding metal, as in cast iron. In a Java arithmetic cast, a value is “molded” into a different type.
It is easy to lose data when performing a cast. For example, the largest byte value is 127 and the largest int value is 2,147,483,647, so the following statements produce distorted results: int anOkayInt = 200; byte aBadByte = (byte)anOkayInt; A byte is constructed from eight 1s and 0s, or binary digits. The first binary digit, or bit, holds a 0 or 1 to represent positive or negative. The remaining seven bits store the actual value. When the integer value 200 is stored in the byte variable, its large value consumes the eighth bit, turning it to a 1, and forcing the aBadByte variable to appear to hold the value –72, which is inaccurate and misleading.
You do not need to perform a cast when assigning a value to a higher unifying type. For example, when you write a statement such as the following, Java automatically promotes the integer constant 10 to be a double so that it can be stored in the payRate variable: double payRate = 10;
However, for clarity, if you want to assign 10 to payRate, you might prefer to write the following: double payRate = 10.0;
The result is identical to the result when you assign the literal integer 10 to the double variable.
TWO TRUTHS & A LIE Understanding Numeric Type Conversion 1. When you perform arithmetic operations with operands of unlike types, you must make an explicit conversion to a unifying type. 2. Summing a double, int, and float results in a double. 3. You can explicitly override the unifying type imposed by Java by performing a type cast; type casting forces a value of one data type to be used as a value of another type.
75
The false statement is #1. When you perform arithmetic operations with operands of unlike types, Java performs an implicit conversion to a unifying type.
CHAPTER 2
Using Data
Using the Scanner Class for Keyboard Input
76
In Chapter 1, you learned how to display output on the monitor using the System.out property. System.out refers to the standard output device, which usually is the monitor. Frequently you also want to create interactive programs that accept input from a user. To do so, you can use System.in, which refers to the standard input device (normally the keyboard). You can use the print() and println() methods to display many data types; for example, you can use them to display a double, int, or String. The System.in object is not as flexible; it is designed to read only bytes. That’s a problem, because you often want to accept data of other types. Fortunately, the designers of Java have created a class named Scanner that makes System.in more flexible. To create a Scanner object and connect it to the System.in object, you write a statement similar to the following: Scanner inputDevice = new Scanner(System.in);
The portion of the statement to the left of the assignment operator, Scanner inputDevice, declares an object of type Scanner with the programmer-chosen name inputDevice, in exactly the same way that int x; declares an integer with the programmer-chosen name x. The portion of the statement to the right of the assignment operator, new Scanner (System.in), creates a Scanner object that is connected to the System.in property. In other words, the created Scanner object is connected to the default input device. The keyword new is required by Java; you will use it whenever you create objects that are more complex than the simple data types. In the chapter More Object Concepts, you will learn that the second part of the Scanner declaration calls a special method called a constructor that is part of the prewritten Scanner class. You also will learn more about the Java keyword new in the next two chapters.
The assignment operator in the Scanner declaration statement assigns the value of the new object—that is, its memory address—to the inputDevice object in the program. A Scanner object breaks its input into units called tokens, separating them when it encounters whitespace. The resulting tokens can then be converted into values of different types using the various class methods. Table 2-8 summarizes some of the most useful methods that read different data types from the default input device. Each retrieves a value from the keyboard and returns it as the appropriate data type. The appropriate method executes, retrieving data when a user presses an appropriate whitespace key at the keyboard. The nextLine() method does not retrieve data until the user presses Enter; the other methods retrieve data when the user presses Enter, the spacebar, or the tab key.
Using the Scanner Class for Keyboard Input
Method
Description
nextDouble()
Retrieves input as a double
nextInt()
Retrieves input as an int
nextLine()
Retrieves the next line of data and returns it as a String
next()
Retrieves the next complete token as a String
Table 2-8
Selected Scanner class methods
In addition to the methods listed in Table 2-8, the Scanner class contains methods called nextByte(), nextFloat(), nextLong(), and nextShort() that work as you would expect based on their identifiers.
The Scanner class does not contain a nextChar() method. To retrieve a single character from the keyboard, you can use the nextLine() method and then use the charAt() method. The chapter Characters, Strings, and the StringBuilder provides more details about the charAt() method.
Figure 2-10 contains a program that uses two of the Scanner class methods. The program reads a string and an integer from the keyboard and displays them. The Scanner class is used in the four shaded statements in the figure. l
The first shaded statement is import java.util.Scanner;. This statement imports the package necessary to use the Scanner class.
l
The second shaded statement declares a Scanner object named inputDevice.
l
The third shaded statement uses the nextLine() method to retrieve a line of text from the keyboard and store it in the name variable.
l
The last shaded statement uses the nextInt() method to retrieve an integer from the keyboard and store it in the age variable.
Figure 2-11 shows a typical execution of the program. Java programmers would say that the Scanner methods return the appropriate value. That also means that the value of the method is the appropriate value, and that you can assign the returned value to a variable, display it, or use it in other legal statements. In the chapter Using Methods, Classes, and Objects, you will learn how to write your own methods that return values.
77
CHAPTER 2
78
Using Data
import java.util.Scanner; public class GetUserInfo { public static void main(String[] args) { String name; int age; Scanner inputDevice = new Scanner(System.in); System.out.print("Please enter your name >> "); 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."); } }
Figure 2-10
The GetUserInfo class
Figure 2-11
Typical execution of the GetUserInfo program
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 in the program in Figure 2-10 are examples of prompts. A prompt is a message displayed for the user that requests and describes input. Interactive programs would work without prompts, but they would not be as user-friendly. Each prompt in the GetUserInfo class ends with two greater-than signs and a space. This punctuation is not required; it just separates the words in the prompt from the user’s input value on the screen, improving readability.
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-12. It is identical to the one in Figure 2-10, except that the user is asked for an age before being asked for a name. (See shading.) Figure 2-13 shows a typical execution.
Using the Scanner Class for Keyboard Input
Don’t Do It
If you accept numeric input import java.util.Scanner; prior to string input, the public class GetUserInfo2 string input is ignored { unless you take special public static void main(String[] args) action. { 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 + " years old."); } }
Figure 2-12
The GetUserInfo2 class
Figure 2-13
Typical execution of the GetUserInfo2 program
In Figure 2-13, 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-13. When you type characters using the keyboard, they are stored temporarily in a location in memory called the keyboard buffer. The keyboard buffer sometimes is called the type-ahead buffer. All keystrokes are stored in the keyboard buffer, including the Enter key. The problem occurs because of a difference in the way the nextLine() method and the other Scanner retrieval methods work: l
The Scanner methods next(), nextInt(), and nextDouble() retrieve the next token in the buffer up to the next whitespace, which might be a space, tab, or Enter key.
l
The nextLine() method reads all data up to the Enter key character.
So, in the execution of the program in Figure 2-13, the user is prompted for an age, types 22, and presses Enter. The call to the nextInt() method retrieves the 22 and leaves the Enter key
79
CHAPTER 2
Using Data
press in the input buffer. Then the name prompt is displayed and the call to nextLine() retrieves the waiting Enter key before the user can type a name.
80
The solution to the problem is simple. After any next(), nextInt(), or nextDouble() call, you can add an extra nextLine() method call that will retrieve the abandoned Enter key character. Then, no matter what type of input follows, the program will execute smoothly. Figure 2-14 shows a program that contains just one change from Figure 2-12—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. Figure 2-14 shows that the call to nextInt() accepts the integer, the first 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-15 shows that the revised program executes correctly. import java.util.Scanner; public class GetUserInfo3 This statement gets { the integer. public static void main(String[] args) { String name; int age; Scanner inputDevice = new Scanner(System.in); This statement System.out.print("Please enter your age >> "); consumes the Enter age = inputDevice.nextInt(); key that follows the inputDevice.nextLine(); integer. System.out.print("Please enter your name >> "); name = inputDevice.nextLine(); System.out.println("Your name is " + name + This statement gets " and you are " + age + " years old."); the name and } discards the Enter } key that follows the name.
Figure 2-14
The GetUserInfo3 class
Figure 2-15
Typical execution of the GetUserInfo3 program
Using the JOptionPane Class for GUI Input
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 later in this book.
81
TWO TRUTHS & A LIE Using the Scanner Class for Keyboard Input 1. System.in refers to the standard input device, which normally is the keyboard. 2. System.in is more flexible than System.out 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. System.in is not as flexible as System.out. System.out can display various data types, but System.in 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 also can accept input in a GUI dialog box using the JOptionPane class. Two dialog boxes that can be used to accept user input are: l l
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 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.
CHAPTER 2
Using Data
Earlier in this chapter you learned that println() also 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.
82
For example, Figure 2-16 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. In the application in Figure 2-16, the response is concatenated with a welcoming message and displayed in a message dialog box. Figure 2-17 shows the dialog box containing a user’s response, and Figure 2-18 shows the resulting output message box. 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-16
The HelloNameDialog class
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: l
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.
Figure 2-17 application
Input dialog box of the HelloNameDialog
Figure 2-18 application
Output of the HelloNameDialog
Using the JOptionPane Class for GUI Input l
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.
l
The title to be displayed in the title bar of the input dialog box.
l
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.
For example, when the following statement executes, it displays the input dialog box shown in Figure 2-19. JOptionPane.showInputDialog(null, "What is your area code?", "Area code information", JOptionPane.QUESTION_MESSAGE);
Note that the title bar displays “Area code information,” and the dialog box shows a question mark icon.
Figure 2-19
An input dialog box with a String in the title bar and 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 primitive type values. Figure 2-20 shows a SalaryDialog application that contains two String objects— and dependentsString. Two showInputDialog() methods are called, and the answers are stored in the declared Strings. The shaded statements in Figure 2-20 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() wageString
83
CHAPTER 2
Using Data
method, and the integer is converted using the Integer.parseInt() method. Figure 2-21 shows a typical execution of the application.
84
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. 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.
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-20
The SalaryDialog class
Using the JOptionPane Class for GUI Input
85
Figure 2-21
Sample execution of the SalaryDialog application
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-22 shows an application that asks a user a question. The shaded statement displays the dialog box shown in Figure 2-23 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-22
The AirlineDialog class
CHAPTER 2
Using Data
86 Figure 2-23
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-24 shows the result when a user clicks the Yes button in the dialog box.
Figure 2-24 Output of AirlineDialog application when user clicks Yes
You can also create a confirm dialog box with five arguments, as follows: l
The parent component, which can be null
l
The prompt message
l
The title to be displayed in the title bar
l
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.)
l
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-25: JOptionPane.showConfirmDialog(null, "A data input error has occurred. Continue?", "Data input error", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE);
You Do It
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. Confirm dialog boxes provide more practical uses when your applications can make decisions based on the users’ responses. In the chapter Making Decisions, you will learn how to make decisions within programs.
87 Figure 2-25 Confirm dialog box with title, Yes and No buttons, and error icon
TWO TRUTHS & 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. Watch the video Getting Input.
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. Create a class header and an opening and closing curly brace for a new class named DemoVariables by typing the following:
CHAPTER 2
Using Data
public class DemoVariables { }
2. Indent a few spaces on the next line and type the following main() method header and its curly braces: 88
public static void main(String[] args) { } 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.
3. Between the main() method’s curly braces, type the following variable declaration: int entry = 315; 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.
4. 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 space before the closing quotation mark creates a space between the literal string and the displayed value in the second statement. The second statement uses the println() method instead of print() so that the insertion point advances to a new line after entry is displayed. System.out.print("The entry is "); System.out.println(entry);
5. Save the file as DemoVariables.java. 6. Compile the file from the command line by typing javac DemoVariables.java. If necessary, correct any errors, save the file, and then compile again. 7. Execute the application from the command line by typing java DemoVariables. The command window output is shown in Figure 2-26.
Figure 2-26 application
Output of the DemoVariables
You Do It
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. 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. 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-27 shows a typical execution. 8. Execute the program several times using different values, including negative numbers, and confirm that the program works as expected. Then exe- Figure 2-27 Output of the DemoVariables2 application cute the program and type an invalid entry—for example, an integer that is too large, a floating-point value, or a letter of the alphabet. Figure 2-28 shows the error messages generated when the user types something other than an integer.
89
CHAPTER 2
Using Data
90
Figure 2-28 program
Error messages generated when the user enters an “X” into the DemoVariables2
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-28 might look intimidating, but you should remember two points: l
First, if you read the messages carefully, you will find they provide some useful information. 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.
l
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();
You Do It
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-29. 7. Make sure to execute the DemoVariables3 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.
Experimenting with Java Programs
Figure 2-29
Output of the DemoVariables3 application
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?
91
CHAPTER 2
Using Data
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. 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?
92
5. Open the DemoVariables3.java file in your text editor, and change the class name to DemoVariables6. Immediately save the file as DemoVariables6.java. 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 floating-point 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 because the integers are cast to doubles. 6. Open the DemoVariables3.java file in your text editor, and change the class name to DemoVariables7. Immediately save the file as DemoVariables7.java. Following the two existing variable declarations, declare a String as follows: String name;
7. 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);
8. 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();
9. Save, compile, and execute the program. This time, you are able to enter a name, and the program executes as expected.
Don’t Do It l
Don’t mispronounce integer. People who are unfamiliar with the term often say interger, inserting an extra r.
l
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.
Key Terms l
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.
l
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.
l
Don’t forget that floating-point numbers are imprecise.
l
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.
l
Don’t use a single equal sign ( = ) in a Boolean comparison for equality. The operator used for equivalency is composed of two equal signs ( == ).
l
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.
l
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).
l
Don’t forget to consume the Enter key after numeric input using the Scanner class when a nextLine() method call follows.
l
Don’t forget to use the appropriate import statement when using the Scanner or JOptionPane class.
Key Terms Constant describes values that cannot be changed during the execution of an application.
A literal constant is a value that is taken literally at each use. A numeric constant is a number whose value is taken literally at each use. An unnamed constant has no identifier associated with it. 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 primitive type is a simple data type. Java’s primitive types are byte, short, int, long, float, and boolean.
double, char,
Reference types are complex data types that are constructed from primitive types.
93
CHAPTER 2
Using Data
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 94
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.
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 value cannot change during program execution. A symbolic constant is a named constant. The keyword final precedes named constant declarations. 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 scope of a data item is the area in which it is visible to a program and in which you can refer to it using its simple identifier. An integer is a whole number without decimal places. The data type int is used to declare variables and constants that store integers. 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 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. A floating-point number contains decimal positions.
Key Terms
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. 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. Concatenated describes values that are attached end to end.
A null String is an empty String created by typing a set of quotes with nothing between them. Arithmetic operators are used to perform calculations with values.
An operand is a value used in an arithmetic statement. Binary operators require two operands. Floating-point division is the operation in which two values are divided and either or both are
floating-point values. Integer division is the operation in which two values are divided and both are integers; 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 modulus operator, sometimes abbreviated as mod, is an alternate name for the remainder operator. Operator precedence is the rules for the order in which parts of a mathematical expression
are evaluated. 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.
95
CHAPTER 2
Using Data
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. 96
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 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. An input dialog box asks a question and provides a text field in which the user can enter a response. The showInputDialog() method creates an input dialog box. 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 l
l
Variables are named memory locations in which programs store values; the value of a variable can change. 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.
Review Questions l
A boolean type variable can hold a true or false value. Java supports six relational operators: >, =, 1 5 = 43 2 == 3 2 + 5 == 7
f. g. h. i. j.
3 + 8 FULL_WEEK) { regularPay = FULL_WEEK * rate; overtimePay = (hoursWorked – FULL_WEEK) * OT_RATE * rate; }
219
The if structure ends here. false
hoursWorked > FULL_WEEK?
true
regularPay = FULL_WEEK * rate
overtimePay = (hoursWorked – FULL_WEEK) * OT_RATE * rate
Figure 5-6
An if structure that determines pay
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.
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, standalone 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. 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.
CHAPTER 5
Making Decisions
Don’t Do It
The if structure ends here.
220
if(hoursWorked > FULL_WEEK) regularPay = FULL_WEEK * rate; overtimePay = (hoursWorked – FULL_WEEK) * OT_RATE * rate; This indentation is ignored by the compiler. false
Don’t Do It
hoursWorked > FULL_WEEK?
true
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 always executes. 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.
Using Multiple Statements in an if or if … else Structure
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
221
CHAPTER 5
Making Decisions
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: Don’t Do It The sum variable is not recognized here.
TWO TRUTHS & A LIE Using Multiple Statements in 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.
222
if(a == b) { int sum = a + b; System.out.println ("The two variables are equal"); } System.out.println("The sum is " + sum);
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 $1,000 in value during a specified time. Figure 5-10 shows the logic and the code to solve the problem.
Nesting if and if … else Statements
false
itemsSold >= MIN_ITEMS?
false
true final int final int final int int bonus
totalValue >= true MIN_VALUE? bonus = SALES_BONUS
MIN_ITEMS = 3; MIN_VALUE = 1000; SALES_BONUS = 50; = 0;
if(itemsSold >= MIN_ITEMS) if(totalValue >= MIN_VALUE) bonus = SALES_BONUS;
The Boolean expression in each if statement must be true for the bonus assignment to be made.
Figure 5-10
Determining whether to assign a bonus using nested if statements
Notice 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. 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 $1,000, the bonus is $25. If the salesperson sells at least three items whose combined value is at least $1,000, the bonus is $50.
223
CHAPTER 5
false
Making Decisions
itemsSold >= MIN_ITEMS?
final final final final final
true
224 bonus = SMALL_BONUS
int int int int int
MIN_ITEMS = 3; MIN_VALUE = 1000; LARGE_BONUS= 50; MEDIUM_BONUS = 25; SMALL_BONUS = 10;
int bonus = 0; false
bonus = MEDIUM_BONUS
totalValue >= MIN_VALUE?
true
bonus = LARGE_BONUS
if(itemsSold >= MIN_ITEMS) if(totalValue >= MIN_VALUE) bonus = LARGE_BONUS; else bonus = MEDIUM_BONUS; else bonus = SMALL_BONUS;
The last else goes with the first if.
Figure 5-11
Determining one of three bonuses using nested if statements
As Figure 5-11 shows, when one if statement follows another, the first else clause encountered is paired with the most recent if encountered. In this figure, 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. 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.
TWO TRUTHS & A LIE Nesting if and if … else Statements 1. Statements in which an if structure is contained inside another if structure commonly are 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
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. In Java, the AND operator is written as