Java Programming 9th Edition PDF by Farrell

Summary

هذا الكتاب عبارة عن نسخة إلكترونية لكتاب برمجة جافا، الإصدار التاسع، من تأليف جويس فاريل. يغطي الكتاب مفاهيم البرمجة بالكائنات، وأساليب العمل، وإنشاء البرامج، وتقديم أمثلة وتمارين متنوعة. يعتبر الكتاب مناسبًا لدراسة علوم الحاسوب.

Full Transcript

N I N T H E d iti o n JAVA™ PROGRAMMING JOYCE FARRELL Australia Brazil Mexico Singapore United Kingdom United States 97070_fm_hr_i-x...

N I N T H E d iti o n JAVA™ PROGRAMMING JOYCE FARRELL Australia Brazil Mexico Singapore United Kingdom United States 97070_fm_hr_i-xxiv.indd 1 27/02/18 7:34 pm This is an electronic version of the print textbook. Due to electronic rights restrictions, some third party content may be suppressed. Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. The publisher reserves the right to remove content from this title at any time if subsequent rights restrictions require it. For valuable information on pricing, previous editions, changes to current editions, and alternate formats, please visit www.cengage.com/highered to search by ISBN#, author, title, or keyword for materials in your areas of interest. Important Notice: Media content referenced within the product description or the product text may not be available in the eBook version. Java™ Programming, Ninth Edition © 2019, 2016, 2014, 2012 Cengage Learning, Inc. Joyce Farrell Unless otherwise noted, all content is © Cengage. ALL RIGHTS RESERVED. No part of this work covered by the c­ opyright SVP, GM Skills: Jonathan Lau herein may be reproduced or distributed in any form or by any means, except as permitted by U.S. copyright law, without the prior Product Team Manager: Kristin McNary written permission of the copyright owner. Associate Product Manager: Unless otherwise noted all screenshots are courtesy of Microsoft Kate Mason Corporation. Unless otherwise noted all tables/figures exhibits are © 2019 Cengage®. Executive Director of Content Design, Skills: Marah Bellegarde Director, Learning Design – For product information and technology assistance, contact us at Skills Computing: Leigh Hefferon Cengage Customer & Sales Support, 1-800-354-9706 Learning Designer: or support.cengage.com. Natalie Onderdonk For permission to use material from this text or product, submit all requests online at www.cengage.com/permissions. Product Assistant: Jake Toth Marketing Director: Michele McTighe Marketing Manager: Stephanie Albracht Library of Congress Control Number: 2018933919 Content Project Manager: Softbound ISBN: 978-1-337-39707-0 Michele Stulga Loose Leaf ISBN: 978-1-337-68590-0 Senior Designer: Diana Graham Cengage Production Service/Composition: 20 Channel Center Street SPi Global Boston, MA 02210 USA Cover image: Colormos/Photodisc /Getty Images Cengage is a leading provider of customized learning solutions with employees residing in nearly 40 different countries and sales in more than 125 countries around the world. Find your local representative at www.cengage.com. Cengage products are represented in Canada by Nelson Education, Ltd. To learn more about Cengage platforms and services, visit www.cengage.com. To register or access your online learning solution or purchase materials for your course, visit www.cengagebrain.com. Notice to the Reader Publisher does not warrant or guarantee any of the products described herein or perform any independent analysis in connection with any of the product information contained herein. Publisher does not assume, and expressly disclaims, any obligation to obtain and include information other than that provided to it by the manufacturer. The reader is expressly warned to consider and adopt all safety precautions that might be indicated by the activities described herein and to avoid all potential hazards. By following the instructions contained herein, the reader willingly assumes all risks in connection with such instructions. The publisher makes no representations or warranties of any kind, including but not limited to, the warranties of fitness for particular purpose or merchantability, nor are any such representations implied with respect to the material set forth herein, and the publisher takes no responsibility with respect to such material. The publisher shall not be liable for any special, consequential, or exemplary damages resulting, in whole or part, from the readers’ use of, or reliance upon, this material. Printed in the United States of America Print Number: 01 Print Year: 2018 97070_fm_hr_i-xxiv.indd 2 27/02/18 7:34 pm Brief Contents iii Pref ace  xiv CHAPTER 1 Creat in g Jav a Programs 1 Chapter 2 U s in g Dat a  49 Chapter 3 U s in g M et hods, Cl asses, and Obj ects  110 Chapter 4 M o re Object Concepts  170 Chapter 5 M ak in g De ci si ons  230 Chapter 6 Lo o pin g 283 Chapter 7 Ch ar act er s, Stri ngs, and the St ri ng Bu ilder  330 Chapter 8 Ar r ays  369 Chapter 9 Advan ced Array Concepts  416 Chapter 10 In t ro du ct ion to I nheri tance  467 Chapter 11 Advan ced I nheri tance Concepts  513 Chapter 12 Except io n Handl i ng 570 Chapter 13 F ile In pu t and Output  635 Chapter 14 In t ro du ct ion to Swing Components  698 Chapter 15 U s in g J avaFX and Scene Bui l der  758 Append ix A Wo r k in g wi th the Jav a Pl atform  799 Append ix B Dat a Representati on  804 Append ix C F o r m at t in g Output  810 Append ix D Gen er at in g R andom Numbers  820 Append ix E J avado c  826 Glo s s ar y  834 In dex  853 97070_fm_hr_i-xxiv.indd 3 27/02/18 7:34 pm 97070_fm_hr_i-xxiv.indd 4 27/02/18 7:34 pm Table of Contents v Pref ace  xiv CHAPTER 1 Creat in g Jav a Programs  1 Learning Programming Terminology  2 Comparing Procedural and Object-Oriented Programming Concepts  5 Procedural Programming  5 Object-Oriented Programming 6 Understanding Classes, Objects, and Encapsulation 7 Understanding Inheritance and Polymorphism 9 Features of the Java Programming Language 10 Analyzing a Java Application that Produces Console Output 12 Understanding the Statement that Produces the Output  13 Understanding the First Class 15 Understanding the main() Method  17 Indent Style  19 Saving a Java Class  20 Compiling a Java Class and Correcting Syntax Errors  22 Compiling a Java Class 22 Correcting Syntax Errors  23 Running a Java Application and Correcting Logic Errors  29 Running a Java Application  29 Modifying a Compiled Java Class  29 Correcting Logic Errors  31 Adding Comments to a Java Class 32 Creating a Java Application that Produces GUI Output 35 Finding Help 38 Don’t Do It  39 Key Terms 41 Chapter Summary  41 Exercises  45 97070_fm_hr_i-xxiv.indd 5 27/02/18 7:34 pm c o ntent s   CHAP TER 2 U s in g Dat a  49 Declaring and Using Constants and Variables 50 Declaring Variables 51 Declaring Named Constants 52 The Scope of Variables and Constants 54 vi Concatenating Strings to Variables and Constants 54 Pitfall: Forgetting that a Variable Holds One Value at a Time  57 Learning About Integer Data Types  60 Using the boolean Data Type 65 Learning About Floating-Point Data Types  67 Using the char Data Type  68 Using the Scanner Class to Accept Keyboard Input 74 Pitfall: Using nextLine() Following One of the Other Scanner Input Methods  77 Using the JOptionPane Class to Accept GUI Input 82 Using Input Dialog Boxes  83 Using Confirm Dialog Boxes 86 Performing Arithmetic Using Variables and Constants  88 Associativity and Precedence  89 Writing Arithmetic Statements Efficiently 91 Pitfall: Not Understanding Imprecision in Floating-Point Numbers  91 Understanding Type Conversion 96 Automatic Type Conversion 96 Explicit Type Conversions 97 Don’t Do It  101 Key Terms 102 Chapter Summary  102 Exercises  105 CHAP TER 3 U s in g M et hods, Cl asses, and Obj ects  110 Understanding Method Calls and Placement  111 Understanding Method Construction 114 Access Specifiers  115 Return Type  116 Method Name  116 Parentheses 117 Adding Parameters to Methods  121 Creating a Method that Receives a Single Parameter  122 Creating a Method that Requires Multiple Parameters  125 Creating Methods that Return Values 127 Chaining Method Calls 129 97070_fm_hr_i-xxiv.indd 6 27/02/18 7:34 pm  Contents Learning About Classes and Objects 133 Creating a Class 136 Creating Instance Methods in a Class  138 Organizing Classes 141 Declaring Objects and Using Their Methods  145 Understanding Data Hiding  147 vii An Introduction to Using Constructors  150 Understanding that Classes Are Data Types  154 Don’t Do It  158 Key Terms 158 Chapter Summary  159 Exercises  163 CHAPTER 4 M o re Object Concepts  170 Understanding Blocks and Scope 171 Overloading a Method  179 Automatic Type Promotion in Method Calls  181 Learning About Ambiguity 185 Creating and Calling Constructors with Parameters  187 Overloading Constructors 188 Learning About the this Reference  192 Using the this Reference to Make Overloaded Constructors More Efficient  195 Using static Fields 199 Using Constant Fields  201 Using Automatically Imported, Prewritten Constants and Methods  206 The Math Class  206 Importing Classes that Are Not Imported Automatically  208 Using the LocalDate Class  210 Understanding Composition and Nested Classes  216 Composition 216 Nested Classes 218 Don’t Do It  220 Key Terms 220 Chapter Summary  220 Exercises  224 CHAPTER 5 M ak in g De ci si ons  230 Planning Decision-Making Logic  231 The if and if…else Statements  233 The if Statement  233 Pitfall: Misplacing a Semicolon in an if Statement 234 97070_fm_hr_i-xxiv.indd 7 27/02/18 7:34 pm c o ntent s   Pitfall: Using the Assignment Operator Instead of the Equivalency Operator  235 Pitfall: Attempting to Compare Objects Using the Relational Operators 236 The if…else Statement  236 viii Using Multiple Statements in if and if…else Clauses 239 Nesting if and if…else Statements  245 Using Logical AND and OR Operators  247 The AND Operator  247 The OR Operator 249 Short-Circuit Evaluation 250 Making Accurate and Efficient Decisions  253 Making Accurate Range Checks  253 Making Efficient Range Checks 256 Using && and || Appropriately  256 Using the switch Statement  258 Using the Conditional and NOT Operators  264 Using the NOT Operator  265 Understanding Operator Precedence 266 Adding Decisions and Constructors to Instance Methods 269 Don’t Do It  272 Key Terms 273 Chapter Summary  273 Exercises  277 CHAP TER 6 Lo o pin g  283 Learning About the Loop Structure  284 Creating while Loops  285 Writing a Definite while Loop  285 Pitfall: Failing to Alter the Loop Control Variable Within the Loop Body  287 Pitfall: Unintentionally Creating a Loop with an Empty Body 288 Altering a Definite Loop’s Control Variable 289 Writing an Indefinite while Loop  290 Validating Data  292 Using Shortcut Arithmetic Operators 296 Creating a for Loop 300 Unconventional for Loops  302 Learning How and When to Use a do…while Loop  306 Learning About Nested Loops 308 Improving Loop Performance  313 Avoiding Unnecessary Operations  314 97070_fm_hr_i-xxiv.indd 8 27/02/18 7:34 pm  Contents Considering the Order of Evaluation of Short-Circuit Operators  314 Comparing to Zero 315 Employing Loop Fusion 316 A Final Note on Improving Loop Performance 317 Don’t Do It  320 ix Key Terms 320 Chapter Summary  320 Exercises  324 CHAPTER 7 Characters, Strings, and the StringBuilder  330 Understanding String Data Problems 331 Using Character Class Methods  332 Declaring and Comparing String Objects  336 Comparing String Values  336 Empty and null Strings  340 Using a Variety of String Methods  342 Converting String Objects to Numbers 347 Learning About the StringBuilder and StringBuffer Classes 352 Don’t Do It  358 Key Terms 359 Chapter Summary  359 Exercises  362 CHAPTER 8 Ar r ays  369 Declaring an Array 370 Initializing an Array 375 Using Variable Subscripts with an Array  378 Using the Enhanced for Loop 380 Using Part of an Array  380 Declaring and Using Arrays of Objects 383 Using the Enhanced for Loop with Objects 385 Manipulating Arrays of String s 385 Searching an Array and Using Parallel Arrays 392 Using Parallel Arrays 393 Searching an Array for a Range Match 395 Passing Arrays to and Returning Arrays from Methods 399 Returning an Array from a Method 402 Don’t Do It  405 Key Terms 405 Chapter Summary  405 Exercises  409 97070_fm_hr_i-xxiv.indd 9 27/02/18 7:34 pm c o ntent s   CHAP TER 9 Advan ced Array Concepts  416 Sorting Array Elements Using the Bubble Sort Algorithm 417 Using the Bubble Sort Algorithm 418 Improving Bubble Sort Efficiency  420 Sorting Arrays of Objects 420 x Sorting Array Elements Using the Insertion Sort Algorithm  425 Using Two-Dimensional and Other Multidimensional Arrays 430 Passing a Two-Dimensional Array to a Method  433 Using the length Field with a Two-Dimensional Array 433 Understanding Jagged Arrays 434 Using Other Multidimensional Arrays 435 Using the Arrays Class 438 Using the ArrayList Class  446 Creating Enumerations  449 Don’t Do It  456 Key Terms 456 Chapter Summary  456 Exercises  460 CHAP TER 10 In t ro du ct ion to I nheri tance  467 Learning About the Concept of Inheritance  468 Diagramming Inheritance Using the UML  468 Inheritance Terminology  470 Extending Classes  472 Overriding Superclass Methods  479 Using the @Override Tag  480 Calling Constructors During Inheritance  483 Using Superclass Constructors that Require Arguments  484 Accessing Superclass Methods  489 Comparing this and super  491 Employing Information Hiding  493 Methods You Cannot Override 495 A Subclass Cannot Override static Methods in Its Superclass  495 A Subclass Cannot Override final Methods in Its Superclass  499 A Subclass Cannot Override Methods in a final Superclass  501 Don’t Do It  502 Key Terms 502 Chapter Summary  503 Exercises  506 97070_fm_hr_i-xxiv.indd 10 27/02/18 7:34 pm  Contents CHAPTER 11 Advan ced I nheri tance Concepts  513 Creating and Using Abstract Classes 514 Using Dynamic Method Binding 523 Using a Superclass as a Method Parameter Type  525 Creating Arrays of Subclass Objects 527 xi Using the Object Class and Its Methods 530 Using the toString() Method  532 Using the equals() Method  535 Using Inheritance to Achieve Good Software Design 540 Creating and Using Interfaces 541 Creating Interfaces to Store Related Constants 548 Using Anonymous Inner Classes and Lambda Expressions  552 Lambda Expressions 554 Creating and Using Packages 555 Don’t Do It  557 Key Terms 558 Chapter Summary  558 Exercises  562 CHAPTER 12 Except io n Handl i ng  570 Learning About Exceptions  571 Trying Code and Catching Exceptions 576 Using a try Block to Make Programs “Foolproof” 580 Declaring and Initializing Variables in try…catch Blocks 582 Throwing and Catching Multiple Exceptions 585 Using the finally Block 591 Understanding the Advantages of Exception Handling  593 Specifying the Exceptions that a Method Can Throw 596 Tracing Exceptions Through the Call Stack 600 Creating Your Own Exception Classes  605 Using Assertions 608 Displaying the Virtual Keyboard  622 Don’t Do It  625 Key Terms 626 Chapter Summary  626 Exercises  630 CHAPTER 13 F ile In pu t and Output 635 Understanding Computer Files  636 Using the Path and Files Classes  638 Creating a Path  638 Retrieving Information About a Path  640 97070_fm_hr_i-xxiv.indd 11 27/02/18 7:34 pm c o ntent s   Converting a Relative Path to an Absolute One  641 Checking File Accessibility 642 Deleting a Path  643 Determining File Attributes  645 File Organization, Streams, and Buffers  648 xii Using Java’s IO Classes 651 Writing to a File  654 Reading from a File  656 Creating and Using Sequential Data Files 657 Learning About Random Access Files  663 Writing Records to a Random Access Data File  667 Reading Records from a Random Access Data File  673 Accessing a Random Access File Sequentially  674 Accessing a Random Access File Randomly 675 Don’t Do It  689 Key Terms 689 Chapter Summary  689 Exercises  693 CHAP TER 14 In t ro du ct ion to Swing Components  698 Understanding Swing Components  699 Using the JFrame Class 700 Customizing a JFrame ’s Appearance  704 Using the JLabel Class 708 Changing a JLabel ’s Font 710 Using a Layout Manager  712 Extending the JFrame Class  715 Adding JTextField s and JButton s to a JFrame  718 Adding JTextField s  718 Adding JButton s  720 Learning About Event-Driven Programming  724 Preparing Your Class to Accept Event Messages 725 Telling Your Class to Expect Events to Happen  726 Telling Your Class How to Respond to Events 726 An Event-Driven Program  727 Using Multiple Event Sources  728 Using the setEnabled() Method 730 Understanding Swing Event Listeners  733 Using the JCheckBox , ButtonGroup , and JComboBox Classes  736 The JCheckBox Class  736 The ButtonGroup Class 740 The JComboBox Class  741 97070_fm_hr_i-xxiv.indd 12 27/02/18 7:34 pm  Contents Don’t Do It  748 Key Terms 749 Chapter Summary  749 Exercises  753 CHAPTER 15 U s in g J avaFX and Scene Bui l der  758 xiii What Is JavaFX?  759 The Life Cycle of JavaFX Applications 760 Understanding JavaFX Structure: Stage, Scene, Panes, and Widgets 762 Deploying JavaFX Applications  768 Creating JavaFX Applications Using Scene Builder 768 Scene Builder Sections 773 Using Widgets as Design Elements in FXML Layouts 774 Using CSS to Create Visual Effects  778 Creating Animations in JavaFX 785 Don’t Do It  790 Key Terms 790 Chapter Summary  790 Exercises  795 Append ix A Wo r k in g wi th the Jav a Pl atform  799 Append ix B Dat a Representati on  804 Append ix C F o r m at t ing Output  810 Append ix D Gen er at ing R andom Numbers  820 Append ix E J avado c  826 Glo s s ar y  834 In dex 853 97070_fm_hr_i-xxiv.indd 13 27/02/18 7:34 pm Preface xiv Java Programming, Ninth Edition, provides the beginning programmer with a guide to developing applications using the Java programming language. Java is popular among professional programmers because it can be used to build visually interesting graphical user interface (GUI) and Web-based applications. Java also provides an excellent environment for the beginning programmer—a student can quickly build useful programs while learning the basics of structured and object-oriented programming techniques. This textbook assumes that you have little or no programming experience. It provides a solid background in good object-oriented programming techniques and introduces terminology using clear, familiar language. The programming examples are business examples; they do not assume a mathematical background beyond high school business math. In addition, the examples illustrate only one or two major points; they do not contain so many features that you become lost following irrelevant and extraneous details. Complete, working programs appear frequently in each chapter; these examples help students make the transition from the theoretical to the practical. The code presented in each chapter also can be downloaded from the publisher’s website, so students easily can run the programs and experiment with changes to them. The student using Java Programming, Ninth Edition, builds applications from the bottom up rather than starting with existing objects. This facilitates a deeper understanding of the concepts used in object-oriented programming and engenders appreciation for the existing objects students use as their knowledge of the language advances. When students complete this book, they will know how to modify and create simple Java programs, and they will have the tools to create more complex examples. They also will have a fundamental knowledge about object-oriented programming, which will serve them well in advanced Java courses or in studying other object-oriented languages such as C++, C#, and Visual Basic. Organization and Coverage Java Programming, Ninth 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 about 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. 97070_fm_hr_i-xxiv.indd 14 27/02/18 7:34 pm New in This Edition P R E FA C E Chapters 10, 11, and 12 thoroughly cover inheritance and exception handling. Inheritance is the object-oriented concept that allows you to develop new objects quickly by adapting the features of existing objects; exception handling is the object-oriented approach to handling errors. Both are important concepts in object-oriented design. Chapter 13 provides information about handling files so you can store and retrieve program output. Chapter 14 introduces GUI Swing components, which are used to create visually pleasing, xv user-friendly, interactive applications. Chapter 15 introduces JavaFX, which is the newest platform for creating and delivering applications for the desktop and the Internet. Chapter 15 is written by Sandra Lavallee, a professor and Computer and Design Technologies Department chairperson at Lakes Region Community College in Laconia, New Hampshire. New in This Edition The following features are new for the Ninth Edition: Java 9e: All programs have been tested using Java 9e, the newest edition of Java. Windows 10: All programs have been tested in Windows 10, and all screen shots have been taken in this environment. Programming exercises: Each chapter contains several new programming exercises not seen in previous editions. All exercises and their solutions from the previous edition that were replaced in this edition are still available on the Instructor Companion site. Anonymous inner classes and lambda expressions: These two new topics are introduced in this edition of the book. JavaFX: This edition includes coverage of JavaFX. Additionally, Java Programming, Ninth Edition, includes the following features: OBJECTIVES: Each chapter begins with a list of objectives so you know the topics that will be presented in the chapter. In addition to providing a quick reference to topics ­covered, this feature provides a useful study aid. YOU DO IT: In each chapter, step-by-step exercises help students create multiple working programs that emphasize the logic a programmer uses in choosing statements to include. These sections provide a means for students to achieve success on their own—even those in online or distance learning classes. NOTES: These highlighted tips provide additional information—for example, an ­alternative method of performing a procedure, another term for a concept, background information about a technique, or a common error to avoid. EMPHASIS ON STUDENT RESEARCH: The student frequently is directed to the Java website to investigate classes and methods. Computer languages evolve, and programming professionals must understand how to find the latest language improvements. This book encourages independent research. 97070_fm_hr_i-xxiv.indd 15 27/02/18 7:34 pm P R E FA C E New in This Edition 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 xvi names. FILES: More than 200 student files can be downloaded from the publisher’s website. Most files contain the code presented in the figures in each chapter; students can run the code for themselves, view the output, and make changes to the code to observe the effects. Other files include debugging exercises that help students improve their programming skills. TWO TRUTHS & A LIE: A short quiz reviews each chapter section, with answers provided. This quiz contains three statements based on the preceding section of text—two statements are true, and one is false. Over the years, students have requested answers to problems, but we have hesitated to distribute them in case instructors want to use problems as assignments or test questions. These true-false quizzes provide students with immediate feedback as they read, without “giving away” answers to the multiple-choice questions and programming exercises. DON’T DO IT: This section at the end of each chapter summarizes common mistakes and pitfalls that plague new programmers while learning the current topic. KEY TERMS: Each chapter includes a list of newly introduced vocabulary, shown in the order of appearance in the text. The list of key terms provides a short review of the major concepts in the chapter. SUMMARIES: Following each chapter is a summary that recaps the programming concepts and techniques covered in the chapter. This feature provides a concise means for students to check their understanding of the main points in each chapter. REVIEW QUESTIONS: Each chapter includes 20 multiple-choice questions that serve as a review of chapter topics. GAME ZONE: Each chapter provides one or more exercises in which students can create interactive games using the programming techniques learned up to that point; 50 game programs are suggested in the book. The games are fun to create and play; writing them motivates students to master the necessary programming techniques. Students might exchange completed game programs with each other, suggesting improvements and discovering alternate ways to accomplish tasks. CASES: Each chapter contains two running case problems. These cases represent projects that continue to grow throughout a semester using concepts learned in each new chapter. Two cases allow instructors to assign different cases in alternate semesters or to divide students in a class into two case teams. GLOSSARY: A glossary contains definitions for all key terms in the book. 97070_fm_hr_i-xxiv.indd 16 27/02/18 7:34 pm Instructor Companion Site P R E FA C E APPENDICES: This edition includes useful appendices on working with the Java platform, data representation, formatting output, generating random numbers, and creating Javadoc comments. QUALITY: Every program example, exercise, and game solution was tested by the author and then tested again by a quality assurance team using Java Standard Edition (SE) 9, the most recent version available. xvii Instructor Resources MindTap MindTap activities for Java Programming, Ninth Edition are designed to help students master the skills they need in today’s workforce. Research shows employers need critical thinkers, troubleshooters, and creative problem-solvers to stay relevant in our fast-paced, technology-driven world. MindTap helps you achieve this with assignments and activities that provide hands-on practice and real-life relevance. Students are guided through assignments that help them master basic knowledge and understanding before moving on to more challenging problems. All MindTap activities and assignments are tied to defined unit learning objectives. Hands-on coding labs provide real-life application and practice. Readings and dynamic visualizations support the lecture, while a post-course assessment measures exactly how much a student has learned. MindTap provides the analytics and reporting to easily see where the class stands in terms of progress, engagement, and completion rates. Use the content and learning path as-is, or pick-and-choose how our materials will wrap around yours. You control what the students see and when they see it. Learn more at http://www.cengage.com/mindtap/. The Java Programming MindTap also includes: Unit Quizzes: Students apply what they have learned in each unit by taking the quizzes provided in the learning path. Video Lessons: Each unit is accompanied by video lessons that help to explain important unit concepts. These videos were created and narrated by the author. Interactive Study Aids: Flashcards and crossword puzzles help users review main concepts from the units and coding Snippets allow students to practice key coding concepts. Instructor Companion Site The following teaching tools are available for download at the Companion Site for this text. Simply search for this text at www.cengagebrain.com and choose “Instructor Downloads.” An instructor login is required. 97070_fm_hr_i-xxiv.indd 17 27/02/18 7:34 pm P R E FA C E Acknowledgments Instructor’s Manual: The Instructor’s Manual that accompanies this textbook includes additional instructional material to assist in class preparation, including items such as Overviews, Chapter Objectives, Teaching Tips, Quick Quizzes, Class Discussion Topics, Additional Projects, Additional Resources, and Key Terms. A sample syllabus also is available. xviii Test Bank: Cengage Testing Powered by Cognero is a flexible, online system that allows you to: ° Author, edit, and manage test bank content from multiple Cengage solutions. ° Create multiple test versions in an instant. ° Deliver tests from your LMS, your classroom, or wherever you want. PowerPoint Presentations: This text provides PowerPoint slides to accompany each chapter. Slides can be used to guide classroom presentations, to make available to students for chapter review, or to print as classroom handouts. Student Files: Files are provided for every figure in the text. Instructors can use the files to customize PowerPoint slides, illustrate quizzes, or create handouts. Solutions: Solutions to all programming exercises are available. If an input file is needed to run a programming exercise, it is included with the solution file. Data Files: Data files necessary to complete the steps and projects in the book are available at www.cengagebrain.com, or your instructor will provide the data files to you. Acknowledgments I would like to thank all of the people who helped to make this book a reality, including Natalie Onderdonk, Learning Designer; Michele Stulga, Content Project Manager; and John Freitas, Quality Assurance Tester. I am lucky to work with these professionals who are dedicated to producing high-quality instructional materials. I am also grateful to the reviewers who provided comments and encouragement during this book’s development, including Cliff Brozo, Monroe College; Fred D’Angelo, University of Arizona; Cassandra Henderson, Albany Technical College; Zack Hubbard, Rowan-Cabarrus Community College; and Sandra Lavallee, Lakes Region Community College. Thanks, too, to my husband, Geoff, for his constant support, advice, and encouragement. Finally, this book is dedicated to George Edward Farrell Peterson and Clifford Geoffrey ­Farrell Peterson. You each had a book dedicated to you earlier, but those books were ­published before I knew your names. Now you are here, and I love you! Joyce Farrell 97070_fm_hr_i-xxiv.indd 18 27/02/18 7:34 pm Using Your Own Computer P R E FA C E 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 xix To complete the steps and projects in this book, you need data files that have been created specifically for this book. Your instructor will provide the data files to you. You also can obtain the files electronically from www.CengageBrain.com. Find the ISBN of your title on the back cover of your book, then enter the ISBN in the search box at the top of the ­Cengage Brain home page. You can find the data files on the product page that opens. Note that you can use a computer in your school lab or your own computer to complete the exercises in this book. Using Your Own Computer To use your own computer to complete the steps and exercises, you need the following: Software: Java SE 9, available from www.oracle.com/technetwork/java/index.html. Although almost all of the examples in this book will work with earlier versions of Java, this book was created using Java 9e. You also need a text editor, such as Notepad. A few exercises ask you to use a browser for research. Chapter 15 uses NetBeans to develop JavaFX programs; you can downoad this software from Https:netbens.org. Hardware: For operating system requirements (memory and disk space), see http://java.com/en/download/help. 97070_fm_hr_i-xxiv.indd 19 27/02/18 7:34 pm Features This text focuses on helping students become better programmers and understand Java program development through a variety of key features. In addition to Chapter Objectives, Summaries, and Key Terms, these useful xx features will help students regardless of their learning styles. Chapter 2 Using Data YOU DO IT sections You Do It walk students through program development 58 Declaring and Using a Variable step by step. In this section, you write an application to work with a variable and a constant. 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 DataDemo by typing the following: public class DataDemo { } 2. Between the curly braces, indent a few spaces and type the following main() method header and its curly braces: public static void main(String[] args) { } 3. Between the main() method’s curly braces, type the following variable declaration: Chapter 2 Using Data int aWholeNumber = 315; 4. Type the following output statements. The first uses the print() method to boxes provide more practical uses when your applications can make decisions based on the Confirm dialog display a string that includes a space before the closing quotation users’ markresponses. and NOTES provide In the chapter “Making Decisions,” you will learn how to make decisions within programs. leaves the insertion point for the next output on the same line. The second statement uses println() to display the value of aWholeNumber and then ­additional information— advance to a new line. for example, another System.out.print("The number is "); System.out.println(aWholeNumber); 88 tWO trUthS & a LIe location in the book 5. Save the file that as DataDemo.java. Using the JOptionPane Class to Accept GUI Input expands on a6. topic, or a Up to this point in the book, every print() and println() statement you have seen has used a String as an argument. When you added1. You two the last can create an input dialog box using the showInputDialog() method; common erroranto watch statements to the DataDemo class, you wrote a println() statementthe int as an argument. As a matter of fact, there are many different method that uses returns a String that represents a user’s response. versions of methods from the Java classes Integer and Double when you 2. You can use out for. print() and println() that use different data types. Go to the (www.oracle.com/technetwork/java/index.html), select Java APIs, and Java website want to convert a dialog box’s returned values to numbers. 3. select then select Java SE 9. Scroll through the list of All Classes, and A confirm dialog box can be created using the showConfirmDialog() method in the JOptionPane class; a confirm dialog box displays the options PrintStream; you will recall from Chapter 1 that PrintStream is the data type Accept, Reject, and Escape. for the out object used with the println() method. Scroll down to view the list of methods in the Method Summary, and notice the many versions of the print() Cancel. and println() methods, including ones that accept a String, an int, a long,The false statement is #3. A confirm dialog box displays the options Yes, No, and and so on. In the last two statements you added to this program, one used a (continues) Watch the video Getting Input. 97070_ch02_hr_049-109.indd 58 performing arithmetic Using Variables and Constants 07/02/18 3:23 pm Table 2-8 describes the five standard arithmetic operators that you use to perform calcula- tions 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. The author does an You will learn about the Java shortcut arithmetic operators in the chapter “Looping.” awesome job: the examples, problems, and material are VIDEO LESSONS help explain The operators / and % deserve special consideration. Java supports two types of division: very easy to understand! important chapter concepts. Floating-point division occurs when either or both of the operands are floating-point Videosvalues.are part45.0of/ 2the For example, is 22.5.eBook in —Bernice ­Cunningham, Integer division occurs when both of the operands are integers. The result is an inte- MindTap and are also posted ger, and any fractional part of the result is lost. For on example, the result of 45 / 2 is 22. As Wayne County ­Community the Instructor Companion Site. 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. College District 97070_ch02_hr_049-109.indd 88 07/02/18 3:24 pm 97070_fm_hr_i-xxiv.indd 20 27/02/18 7:34 pm  FE eature AT U R E S s Comparing Procedural and Object-Oriented Programming Concepts TWO TRUTHS & A LIE quizzes appear TWO TRUTHS & A LIE Learning Programming Terminology after each chapter section, with answers In each “Two Truths & a Lie” section, two of the numbered statements are true, and one is false. Identify the false statement and explain why it is false. 5 provided. The quiz contains three state- 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 ments based on the preceding section of of on-and-off switches that perform the corresponding tasks. text—two statements are true and one is xxi 2. A syntax error occurs when you violate the rules of a language; locating and false. Answers give immediate feedback repairing all syntax errors is part of the process of debugging a program. 3. Logic errors are fairly easy to find because the software that translates a program finds all the logic errors for you. errors can still exist in a program that is free of syntax errors. without “giving away” answers to the multiple-choice questions and programming The false statement is #3. A language translator finds syntax errors, but logic Comparing Procedural and Object-Oriented problems later in the chapter. Students also Programming Concepts Procedural programming and object-oriented programming describe two different approaches to writing computer programs. have the option to take these quizzes in MindTap. Procedural Programming Procedural programming is a style of programming in which operations are executed one after another in sequence. The typical procedural program defines and uses named computer memory locations that are called variables. Variables hold the data a program uses. For example, data might be read from an input device and stored in a location the programmer has named rateOfPay. Chapter 3 Using Methods, Classes, and Objects The variable value might be used in an arithmetic statement, used as the basis for a decision, sent to an output device, or have other operations performed with it. The data stored in a variable can change, or vary, during a program’s execution. For convenience, the individual operations used in a computer program are often grouped (continued) 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 where it is assigned to the object used in the method call. Add a closing curly grouped as a procedure named calculateFederalWithholding(). (As a convention, this brace for the method. book will show parentheses following every procedure name.) As a procedural computer 158 service.setServiceDescription(service); executes its statements, it can sometimes pause to call a procedure. When a program service.setPrice(price); return service; } 8. Save the file, compile it, and execute it. The execution looks no different from the original version in Figure 3-28 earlier in this chapter, but by creating a method 97070_ch01_hr_001-048.indd 5 07/02/18 3:21 pm that accepts an unfilled SpaService object and returns one filled with data, you have made the main() method shorter and reused the data entry code. Don’t Do It DON’T DO IT sections at the end of Don’t place a semicolon at the end of a method header. After you get used to putting semicolons at the end of every statement, it’s easy to start putting them in too many each chapter list advice for avoiding places. Method headers never end in a semicolon. Don’t think “default constructor” means only the automatically supplied constructor. common programming errors. Any constructor that does not accept parameters is a default constructor. Don’t think that a class’s methods must accept its own fields’ values as parameters or return values to its own fields. When a class contains both fields and methods, each method has direct access to every field within the class. Don’t create a class method that has a parameter with the same identifier as a class field—yet. If you do, you will only be allowed to access the local variable within the method, and you will not be able to access the field. You will be able to use the same identifier and still access both values after you read the next chapter. For now, make sure that the parameter in any method has a different identifier from any field. Using the Scanner Class to Accept Keyboard Input Key terms method abstraction stub It is legal to write a single prompt that requests multiple input values—for example, invoke method header access modifier Please enter your age, area code, and zip code >>. The user could then enter the three call declaration return type values separated with spaces, tabs, or Enter key presses. The values would be interpreted calling method method body return a value as separate tokens and could be retrieved with three separate nextInt() method calls. called method implementation fully qualified identifier However, asking a user to enter multiple values is more likely to lead to mistakes. For example, if a program asks a user to enter a name, address, and birthdate all at once, the 77 user is likely to forget one of the values or to enter them in the wrong order. This book will follow the practice of using a separate prompt for each input value required. 97070_ch03_hr_110-169.indd 158 07/02/18 3:16 pm 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 pro- THE DON’T DO IT ICON illustrates gram in Figure 2-19. It is identical to the one in Figure 2-17, except that the user is asked for an age before being asked for a name. Figure 2-20 shows a typical execution. how NOT to do something—for import java.util.Scanner; public class GetUserInfo2 Don’t Do It If you accept numeric input prior to string input, the example, having a dead code path in a program. This icon provides a { string input is ignored public static void main(String[] args) unless you take special { action. visual jolt to the student, emphasizing 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(); that particular figures are NOT to be emulated and making students more System.out.println("Your name is " + name + " and you are " + age + " years old."); } } Figure 2-19 The GetUserInfo2 class careful to recognize problems in ­existing code. Figure 2-20 Typical execution of the GetUserInfo2 program 97070_ch02_hr_049-109.indd 77 07/02/18 3:05 pm 97070_fm_hr_i-xxiv.indd 21 27/02/18 7:34 pm Assessment I found the author’s explanation of difficult topics to be very clear and thorough. PROGRAMMING EXERCISES xxii —Leslie Spivey, provide opportunities to practice Edison Community College concepts. These exercises increase in difficulty and allow students to explore each major programming concept presented Chapter 3 Using Methods, Classes, and Objects in the chapter. Additional coding A constructor establishes an object and provides specific initial values for the object’s data fields. A constructor always has the same name as the class of which it is a member. labs and snippets are available By default, numeric fields are set to 0 (zero), character fields are set to Unicode ‘\u0000’, Boolean fields are set to false, and object type fields are set to null. in the MindTap. A class is an abstract, programmer-defined data type, similar to Java’s built-in, primitive 160 data types. Review Questions 1. In Java, methods must include all of the following except _____________. a. a call to another method c. curly braces b. a declaration d. a body 2. All method declarations contain _____________. a. arguments b. one or more explicitly named access specifiers Exercises c. parentheses d. the keyword static Exercises 3. A public static method named computeSum() is located in ClassA. To call the method from within ClassB, use the statement _____________.Programming Exercises a. ClassA.computeSum(); b. ClassB(computeSum()); 163 1. Suppose that you have created a program with only the following variables. c. ComputeSum(ClassA); d. You cannot call computeSum() from within ClassB. int x = 2; int y = 3; 4. Which of the following method declarations is correct for a static method named displayFacts() if the method receives an int argument?Suppose that you also have a method with the following header: a. public static int displayFacts() public static void mathMethod(int x) b. public void displayFacts(int data) Which of the following method calls are legal? c. public static void displayFacts(int data) a. mathMethod(x); f. mathMethod(12); d. Two of these are correct. b. mathMethod(y); g. mathMethod(12.2); 5. The method with the declaration public static int aMethod(double d) is a c. mathMethod(x, y); h. mathMethod(); method type of _____________. d. mathMethod(x + y); i. mathMethod(a); a. static e. mathMethod(12L); j. mathMethod(a / x); b. int 2. Suppose that you have created a program with only the following variables. c. double int age = 34; d. You cannot determine the method type. int weight = 180; double height = 5.9; Suppose that you also have a method with the following header: public static void calculate(int age, double size) 97070_ch03_hr_110-169.indd 160 Which of the following method 07/02/18 3:25 pmcalls are legal? a. calculate(age, weight); f. calculate(12, 120.2); b. calculate(age, height); g. calculate(age, size); c. calculate(weight, height); h. calculate(2, 3); REVIEW QUESTIONS d. e. calculate(height, age); calculate(45.5, 120); i. j. calculate(age); calculate(weight, weight); test student 3. Suppose that a class

Use Quizgecko on...
Browser
Browser