Statistics
5
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-06-14

AuthorY. Daniel Liang

For courses in Java Programming. Java Programming Concepts for AP Computer Science A Written for AP students, Introduction to Java Programming: AP Edition covers all Java programming material and concepts required as part of the AP Computer Science A curriculum. Daniel Liang teaches concepts of problem-solving and object-oriented programming using a fundamentals-first approach and effectively communicates critical problem-solving techniques to beginning programmers. The text focuses on problem solving through Java programming and emphasizes both imperative and object-oriented problem solving and design. It is divided into two parts: in the first, students learn the fundamental concepts and techniques of selection statements, loops, methods, and arrays, before building on this foundation in the second part, as the text introduces concepts of object-oriented programming. Because knowledge is cumulative, the early chapters provide the conceptual basis for understanding programming, guiding students through simple examples and exercises subsequent chapters progressively present programming and problem solving in more detail, culminating with the development of comprehensive applications. Throughout the text, understanding of Java concepts is supported by frequent practice and the use of relevant examples. Also Available with MyProgrammingLab ™ MyProgrammingLab is an online learning system designed to engage students and improve results. MyProgrammingLab consists of a set of programming exercises correlated to the programming concepts in this book. Through practice exercises and immediate, personalized feedback, MyProgrammingLab improves the programming competence of beginning students who often struggle with the basic concepts of programming languages.

AI Reading Assistant

Summary and highlights from this book's index; jump to passages in the text

Passage locations
Tags
No tags
ISBN: 0134304748
Publisher: Pearson
Publish Year: 2015
Language: 英文
Pages: 549
File Format: PDF
File Size: 10.6 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

(This page has no text content)
INTRODUCTION TO JAVA PROGRAMMING AP® EDITION Tenth Edition Y. Daniel Liang Armstrong State University ® Boston Columbus Indianapolis New York San Francisco Hoboken Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montreal Toronto Delhi Mexico City Sao Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo A01_LIAN4748_10_AP_FM.indd 1 25/11/15 2:09 pm
To Samantha, Michael, and Michelle Credits and acknowledgments borrowed from other sources and reproduced, with permission, in this textbook appear on the appropriate page within text. Microsoft® and Windows® are registered trademarks of the Microsoft Corporation in the U.S.A. and other coun- tries. Screen shots and icons reprinted with permission from the Microsoft Corporation. This book is not sponsored or endorsed by or affiliated with the Microsoft Corporation. AP® is a trademark registered and/or owned by the College Board, which was not involved in the production of, and does not endorse, this product. Copyright © 2017, 2015, 2013, 2011 Pearson Education, Inc., All rights reserved. Printed in the United States of America. This publication is protected by Copyright, and permission should be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. To obtain permission(s) to use material from this work, please submit a written request to Pearson Education, Inc., Permissions Department, 221 River Street, Hoboken, New Jersey 07030, or you may fax your request to 201-236-3290. Many of the designations by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed in initial caps or all caps. Library of Congress Cataloging-in-Publication Data available upon request. Editorial Director, ECS: Marcia Horton Executive Editor: Tracy Johnson (Dunkelberger) Editorial Assistant: Kristy Alaura Director of Marketing: Christy Lesko Product Marketing Manager: Bram van Kempen Field Marketing Manager: Demetrius Hall Marketing Assistant: Jon Bryant Director of Product Management: Erin Gregg Product Management-Team Lead: Scott Disanno Program Manager: Carole Snyder Procurement Specialist: Maura Zaldivar-Garcia Cover Designer: Marta Samsel Permissions Supervisor: Rachel Youdelman Director, Image Asset Services: Annie Atherton Cover Art: © alexpixel / Getty Images Media Project Manager: Renata Butera Full-Service Project Management: Shylaja Gattupalli, SPi Global 10 9 8 7 6 5 4 3 2 1 ISBN 10: 0-13-430474-8 (High School Binding) ISBN 13: 978-0-13-430474-8 (High School Binding)PearsonSchool.com/Advanced A01_LIAN4748_10_AP_FM.indd 2 25/11/15 2:09 pm
iii AP® Topics Mapped to the Text AP Computer Science A is equivalent to a first-semester, college level course in computer science. The course introduces problem solving and programming using Java. The topics are outlined in http://media.collegeboard.com/digitalServices/pdf/ap/ap-course- overviews/ap-computer-science-a-course-overview.pdf. Here is the mapping for the topics to the text. AP® Topic Covered in the Text Part I.A Program and class design Program design is discussed throughout the book. Class design is discussed in Chapters 9–13. Part II.A Implementation techniques Simple program implementation is introduced in Chapters 2–5. Method implementation is presented in Chapter 6. Class implementation is covered in Chapters 9–13. Part II.B Programming constructs The if-else, switch, and conditional statements are covered in Chapter 3. The loops are covered in Chapter 5. The arrays are covered in Chapters 7 and 8. The classes and objects are covered in Chapters 9–13. Part II.C Java library classes and interfaces included in the AP Java Subset The AP Java subset classes and methods are all covered, including the toString, equals methods in the Object class (Sections 11.6, 11.10), the Integer and Double classes (Section 10.7), the String class (Section 4.4 and Section 10.10), the Math class (Sec- tion 4.2), the ArrayList class (Section 11.11), and the List interface (Section 13.8). Part III.A Testing Program testing is discussed throughout the book. Part III.B Debugging Debugging techniques are covered in Chapter 2. Part III.C Runtime exceptions Chapter 12 Part III.D Program correctness Program correctness is covered throughout the book. Part III.E Algorithm analysis Chapter 7 and Chapter 14 Part III.F Numerical representations of integers Chapter 2 Part IV.A Primitive data types (int, boolean, double) Chapters 2 and 3 Part IV.B Strings Sections 4.4 and 10.10 Part IV.C Classes Chapters 9 and 10 Part IV.D Lists The ArrayList class is covered in Section 11.11 and List interface is covered in Section 13.8. Part IV.E Arrays (1-dimensional and 2-dimensional) Chapters 7 and 8 Part V.A. Operations on data structures Chapters 7, 8, 10, and 13 Part V.B Searching Linear Search is covered in Section 7.10.1. Binary search is covered in Section 11.10.2. Part V.C Sorting Selection sort is covered in Section 7.11.1. Insertion sort is covered in Section 7.11.2. Merge sort is covered in Section 14.8. A01_LIAN4748_10_AP_FM.indd 3 25/11/15 2:09 pm
This page intentionally left blank A01_LIAN4748_10_AP_FM.indd 16 12/21/15 9:20 PM
v Dear Reader, This book is an AP® Edition of Introduction to Java Programming, Tenth Edition, which is the most widely used Computer Science textbook in colleges around the world. The College Board offers AP® Computer Science A that is equivalent to a college-level course on intro- duction to Java programming. This AP edition has 14 chapters that cover all required Java materials and concepts in the AP Computer Science A curriculum. The AP® Computer Science A course is an introductory course on programming and problem solving. This book teaches programming in a problem-driven way that focuses on problem solving rather than syntax. We make introductory programming interesting by using thought-provoking problems in a broad context. The central thread of early chapters is on problem solving. Appropriate syntax and library are introduced to enable readers to write pro- grams for solving the problems. To support the teaching of programming in a problem-driven way, the book provides a wide variety of problems at various levels of difficulty to motivate students. To appeal to students in all majors, the problems cover many application areas, including math, science, business, financial, and gaming. The AP® Computer Science A course emphasizes both imperative and object-oriented problem solving and design. The book is fundamentals first by introducing basic program- ming concepts and techniques before designing custom classes. The fundamental concepts and techniques of selection statements, loops, methods, and arrays are the foundation for programming. Building this strong foundation prepares students to learn object-oriented pro- gramming. The book teaches solving problems using both imperative and object-oriented approaches. The best way to teach programming is by example, and the only way to learn program- ming is by doing. Basic concepts are explained by example and a large number of exercises with various levels of difficulty are provided for students to practice. For our programming courses, we assign programming exercises after each lecture. Our goal is to produce a text that teaches problem solving and programming in a broad context using a wide variety of interesting examples. If you have any comments on and sug- gestions for improving the book, please email me. Sincerely, Y. Daniel Liang, Ph.D. y.daniel.liang@gmail.com www.cs.armstrong.edu/liang www.pearsonhighered.com/liang Pedagogical Features The book uses the following elements to help students get the most from the material: ■ The Objectives at the beginning of each chapter list what students should learn from the chapter. This will help them determine whether they have met the objectives after complet- ing the chapter. ■ The Introduction opens the discussion with representative problems to give the reader an overview of what to expect from the chapter. problem-driven fundamentals-first examples and exercises PREFACE A01_LIAN4748_10_AP_FM.indd 5 25/11/15 2:09 pm
vi Preface ■ Key Points highlight the important concepts covered in each section. ■ Check Points, accessible online, provide review questions to help students track their progress as they read through the chapter and evaluate their learning. ■ Problems and Case Studies, carefully chosen and presented in an easy-to-follow style, teach problem solving and programming concepts. The book uses many small, simple, and stimulating examples to demonstrate important ideas. ■ The Chapter Summary reviews the important subjects that students should understand and remember. It helps them reinforce the key concepts they have learned in the chapter. ■ Quizzes are accessible online, grouped by sections, for students to do self-test on pro- gramming concepts and techniques. ■ Programming Exercises are grouped by sections to provide students with opportunities to apply the new skills they have learned on their own. The level of difficulty is rated as easy (no asterisk), moderate (*), hard (**), or challenging (***). The trick of learning pro- gramming is practice, practice, and practice. To that end, the book provides a great many exercises. Additionally, more than 50 programming exercises with solutions are provided to the instructors on the Companion Website. These exercises are not printed in the text. ■ Notes, Tips, Cautions, and Design Guides are inserted throughout the text to offer valu- able advice and insight on important aspects of program development. Note Provides additional information on the subject and reinforces important concepts. Tip Teaches good programming style and practice. Caution Helps students steer away from the pitfalls of programming errors. Design Guide Provides guidelines for designing programs. Organization of the Book The chapters in this AP edition can be grouped into two parts that, taken together, form a solid introduction to programming and problem solving using Java. Because knowledge is cumulative, the early chapters provide the conceptual basis for understanding programming and guide students through simple examples and exercises; subsequent chapters progressively present programming and problem solving in detail, culminating with the development of comprehensive applications. The appendixes contain a mixed bag of topics, including an introduction to number systems. Part I: Fundamentals of Programming (Chapters 1–8, 14) The first part of the book is a stepping stone, preparing you to embark on the journey of learn- ing Java. You will begin to learn about Java (Chapter 1) and fundamental programming tech- niques with primitive data types, variables, constants, assignments, expressions, and operators ( Chapter  2), selection statements (Chapter 3), mathematical functions, characters, and strings (Chapter 4), loops (Chapter 5), methods (Chapter 6), and arrays (Chapters 7–8). After Chapter 7, you can jump to Chapter 14 to learn how to write recursive methods for solving inherently recursive problems. A01_LIAN4748_10_AP_FM.indd 6 25/11/15 2:09 pm
Preface vii Part II: Object-Oriented Programming (Chapters 9–13) This part introduces object-oriented programming. Java is an object-oriented programming language that uses abstraction, encapsulation, inheritance, and polymorphism to provide great flexibility, modularity, and reusability in developing software. You will learn program- ming with objects and classes (Chapters 9–10), class inheritance (Chapter 11), polymorphism (Chapter 11), exception handling and text I/O (Chapter 12), abstract classes (Chapter 13), and interfaces (Chapter 13). Appendixes This part of the book covers a mixed bag of topics. Appendix A lists Java keywords. Appendix B gives tables of ASCII characters and their associated codes in decimal and in hex. Appendix C shows the operator precedence. Appendix D summarizes Java modifiers and their usage. Appendix E discusses special floating-point values. Appendix F introduces number systems and conversions among binary, decimal, and hex numbers. Java Development Tools You can use a text editor, such as the Windows Notepad or WordPad, to create Java programs and to compile and run the programs from the command window. You can also use a Java development tool, such as NetBeans or Eclipse. These tools support an integrated develop- ment environment (IDE) for developing Java programs quickly. Editing, compiling, building, executing, and debugging programs are integrated in one graphical user interface. Using these tools effectively can greatly increase your programming productivity. NetBeans and Eclipse are easy to use if you follow the tutorials. Tutorials on NetBeans and Eclipse can be found under Supplement on the Student Companion Website www.cs.armstrong.edu/liang/apcs/. MyProgrammingLab and Program Resources MyProgrammingLab with Pearson eText MyProgrammingLab is an online learning system designed to engage students and improve results. MyProgrammingLab consists of a set of programming exercises correlated to specific Pearson Intro to Programming textbooks. Through practice exercises and immediate, person- alized feedback, MyProgrammingLab improves the programming competence of beginning students who often struggle with the basic concepts of programming languages. MyProgrammingLab offers additional student resources, which include: Check point questions (organized by sections for each chapter), Solutions to even-numbered programming exercises, Source code for the examples in the book, Interactive quiz (organized by sections for each chapter), Java IDE and programming resources, Debugging tips, Errata, plus VideoNotes, and Algorithm Animations. MyProgrammingLab is not a self-paced technology and should only be used when required by an instructor. Preview and Adoption Access Upon textbook purchase, students and teachers are granted access to MyProgrammingLab with Pearson eText. High school teachers can obtain preview or adoption access to MyPro- grammingLab in one of the following ways: Preview Access ■ Teachers can request preview access online by visiting IDE tutorials A01_LIAN4748_10_AP_FM.indd 7 25/11/15 2:09 pm
viii Preface www.PearsonSchool.com/Access_Request. Select Computer Science, choose Initial Access, and complete the form under Option 2. Preview Access information will be sent to the teacher via e-mail. Adoption Access ■ With the purchase of this program, a Pearson Adoption Access Card with Instructor Man- ual will be delivered with your textbook purchase. (ISBN: 978-0-13-354087-1) ■ Ask your sales representative for a Pearson Adoption Access Card with Instructor Manual. (ISBN: 978-0-13-354087-1) OR ■ Visit PearsonSchool.com/Access_Request, select Science, choose initial Access, and com- plete the form under Option 3—MyLab/Mastering Class Adoption Access. Teacher and Student access information will be sent to the teacher via e-mail. Students, ask your teacher for access. Pearson reserves the right to change and/or update technology platforms, including possible edition updates to customers during the term of access. This will allow Pearson to continue to deliver the most up-to-date content and technology to customers. Customer will be notified of any change prior to the beginning of the new school year. Instructor Resources Teacher supplements and resources for this text are available electronically to qualified adop- ters on the Instructor Resource Center (IRC) for download. Upon adoption or to preview, please go to www.pearsonschool.com/access_request and select Instructor Resource Center. You will be required to complete a brief one-time registration subject to verification of edu- cator status. Upon verification, access information and instructions will be sent to you via e-mail. Once logged into the IRC, enter 978-0-13-430474-8 in the “Search our Catalog” box to locate resources. Resources include: Instructor Projects and Exercises for Introduction to Java Programming   Instructor Solutions Manual for Introduction to Java Programming   Test Bank for Introduction to Java Programming   TestGen   PowerPoints Acknowledgments I would like to thank Armstrong State University for enabling me to teach what I write and for supporting me in writing what I teach. Teaching is the source of inspiration for continuing to improve the book. I am grateful to the instructors and students who have offered comments, suggestions, bug reports, and praise. This book has been greatly enhanced thanks to outstanding reviews for this and previous editions of Introduction to Java Programming. The reviewers are: Elizabeth Adams (James Madison University), Syed Ahmed (North Georgia College and State University), Omar Aldawud (Illinois Institute of Technology), Stefan Andrei (Lamar University), Yang Ang (University of Wollongong, Australia), Kevin Bierre (Rochester Institute of Technology), Aaron Braskin (Mira Costa High School), David Champion (DeVry Institute), James Chegwidden (Tarrant County College), Anup Dargar (University of North Dakota), Daryl Detrick (Warren Hills Regional High School), Charles Dierbach (Towson University), Frank Ducrest (University of Louisiana at Lafayette), Erica Eddy (University of Wisconsin at Parkside), Summer Ehresman (Center Grove High School), Deena Engel (New York University), Henry A. Etlinger (Rochester Institute of Technology), James Ten Eyck (Marist College), Myers Foreman (Lamar University), Olac A01_LIAN4748_10_AP_FM.indd 8 25/11/15 2:09 pm
Preface ix Fuentes (University of Texas at El Paso), Edward F. Gehringer (North Carolina State University), Harold Grossman (Clemson University), Barbara Guillot (Louisiana State University), Stuart Hansen (University of Wisconsin, Parkside), Dan Harvey (Southern Oregon University), Ron Hofman (Red River College, Canada), Stephen Hughes (Roanoke College), Vladan Jovanovic (Georgia Southern University), Deborah Kabura Kariuki (Stony Point High School), Edwin Kay (Lehigh University), Larry King (University of Texas at Dallas), Nana Kofi (Langara College, Canada), George Koutsogiannakis (Illinois Institute of Technology), Roger Kraft (Purdue University at Calumet), Norman Krumpe (Miami University), Hong Lin (DeVry Institute), Dan Lipsa (Armstrong State University), James Madison (Rensselaer Polytechnic Institute), Frank Malinowski (Darton College), Tim Margush (University of Akron), Debbie Masada (Sun Microsystems), Blayne Mayfield (Oklahoma State University), John McGrath (J.P. McGrath Consulting), Hugh McGuire (Grand Valley State), Shyamal Mitra (University of Texas at Austin), Michel Mitri (James Madison University), Kenrick Mock (University of Alaska Anchorage), Frank Murgolo (California State University, Long Beach), Jun Ni (University of Iowa), Benjamin Nystuen (University of Colorado at Colorado Springs), Maureen Opkins (CA State University, Long Beach), Gavin Osborne (University of Saskatchewan), Kevin Parker (Idaho State University), Dale Parson (Kutztown University), Mark Pendergast (Florida Gulf Coast University), Richard Povinelli (Marquette University), Roger Priebe (University of Texas at Austin), Mary Ann Pumphrey (De Anza Junior College), Pat Roth (Southern Polytechnic State University), Amr Sabry (Indiana University), Ben Setzer (Kennesaw State University), Carolyn Schauble (Colorado State University), David Scuse (University of Manitoba), Ashraf Shirani (San Jose State University), Daniel Spiegel (Kutztown University), Joslyn A. Smith (Florida Atlantic University) , Lixin Tao (Pace University), Ronald F. Taylor (Wright State University), Russ Tront (Simon Fraser University), Deborah Trytten (University of Oklahoma), Michael Verdicchio (Citadel), Kent Vidrine (George Washington University), and Bahram Zartoshty (California State University at Northridge). The reviewers for this AP Edition of Introduction to Java Programming, Tenth Edition, are Daryl Detrick, Warren Hills Regional High School, Summer Ehresman, Center Grove High School, Aaron Braskin, Mira Costa High School, and Deborah Kabura Kariuk, Stony Point High School. It is a great pleasure, honor, and privilege to work with Pearson. I would like to thank Tracy Johnson and her colleagues Marcia Horton, Demetrius Hall, Bram Van Kempen, Carole Sny- der, Kristy Alaura, Scott Disanno, Bob Engelhardt, Shylaja Gattupalli, and their colleagues for organizing, producing, and promoting this project. As always, I am indebted to my wife, Samantha, for her love, support, and encouragement. A01_LIAN4748_10_AP_FM.indd 9 25/11/15 2:09 pm
x 1 Introduction to Computers, Programs, and Java 1 2 Elementary Programming 31 3 Selections 71 4 Mathematical Functions, Characters, and Strings 111 5 Loops 147 6 Methods 187 7 Single-Dimensional Arrays 227 8 Multidimensional Arrays 267 9 Objects and Classes 299 10 Object-Oriented Thinking 337 11 Inheritance and Polymorphism 371 12 Exception Handling and Text I/O 405 BRIEF CONTENTS 13 Abstract Classes and Interfaces 443 14 Recursion 477 Appendixes A Java Keywords 503 B The ASCII Character Set 506 C Operator Precedence Chart 508 D Java Modifiers 510 E Special Floating-Point Values 512 F Number Systems 513 Index 517 A01_LIAN4748_10_AP_FM.indd 10 25/11/15 2:09 pm
xi Chapter 1 Introduction to Computers, Programs, and Java 1 1.1 Introduction 2 1.2 What Is a Computer? 2 1.3 Programming Languages 6 1.4 Operating Systems 9 1.5 Java, the World Wide Web, and Beyond 10 1.6 The Java Language Specification, API, JDK, JRE, and IDE 11 1.7 A Simple Java Program 11 1.8 Creating, Compiling, and Executing a Java Program 14 1.9 Programming Style and Documentation 17 1.10 Programming Errors 18 1.11 Developing Java Programs Using NetBeans 21 1.12 Developing Java Programs Using Eclipse 23 Chapter 2 Elementary Programming 31 2.1 Introduction 32 2.2 Writing a Simple Program 32 2.3 Reading Input from the Console 35 2.4 Identifiers 37 2.5 Variables 38 2.6 Assignment Statements and Assignment Expressions 39 2.7 Named Constants 40 2.8 Naming Conventions 41 2.9 Numeric Data Types and Operations 41 2.10 Numeric Literals 45 2.11 Evaluating Expressions and Operator Precedence 46 2.12 Case Study: Displaying the Current Time 48 2.13 Augmented Assignment Operators 50 2.14 Increment and Decrement Operators 51 2.15 Numeric Type Conversions 52 2.16 Software Development Process 54 2.17 Case Study: Counting Monetary Units 58 2.18 Common Errors and Pitfalls 60 Chapter 3 Selections 71 3.1 Introduction 72 3.2 boolean Data Type 72 3.3 if Statements 74 3.4 Two-Way if-else Statements 76 3.5 Nested if and Multi-Way if-else Statements 77 3.6 Common Errors and Pitfalls 78 3.7 Generating Random Numbers 81 3.8 Case Study: Computing Body Mass Index 82 3.9 Case Study: Computing Taxes 84 3.10 Logical Operators 87 3.11 Case Study: Determining Leap Year 89 3.12 Case Study: Lottery 90 3.13 switch Statements 92 3.14 Conditional Operators 95 CONTENTS A01_LIAN4748_10_AP_FM.indd 11 25/11/15 2:09 pm
xii Contents 3.15 Operator Precedence and Associativity 96 3.16 Debugging 97 Chapter 4 Mathematical Functions, Characters, and Strings 111 4.1 Introduction 112 4.2 Common Mathematical Functions 112 4.3 Character Data Type and Operations 116 4.4 The String Type 120 4.5 Case Studies 128 4.6 Formatting Console Output 135 Chapter 5 Loops 147 5.1 Introduction 148 5.2 The while Loop 148 5.3 The do-while Loop 157 5.4 The for Loop 159 5.5 Which Loop to Use? 161 5.6 Nested Loops 162 5.7 Minimizing Numeric Errors 163 5.8 Case Studies 165 5.9 Keywords break and continue 169 5.10 Case Study: Checking Palindromes 172 5.11 Case Study: Displaying Prime Numbers 173 Chapter 6 Methods 187 6.1 Introduction 188 6.2 Defining a Method 188 6.3 Calling a Method 190 6.4 void Method Example 193 6.5 Passing Arguments by Values 195 6.6 Modularizing Code 197 6.7 Case Study: Converting Hexadecimals to Decimals 199 6.8 Overloading Methods 201 6.9 The Scope of Variables 203 6.10 Case Study: Generating Random Characters 204 6.11 Method Abstraction and Stepwise Refinement 206 Chapter 7 Single-Dimensional Arrays 227 7.1 Introduction 228 7.2 Array Basics 228 7.3 Case Study: Analyzing Numbers 234 7.4 Case Study: Deck of Cards 235 7.5 Copying Arrays 237 7.6 Passing Arrays to Methods 238 7.7 Returning an Array from a Method 241 7.8 Case Study: Counting the Occurrences of Each Letter 241 7.9 Variable-Length Argument Lists 244 7.10 Searching Arrays 245 7.11 Sorting Arrays 249 7.12 The Arrays Class 252 7.13 Command-Line Arguments 253 Chapter 8 Multidimensional Arrays 267 8.1 Introduction 268 8.2 Two-Dimensional Array Basics 268 A01_LIAN4748_10_AP_FM.indd 12 25/11/15 2:09 pm
Contents xiii 8.3 Processing Two-Dimensional Arrays 271 8.4 Passing Two-Dimensional Arrays to Methods 272 8.5 Case Study: Grading a Multiple-Choice Test 273 8.6 Case Study: Finding the Closest Pair 275 8.7 Case Study: Sudoku 277 8.8 Multidimensional Arrays 280 Chapter 9 Objects and Classes 299 9.1 Introduction 300 9.2 Defining Classes for Objects 300 9.3 Example: Defining Classes and Creating Objects 302 9.4 Constructing Objects Using Constructors 307 9.5 Accessing Objects via Reference Variables 307 9.6 Using Classes from the Java Library 311 9.7 Static Variables, Constants, and Methods 314 9.8 Visibility Modifiers 319 9.9 Data Field Encapsulation 320 9.10 Passing Objects to Methods 323 9.11 Array of Objects 325 9.12 Immutable Objects and Classes 327 9.13 The Scope of Variables 328 9.14 The this Reference 329 Chapter 10 Object-Oriented Thinking 337 10.1 Introduction 338 10.2 Class Abstraction and Encapsulation 338 10.3 Thinking in Objects 342 10.4 Class Relationships 345 10.5 Case Study: Designing the Course Class 348 10.6 Case Study: Designing a Class for Stacks 350 10.7 Processing Primitive Data Type Values as Objects 352 10.8 Automatic Conversion between Primitive Types and Wrapper Class Types 355 10.9 The BigInteger and BigDecimal Classes 355 10.10 The String Class 356 Chapter 11 Inheritance and Polymorphism 371 11.1 Introduction 372 11.2 Superclasses and Subclasses 372 11.3 Using the super Keyword 378 11.4 Overriding Methods 381 11.5 Overriding vs. Overloading 381 11.6 The Object Class and Its toString() Method 382 11.7 Polymorphism 383 11.8 Dynamic Binding 384 11.9 Casting Objects and the instanceof Operator 386 11.10 The Object’s equals Method 388 11.11 The ArrayList Class 389 11.12 Useful Methods for Lists 394 11.13 Case Study: A Custom Stack Class 395 11.14 The protected Data and Methods 396 11.15 Preventing Extending and Overriding 398 Chapter 12 Exception Handling and Text I/O 405 12.1 Introduction 406 12.2 Exception-Handling Overview 406 12.3 Exception Types 410 A01_LIAN4748_10_AP_FM.indd 13 25/11/15 2:09 pm
xiv Contents 12.4 More on Exception Handling 412 12.5 The finally Clause 419 12.6 When to Use Exceptions 419 12.7 Rethrowing Exceptions 420 12.8 Chained Exceptions 420 12.9 Defining Custom Exception Classes 421 12.10 The File Class 424 12.11 File Input and Output 426 12.12 Reading Data from the Web 431 12.13 Case Study: Web Crawler 432 Chapter 13 Abstract Classes and Interfaces 443 13.1 Introduction 444 13.2 Abstract Classes 444 13.3 Case Study: the Abstract Number Class 448 13.4 Case Study: Calendar and GregorianCalendar 450 13.5 Interfaces 452 13.6 The Comparable Interface 456 13.7 Interfaces vs. Abstract Classes 459 13.8 Example: The List and Collection Interfaces 462 13.9 Case Study: The Rational Class 463 13.10 Class Design Guidelines 468 Chapter 14 Recursion 477 14.1 Introduction 478 14.2 Case Study: Computing Factorials 478 14.3 Case Study: Computing Fibonacci Numbers 481 14.4 Problem Solving Using Recursion 483 14.5 Recursive Helper Methods 485 14.6 Case Study: Finding the Directory Size 487 14.7 Case Study: Tower of Hanoi 489 14.8 Merge Sort 492 14.9 Recursion vs. Iteration 495 14.10 Tail Recursion 496 APPENDIXES Appendix A Java Keywords 503 Appendix B The ASCII Character Set 506 Appendix C Operator Precedence Chart 508 Appendix D Java Modifiers 510 Appendix E Special Floating-Point Values 512 Appendix F Number Systems 513 INDEX 517 A01_LIAN4748_10_AP_FM.indd 14 25/11/15 2:09 pm
xv Chapter 1 Introduction to Computers, Programs, and Java 1 Your first Java program 12 Compile and run a Java program 16 NetBeans brief tutorial 21 Eclipse brief tutorial 24 Chapter 2 Elementary Programming 31 Obtain input 35 Use operators / and % 48 Software development process 54 Compute loan payments 55 Compute BMI 67 Chapter 3 Selections 71 Program addition quiz 73 Program subtraction quiz 81 Use multi-way if-else statements 84 Sort three integers 101 Check point location 104 Chapter 4 Mathematical Functions, Characters, and Strings 111 Introduce math functions 112 Introduce strings and objects 120 Convert hex to decimal 132 Compute great circle distance 140 Convert hex to binary 142 Chapter 5 Loops 147 Guess a number 151 Multiple subtraction quiz 154 Minimize numeric errors 163 Display loan schedule 180 Sum a series 181 Chapter 6 Methods 187 Define/invoke max method 190 Use void method 193 Modularize code 197 Stepwise refinement 206 Reverse an integer 215 Estimate p 218 Chapter 7 Single-Dimensional Arrays 227 Random shuffling 232 Deck of cards 235 Selection sort 249 VideoNotes Locations of VideoNotes MyProgrammingLab™ Command-line arguments 253 Command-line argument 254 Coupon collector’s problem 262 Consecutive four 264 Chapter 8 Multidimensional Arrays 267 Find the row with the largest sum 272 Grade multiple-choice test 273 Sudoku 277 Multiply two matrices 286 Even number of 1s 293 Chapter 9 Objects and Classes 299 Define classes and objects 300 Static vs. instance 314 Data field encapsulation 320 The Fan class 334 Chapter 10 Object-Oriented Thinking 337 The Loan class 339 The BMI class 342 The StackOfIntegers class 350 Process large numbers 355 The String class 356 The MyPoint class 363 Chapter 11 Inheritance and Polymorphism 371 Geometric class hierarchy 372 Polymorphism and dynamic binding demo 385 The ArrayList class 389 The MyStack class 395 New Account class 401 Chapter 12 Exception Handling and Text I/O 405 Exception-handling advantages 406 Create custom exception classes 421 Write and read data 426 HexFormatException 437 Chapter 13 Abstract Classes and Interfaces 443 Abstract GeometricObject class 444 Calendar and GregorianCalendar classes 450 The concept of interface 452 Redesign the Rectangle class 473 Chapter 14 Recursion 477 Binary search 486 Directory size 487 Search in a string a directory 501 VideoNote A01_LIAN4748_10_AP_FM.indd 15 25/11/15 2:09 pm
This page intentionally left blank A01_LIAN4748_10_AP_FM.indd 16 12/21/15 9:20 PM
INTRODUCTION TO COMPUTERS, PROGRAMS, AND JAVA Objectives ■ To understand computer basics, programs, and operating systems (§§1.2–1.4). ■ To describe the relationship between Java and the World Wide Web (§1.5). ■ To understand the meaning of Java language specification, API, JDK, JRE, and IDE (§1.6). ■ To write a simple Java program (§1.7). ■ To display output on the console (§1.7). ■ To explain the basic syntax of a Java program (§1.7). ■ To create, compile, and run Java programs (§1.8). ■ To use sound Java programming style and document programs properly (§1.9). ■ To explain the differences between syntax errors, runtime errors, and logic errors (§1.10). ■ To develop Java programs using NetBeans (§1.11). ■ To develop Java programs using Eclipse (§1.12). CHAPTER 1 M01_LIAN4748_10_AP_C01.indd 1 23/11/15 7:52 am
2 Chapter 1 Introduction to Computers, Programs, and Java 1.1 Introduction The central theme of this book is to learn how to solve problems by writing a program. This book is about programming. So, what is programming? The term programming means to create (or develop) software, which is also called a program. In basic terms, software contains the instructions that tell a computer—or a computerized device—what to do. Software is all around you, even in devices that you might not think would need it. Of course, you expect to find and use software on a personal computer, but software also plays a role in running airplanes, cars, cell phones, and even toasters. On a personal computer, you use word processors to write documents, Web browsers to explore the Internet, and e-mail pro- grams to send and receive messages. These programs are all examples of software. Software developers create software with the help of powerful tools called programming languages. This book teaches you how to create programs by using the Java programming language. There are many programming languages, some of which are decades old. Each language was invented for a specific purpose—to build on the strengths of a previous language, for example, or to give the programmer a new and unique set of tools. Knowing that there are so many programming languages available, it would be natural for you to wonder which one is best. But, in truth, there is no “best” language. Each one has its own strengths and weaknesses. Experienced programmers know that one language might work well in some situations, whereas a different language may be more appropriate in other situations. For this reason, seasoned programmers try to master as many different programming languages as they can, giving them access to a vast arsenal of software-development tools. If you learn to program using one language, you should find it easy to pick up other languages. The key is to learn how to solve problems using a programming approach. That is the main theme of this book. You are about to begin an exciting journey: learning how to program. At the outset, it is helpful to review computer basics, programs, and operating systems. If you are already familiar with such terms as CPU, memory, disks, operating systems, and programming languages, you may skip Sections 1.2–1.4. 1.2 What Is a Computer? A computer is an electronic device that stores and processes data. A computer includes both hardware and software. In general, hardware comprises the visible, physical elements of the computer, and software provides the invisible instructions that control the hardware and make it perform specific tasks. Knowing computer hardware isn’t essential to learning a programming language, but it can help you better understand the effects that a program’s instructions have on the computer and its components. This section introduces computer hardware components and their functions. A computer consists of the following major hardware components (Figure 1.1): ■ A central processing unit (CPU) ■ Memory (main memory) ■ Storage devices (such as disks and CDs) ■ Input devices (such as the mouse and keyboard) ■ Output devices (such as monitors and printers) ■ Communication devices (such as modems and network interface cards) A computer’s components are interconnected by a subsystem called a bus. You can think of a bus as a sort of system of roads running among the computer’s components; data and power travel along the bus from one part of the computer to another. In personal computers, Key Point what is programming? programming program Key Point hardware software bus M01_LIAN4748_10_AP_C01.indd 2 23/11/15 7:52 am
1.2 What Is a Computer? 3 the bus is built into the computer’s motherboard, which is a circuit case that connects all of the parts of a computer together. 1.2.1 Central Processing Unit The central processing unit (CPU) is the computer’s brain. It retrieves instructions from memory and executes them. The CPU usually has two components: a control unit and an arithmetic/logic unit. The control unit controls and coordinates the actions of the other components. The arithmetic/logic unit performs numeric operations (addition, subtraction, multiplication, division) and logical operations (comparisons). Today’s CPUs are built on small silicon semiconductor chips that contain millions of tiny electric switches, called transistors, for processing information. Every computer has an internal clock, which emits electronic pulses at a constant rate. These pulses are used to control and synchronize the pace of operations. A higher clock speed enables more instructions to be executed in a given period of time. The unit of measurement of clock speed is the hertz (Hz), with 1 hertz equaling 1 pulse per second. In the 1990s, computers measured clocked speed in megahertz (MHz), but CPU speed has been improving continuously; the clock speed of a computer is now usually stated in gigahertz (GHz). Intel’s newest proces- sors run at about 3 GHz. CPUs were originally developed with only one core. The core is the part of the processor that performs the reading and executing of instructions. In order to increase CPU processing power, chip manufacturers are now producing CPUs that contain multiple cores. A multicore CPU is a single component with two or more independent cores. Today’s consumer comput- ers typically have two, three, and even four separate cores. Soon, CPUs with dozens or even hundreds of cores will be affordable. 1.2.2 Bits and Bytes Before we discuss memory, let’s look at how information (data and programs) is stored in a computer. A computer is really nothing more than a series of switches. Each switch exists in two states: on or off. Storing information in a computer is simply a matter of setting a sequence of switches on or off. If the switch is on, its value is 1. If the switch is off, its value is 0. These 0s and 1s are interpreted as digits in the binary number system and are called bits (binary digits). The minimum storage unit in a computer is a byte. A byte is composed of eight bits. A small number such as 3 can be stored as a single byte. To store a number that cannot fit into a single byte, the computer uses several bytes. Data of various kinds, such as numbers and characters, are encoded as a series of bytes. As a programmer, you don’t need to worry about the encoding and decoding of data, which the computer system performs automatically, based on the encoding scheme. An encoding scheme is a set of rules that govern how a computer translates characters and numbers into data the computer can actually work with. Most schemes translate each character into a predetermined motherboard CPU speed hertz megahertz gigahertz core bits byte encoding scheme FIGURE 1.1 A computer consists of a CPU, memory, storage devices, input devices, output devices, and communication devices. Memory e.g., Disk, CD, and Tape e.g., Modem and NIC e.g., Keyboard, Mouse e.g., Monitor, Printer CPU Bus Storage Devices Communication Devices Input Devices Output Devices M01_LIAN4748_10_AP_C01.indd 3 23/11/15 7:52 am