Widget HTML Atas

building java programs pdf free download

  • 9,358,873 books books
  • 84,837,646 articles articles
  • ZLibrary Home
  • Home

Main Building Java Programs: A Back to Basics Approach

Book cover Building Java Programs: A Back to Basics Approach

Building Java Programs: A Back to Basics Approach

Stuart Reges, Marty Stepp

How much do you like this book?

What's the quality of the file?

Download the book for quality assessment

What's the quality of the downloaded files?

For courses in Java Programming Layered, Back-to-Basics Approach to Java ProgrammingNewly revised and updated, thisFourth Editionof Building Java Programs: A Back to Basics Approach uses a layered strategy to introduce Java programming, with the aim of overcoming the difficulty associated with introductory programming textbooks. The authors' proven and class-tested "back to basics" approach introduces programming fundamentals first, with new syntax and concepts added over multiple chapters, and object-oriented programming discussed only once readers have developed a basic understanding of Java programming. Previous editions have established the text's reputation as an excellent choice for thoroughly introducing the basics of computer science, and new material in theFourth Editionincorporates concepts related to Java 8, functional programming, and image manipulation.Note:You are purchasing a standalone product; MyLab(TM) & Mastering(TM) does not come packaged with this content. Students, if interested in purchasing this title with MyLab & Mastering, ask your instructor for the correct package ISBN and Course ID. Instructors, contact your Pearson representative for more information. If you would like to purchase both the physical text and MyLab & Mastering, search for:0134448308 / 9780134448305 Building Java Programs: A Back to Basics Approach plus MyProgrammingLab with Pearson eText -- Access Card Package, 4/e Package consists of:
0134324706 / 9780134324708 MyProgrammingLab with Pearson eText -- Instant Access -- for Building Java Programs: A Back to Basics Approach, 4/e
0134322762 / 9780134322766 Building Java Programs: A Back to Basics Approach

The file will be sent to your email address. It may take up to 1-5 minutes before you receive it.

The file will be sent to your Kindle account. It may takes up to 1-5 minutes before you received it.

Please note: you need to verify every book you want to send to your Kindle. Check your mailbox for the verification email from Amazon Kindle.

You may be interested in Powered by Rec2Me

Most frequently terms

                Building Java Programs A Back to Basics Approach Fourth Edition Stuart Reges University of Washington Marty Stepp Stanford 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  Vice President, Editorial Director: Marcia Horton Acquisitions Editor: Matt Goldstein Editorial Assistant: Kristy Alaura VP of Marketing: Christy Lesko Director of Field Marketing: Tim Galligan Product Marketing Manager: Bram Van Kempen Field Marketing Manager: Demetrius Hall Marketing Assistant: Jon Bryant Director of Product Management: Erin Gregg Team Lead, Program and Project Management: Scott Disanno Program Manager: Carole Snyder Project Manager: Lakeside Editorial Services L.L.C. Senior Specialist, Program Planning and Support: Maura Zaldivar-Garcia Cover Design: Joyce Wells R&P Manager: Rachel Youdelman R&P Project Manager: Timothy Nicholls Inventory Manager: Meredith Maresca Cover Art: Matt Walford/Cultura/Getty Images Full-Service Project Management: Apoorva Goel/Cenveo Publisher Services  Composition: Cenveo® Publisher Services Printer/Binder: Edwards Brothers Malloy Cover Printer: Phoenix Color Text Font: Monotype The authors and publisher of this book have used their best efforts in preparing this book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in this book. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs. Copyright © 2017, 2014 and 2011 Pearson Education, Inc. or its affiliates. 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 otherwise. For information regarding permissions, request forms and the appropriate contacts within the Pearson Education Global Rights & Permissions department, please visit www.pearsonhighed.com/permissions/. Acknowledgements of third party content appear on pages 1193–1194, which constitute an extension of this copyright page. PEARSON, and MYPROGRAMMINGLAB are exclusive trademarks in the U.S. and/or other countries owned by Pearson Education, Inc. or its affiliates. Unless otherwise indicated herein, any third-party trademarks that may appear in this work are the property of their respective owners and any references to third-party trademarks, logos or other trade dress are for demonstrative or descriptive purposes only. Such references are not intended to imply any sponsorship, endorsement, authorization, or promotion of  Pearson's products by the owners of such marks, or any relationship between the owner and Pearson Education, Inc. or its affiliates, authors, licensees or distributors. Library of Congress Cataloging-in-Publication Data Names: Reges, Stuart, author. | Stepp, Martin, author. Title: Building Java programs : a back to basics approach / Stuart Reges, University of Washington; Marty Stepp, Stanford University. Description: Fourth Edition. | Hoboken, NJ : Pearson, 2016. Identifiers: LCCN 2015049340 | ISBN 9780134322766 (alk. paper) Subjects: LCSH: Java (Computer program language) Classification: LCC QA76.73.J38 R447 2016 | DDC 005.13/3—dc23 LC record available at http://lccn.loc.gov/2015049340 10 9 8 7 6 5 4 3 2 1  ISBN 10: 0-13-432276-2 ISBN 13: 978-0-13-432276-6  Preface The newly revised fourth edition of our Building Java Programs textbook is designed for use in a two-course introduction to computer science. We have class-tested it with thousands of undergraduates, most of whom were not computer science majors, in our CS1-CS2 sequence at the University of Washington. These courses are experiencing record enrollments, and other schools that have adopted our textbook report that students are succeeding with our approach. Introductory computer science courses are often seen as "killer" courses with high failure rates. But as Douglas Adams says in The Hitchhiker's Guide to the Galaxy, "Don't panic." Students can master this material if they can learn it gradually. Our textbook uses a layered approach to introduce new syntax and concepts over multiple chapters. Our textbook uses an "objects later" approach where programming fundamentals and procedural decomposition are taught before diving into object-oriented programming. We have championed this approach, which we sometimes call "back to basics," and have seen through years of experience that a broad range of scientists, engineers, and others can learn how to program in a procedural manner. Once we have built a solid foundation of procedural techniques, we turn to object-oriented programming. By the end of the course, students will have learned about both styles of programming. Here are some of the changes that we have made in the fourth edition: New chapter on functional programming with Java 8. As explained below, we have introduced a chapter that uses the new language features available in Java 8 to discuss the core concepts of functional programming. New section on images and 2D pixel array manipulation. Image manipulation is becoming increasingly popular, so we have expanded our DrawingPanel class to include features that support manipulating  images as two-dimensional arrays of pixel values. This extra coverage will be particularly helpful for students taking an AP/CS A course because of the heavy emphasis on two-dimensional arrays on the AP exam. Expanded self-checks and programming exercises. Many chapters have received new self-check problems and programming exercises. There are roughly fifty total problems and exercises per chapter, all of which have been class-tested with real students and have solutions provided for instructors on our web site. Since the publication of our third edition, Java 8 has been released. This new version supports a style of programming known as functional programming that is gaining in popularity because of its ability to simply express complex algorithms that are more easily executed in parallel on machines with multiple processors. ACM and IEEE have released new guidelines for undergraduate computer science curricula, including a strong recommendation to cover functional programming concepts. We have added a new Chapter 19 that covers most of the functional concepts from the new curriculum guidelines. The focus is on concepts, not on language features. As a result, it provides an introduction to several new Java 8 constructs but not a comprehensive coverage of all new language features. This provides flexibility to instructors since functional programming features can be covered as an advanced independent topic, incorporated along the way, or skipped entirely. Instructors can choose to start covering functional constructs along with traditional constructs as early as Chapter 6. See the dependency chart at the end of this section. The following features have been retained from previous editions: Focus on problem solving. Many textbooks focus on language details when they introduce new constructs. We focus instead on problem solving. What new problems can be solved with each construct? What pitfalls are novices likely to encounter along the way? What are the most common ways to use a new construct? Emphasis on algorithmic thinking. Our procedural approach allows us to  emphasize algorithmic problem solving: breaking a large problem into smaller problems, using pseudocode to refine an algorithm, and grappling with the challenge of expressing a large program algorithmically. Layered approach. Programming in Java involves many concepts that are difficult to learn all at once. Teaching Java to a novice is like trying to build a house of cards. Each new card has to be placed carefully. If the process is rushed and you try to place too many cards at once, the entire structure collapses. We teach new concepts gradually, layer by layer, allowing students to expand their understanding at a manageable pace. Case studies. We end most chapters with a significant case study that shows students how to develop a complex program in stages and how to test it as it is being developed. This structure allows us to demonstrate each new programming construct in a rich context that can't be achieved with short code examples. Several of the case studies were expanded and improved in the second edition. Utility as a CS1+CS2 textbook. In recent editions, we added chapters that extend the coverage of the book to cover all of the topics from our second course in computer science, making the book usable for a twocourse sequence. Chapters 12–19 explore recursion, searching and sorting, stacks and queues, collection implementation, linked lists, binary trees, hash tables, heaps, and more. Chapter 12 also received a section on recursive backtracking, a powerful technique for exploring a set of possibilities for solving problems such as 8 Queens and Sudoku.  Layers and Dependencies Many introductory computer science books are language-oriented, but the early chapters of our book are layered. For example, Java has many control structures (including for-loops, while-loops, and if/else-statements), and many books include all of these control structures in a single chapter. While that might make sense to someone who already knows how to program, it can  be overwhelming for a novice who is learning how to program. We find that it is much more effective to spread these control structures into different chapters so that students learn one structure at a time rather than trying to learn them all at once. The following table shows how the layered approach works in the first six chapters: Chapter  Control Flow  Data  1  methods  String  2  definite loops (for)  variables, expressions, int, double  3  return values  using objects  4 5 6  literals  conditional char (if/else) indefinite boolean loops (while) Scanner  Programming Input/Output Techniques procedural println, print decomposition local variables, class constants, pseudocode console input, 2D parameters graphics (optional) pre/post conditions, printf throwing exceptions assertions, robust programs token/line-based file file I/O processing  Chapters 1–6 are designed to be worked through in order, with greater flexibility of study then beginning in Chapter 7. Chapter 6 may be skipped, although the case study in Chapter 7 involves reading from a file, a topic that is covered in Chapter 6. The following is a dependency chart for the book:  Supplements http://www.buildingjavaprograms.com/ Answers to all self-check problems appear on our web site and are accessible to anyone. Our web site has the following additional resources for students: Online-only supplemental chapters, such as a chapter on creating Graphical User Interfaces Source code and data files for all case studies and other complete program examples The DrawingPanel class used in the optional graphics Supplement 3G Our web site has the following additional resources for teachers: PowerPoint slides suitable for lectures Solutions to exercises and programming projects, along with homework specification documents for many projects Sample exams and solution keys Additional lab exercises and programming exercises with solution keys Closed lab creation tools to produce lab handouts with the instructor's choice of problems integrated with the textbook To access protected instructor resources, contact us at authors@buildingjavaprograms.com. The same materials are also available at http://www.pearsonhighered.com/cs-resources. To receive a password for this site or to ask other questions related to resources, contact your Pearson sales representative.  MyProgrammingLab  MyProgrammingLab is an online practice and assessment tool that helps students fully grasp the logic, semantics, and syntax of programming. Through practice exercises and immediate, personalized feedback, MyProgrammingLab improves the programming competence of beginning students who often struggle with basic concepts and paradigms of popular high-level programming languages. A self-study and homework tool, the MyProgrammingLab course consists of hundreds of small practice exercises organized around the structure of this textbook. For students, the system automatically detects errors in the logic and syntax of code submissions and offers targeted hints that enable students to figure out what went wrong, and why. For instructors, a comprehensive grade book tracks correct and incorrect answers and stores the code inputted by students for review. For a full demonstration, to see feedback from instructors and students, or to adopt MyProgrammingLab for your course, visit the following web site: http://www.myprogramminglab.com/  VideoNotes  We have recorded a series of instructional videos to accompany the textbook. They are available at the following web site: www.pearsonhighered.com/csresources Roughly 3–4 videos are posted for each chapter. An icon in the margin of the page indicates when a VideoNote is available for a given topic. In each video, we spend 5–15 minutes walking through a particular concept or problem, talking about the challenges and methods necessary to solve it. These videos make a good supplement to the instruction given in lecture classes and in the textbook. Your new copy of the textbook has an access code that will allow you to view the videos.  Acknowledgments First, we would like to thank the many colleagues, students, and teaching assistants who have used and commented on early drafts of this text. We could not have written this book without their input. Special thanks go to Hélène Martin, who pored over early versions of our first edition chapters to find errors and to identify rough patches that needed work. We would also like to thank instructor Benson Limketkai for spending many hours performing a technical proofread of the second edition. Second, we would like to thank the talented pool of reviewers who guided us in the process of creating this textbook: Greg Anderson, Weber State University Delroy A. Brinkerhoff, Weber State University Ed Brunjes, Miramar Community College Tom Capaul, Eastern Washington University Tom Cortina, Carnegie Mellon University Charles Dierbach, Towson University H.E. Dunsmore, Purdue University Michael Eckmann, Skidmore College Mary Anne Egan, Siena College Leonard J. Garrett, Temple University Ahmad Ghafarian, North Georgia College & State University Raj Gill, Anne Arundel Community College  Michael Hostetler, Park University David Hovemeyer, York College of Pennsylvania Chenglie Hu, Carroll College Philip Isenhour, Virginia Polytechnic Institute Andree Jacobson, University of New Mexico David C. Kamper, Sr., Northeastern Illinois University Simon G.M. Koo, University of San Diego Evan Korth, New York University Joan Krone, Denison University John H.E.F. Lasseter, Fairfield University Eric Matson, Wright State University Kathryn S. McKinley, University of Texas, Austin Jerry Mead, Bucknell University George Medelinskas, Northern Essex Community College John Neitzke, Truman State University Dale E. Parson, Kutztown University Richard E. Pattis, Carnegie Mellon University Frederick Pratter, Eastern Oregon University Roger Priebe, University of Texas, Austin Dehu Qi, Lamar University  John Rager, Amherst College Amala V.S. Rajan, Middlesex University Craig Reinhart, California Lutheran University Mike Scott, University of Texas, Austin Alexa Sharp, Oberlin College Tom Stokke, University of North Dakota Leigh Ann Sudol, Fox Lane High School Ronald F. Taylor, Wright State University Andy Ray Terrel, University of Chicago Scott Thede, DePauw University Megan Thomas, California State University, Stanislaus Dwight Tuinstra, SUNY Potsdam Jeannie Turner, Sayre School Tammy VanDeGrift, University of Portland Thomas John VanDrunen, Wheaton College Neal R. Wagner, University of Texas, San Antonio Jiangping Wang, Webster University Yang Wang, Missouri State University Stephen Weiss, University of North Carolina at Chapel Hill Laurie Werner, Miami University  Dianna Xu, Bryn Mawr College Carol Zander, University of Washington, Bothell Finally, we would like to thank the great staff at Pearson who helped produce the book. Michelle Brown, Jeff Holcomb, Maurene Goo, Patty Mahtani, Nancy Kotary, and Kathleen Kenny did great work preparing the first edition. Our copy editors and the staff of Aptara Corp, including Heather Sisan, Brian Baker, Brendan Short, and Rachel Head, caught many errors and improved the quality of the writing. Marilyn Lloyd and Chelsea Bell served well as project manager and editorial assistant respectively on prior editions. For their help with the third edition we would like to thank Kayla Smith-Tarbox, Production Project Manager, and Jenah Blitz-Stoehr, Computer Science Editorial Assistant. Mohinder Singh and the staff at Aptara, Inc., were also very helpful in the final production of the third edition. For their great work on production of the fourth edition, we thank Louise Capulli and the staff of Lakeside Editorial Services, along with Carole Snyder at Pearson. Special thanks go to our lead editor at Pearson, Matt Goldstein, who has believed in the concept of our book from day one. We couldn't have finished this job without all of their hard work and support. Stuart Reges Marty Stepp  Break through To Improving results  MyProgammingLab™ Through the power of practice and immediate personalized feedback, MyProgrammingLab helps improve your students' performance.  Programming Practice With MyProgrammingLab, your students will gain firs-hand programming experience in an interactive online environment.  Immediate, Personalized Feedback MyProgrammingLab automatically detects errors in the logic and syntax of their code submission and offers targeted hints that enables students to figure out what went wrong and why.  Graduated Complexity MyProgrammingLab breaks down programming concepts into short, understandable sequences of exercises. Within each sequence the level and sophistication of the exercises increase gradually but steadily.  Dynamic Roster Students' submissions are stored in a roster that indicates whether the submission is correct, how many attempts were made, and the actual code submissions from each attempt.  Pearson eText The Pearson eText gives students access to their textbook anytime, anywhere  Step-By-Step Videonote Tutorials These step-by-step video tutorials enhance the programming concepts presented in select Pearson textbooks.  For more information and titles available with MyProgrammingLab, please visit www.myprogramminglab.com. Copyright © 2016 Pearson Education, Inc. or its affiliate(s). All rights reserved. HELO88173 · 11/15 LOCATION OF VIDEO NOTES IN THE TEXT  www.pearsonhighered.com/cs-resources Chapter 1 Chapter 2 Chapter 3 Chapter 3G Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14 Chapter 15 Chapter 16 Chapter 17 Chapter 18  Pages 31, 40 Pages 65, 74, 89, 97, 110 Pages 141, 156, 161, 167 Pages 197, 215 Pages 243, 251, 278 Pages 324, 327, 329, 333, 356 Pages 396, 409, 423 Pages 458, 465, 484, 505 Pages 535, 547, 555, 568 Pages 597, 610, 626 Pages 672, 677, 686 Pages 716, 729, 737 Pages 764, 772, 809 Pages 834, 837, 843 Pages 889, 896 Pages 930, 936, 940 Pages 972, 979, 992 Pages 1037, 1038, 1048 Pages 1073, 1092  Brief Contents 1. Chapter 1 Introduction to Java Programming 1 2. Chapter 2 Primitive Data and Definite Loops 63 3. Chapter 3 Introduction to Parameters and Objects 137 4. Supplement 3G Graphics (Optional) 196 5. Chapter 4 Conditional Execution 238 6. Chapter 5 Program Logic and Indefinite Loops 315 7. Chapter 6 File Processing 387 8. Chapter 7 Arrays 443 9. Chapter 8 Classes 530 10. Chapter 9 Inheritance and Interfaces 587 11. Chapter 10 ArrayLists 662 12. Chapter 11 Java Collections Framework 715 13. Chapter 12 Recursion 754 14. Chapter 13 Searching and Sorting 832 15. Chapter 14 Stacks and Queues 884 16. Chapter 15 Implementing a Collection Class 922 17. Chapter 16 Linked Lists 965 18. Chapter 17 Binary Trees 1017  19. Chapter 18 Advanced Data Structures 1071 20. Chapter 19 Functional Programming with Java 1107 1. Appendix A Java Summary 1149 2. Appendix B The Java API Specification and Javadoc Comments 1164 3. Appendix C Additional Java Syntax 1170  Contents 1. Chapter 1 Introduction to Java Programming 1 1. 1.1 Basic Computing Concepts 2 1. Why Programming? 2 2. Hardware and Software 3 3. The Digital Realm 4 4. The Process of Programming 6 5. Why Java? 7 6. The Java Programming Environment 8 2. 1.2 And Now—Java 10 1. String Literals (Strings) 14 2. System.out.println 15 3. Escape Sequences 15 4. print versus println 17 5. Identifiers and Keywords 18 6. A Complex Example: DrawFigures1 20 7. Comments and Readability 21 3. 1.3 Program Errors 24 1. Syntax Errors 24  2. Logic Errors (Bugs) 28 4. 1.4 Procedural Decomposition 28 1. Static Methods 31 2. Flow of Control 34 3. Methods That Call Other Methods 36 4. An Example Runtime Error 39 5. 1.5 Case Study: DrawFigures 40 1. Structured Version 41 2. Final Version without Redundancy 43 3. Analysis of Flow of Execution 44 2. Chapter 2 Primitive Data and Definite Loops 63 1. 2.1 Basic Data Concepts 64 1. Primitive Types 64 2. Expressions 65 3. Literals 67 4. Arithmetic Operators 68 5. Precedence 70 6. Mixing Types and Casting 73 2. 2.2 Variables 74 1. Assignment/Declaration Variations 79  2. String Concatenation 82 3. Increment/Decrement Operators 84 4. Variables and Mixing Types 87 3. 2.3 The for Loop 89 1. Tracing for Loops 91 2. for Loop Patterns 95 3. Nested for Loops 97 4. 2.4 Managing Complexity 99 1. Scope 99 2. Pseudocode 105 3. Class Constants 108 5. 2.5 Case Study: Hourglass Figure 110 1. Problem Decomposition and Pseudocode 111 2. Initial Structured Version 113 3. Adding a Class Constant 114 4. Further Variations 117 3. Chapter 3 Introduction to Parameters and Objects 137 1. 3.1 Parameters 138 1. The Mechanics of Parameters 141 2. Limitations of Parameters 145  3. Multiple Parameters 148 4. Parameters versus Constants 151 5. Overloading of Methods 151 2. 3.2 Methods That Return Values 152 1. The Math Class 153 2. Defining Methods That Return Values 156 3. 3.3 Using Objects 160 1. String Objects 161 2. Interactive Programs and Scanner Objects 167 3. Sample Interactive Program 170 4. 3.4 Case Study: Projectile Trajectory 173 1. Unstructured Solution 177 2. Structured Solution 179 4. Supplement 3G Graphics (Optional) 196 1. 3G.1 Introduction to Graphics 197 1. DrawingPanel 197 2. Drawing Lines and Shapes 198 3. Colors 203 4. Drawing with Loops 206 5. Text and Fonts 210  6. Images 213 2. 3G.2 Procedural Decomposition with Graphics 215 1. A Larger Example: DrawDiamonds 216 3. 3G.3 Case Study: Pyramids 219 1. Unstructured Partial Solution 220 2. Generalizing the Drawing of Pyramids 222 3. Complete Structured Solution 223 5. Chapter 4 Conditional Execution 238 1. 4.1 if/else Statements 239 1. Relational Operators 241 2. Nested if/else Statements 243 3. Object Equality 250 4. Factoring if/else Statements 251 5. Testing Multiple Conditions 253 2. 4.2 Cumulative Algorithms 254 1. Cumulative Sum 254 2. Min/Max Loops 256 3. Cumulative Sum with if 260 4. Roundoff Errors 262 3. 4.3 Text Processing 265  1. The char Type 265 2. char versus int 266 3. Cumulative Text Algorithms 267 4. System.out.printf 269 4. 4.4 Methods with Conditional Execution 274 1. Preconditions and Postconditions 274 2. Throwing Exceptions 274 3. Revisiting Return Values 278 4. Reasoning about Paths 283 5. 4.5 Case Study: Body Mass Index 285 1. One-Person Unstructured Solution 286 2. Two-Person Unstructured Solution 289 3. Two-Person Structured Solution 291 4. Procedural Design Heuristics 295 6. Chapter 5 Program Logic and Indefinite Loops 315 1. 5.1 The while Loop 316 1. A Loop to Find the Smallest Divisor 317 2. Random Numbers 320 3. Simulations 324 4. do/while Loop 325  2. 5.2 Fencepost Algorithms 327 1. Sentinel Loops 329 2. Fencepost with if 330 3. 5.3 The boolean Type 333 1. Logical Operators 335 2. Short-Circuited Evaluation 338 3. boolean Variables and Flags 342 4. Boolean Zen 344 5. Negating Boolean Expressions 347 4. 5.4 User Errors 348 1. Scanner Lookahead 349 2. Handling User Errors 351 5. 5.5 Assertions and Program Logic 353 1. Reasoning about Assertions 355 2. A Detailed Assertions Example 356 6. 5.6 Case Study: NumberGuess 361 1. Initial Version without Hinting 361 2. Randomized Version with Hinting 363 3. Final Robust Version 367 7. Chapter 6 File Processing 387  1. 6.1 File-Reading Basics 388 1. Data, Data Everywhere 388 2. Files and File Objects 388 3. Reading a File with a Scanner 391 2. 6.2 Details of Token-Based Processing 396 1. Structure of Files and Consuming Input 398 2. Scanner Parameters 403 3. Paths and Directories 404 4. A More Complex Input File 407 3. 6.3 Line-Based Processing 409 1. String Scanners and Line/Token Combinations 410 4. 6.4 Advanced File Processing 415 1. Output Files with PrintStream 415 2. Guaranteeing That Files Can Be Read 420 5. 6.5 Case Study: Zip Code Lookup 423 8. Chapter 7 Arrays 443 1. 7.1 Array Basics 444 1. Constructing and Traversing an Array 444 2. Accessing an Array 448 3. A Complete Array Program 451  4. Random Access 455 5. Arrays and Methods 458 6. The For-Each Loop 461 7. Initializing Arrays 463 8. The Arrays Class 464 2. 7.2 Array-Traversal Algorithms 465 1. Printing an Array 466 2. Searching and Replacing 468 3. Testing for Equality 471 4. Reversing an Array 472 5. String Traversal Algorithms 477 6. Functional Approach 478 3. 7.3 Reference Semantics 479 1. Multiple Objects 481 4. 7.4 Advanced Array Techniques 484 1. Shifting Values in an Array 484 2. Arrays of Objects 488 3. Command-Line Arguments 490 4. Nested Loop Algorithms 490 5. 7.5 Multidimensional Arrays 492  1. Rectangular Two-Dimensional Arrays 492 2. Jagged Arrays 494 6. 7.6 Arrays of Pixels 499 7. 7.7 Case Study: Benford's Law 504 1. Tallying Values 505 2. Completing the Program 509 9. Chapter 8 Classes 530 1. 8.1 Object-Oriented Programming 531 1. Classes and Objects 532 2. Point Objects 534 2. 8.2 Object State and Behavior 535 1. Object State: Fields 536 2. Object Behavior: Methods 538 3. The Implicit Parameter 541 4. Mutators and Accessors 543 5. The toString Method 545 3. 8.3 Object Initialization: Constructors 547 1. The Keyword this 552 2. Multiple Constructors 554 4. 8.4 Encapsulation 555  1. Private Fields 556 2. Class Invariants 562 3. Changing Internal Implementations 566 5. 8.5 Case Study: Designing a Stock Class 568 1. Object-Oriented Design Heuristics 569 2. Stock Fields and Method Headers 571 3. Stock Method and Constructor Implementation 573 10. Chapter 9 Inheritance and Interfaces 587 1. 9.1 Inheritance Basics 588 1. Nonprogramming Hierarchies 589 2. Extending a Class 591 3. Overriding Methods 595 2. 9.2 Interacting with the Superclass 597 1. Calling Overridden Methods 597 2. Accessing Inherited Fields 598 3. Calling a Superclass's Constructor 600 4. DividendStock Behavior 602 5. The Object Class 604 6. The equals Method 605 7. The instanceof Keyword 608  3. 9.3 Polymorphism 610 1. Polymorphism Mechanics 613 2. Interpreting Inheritance Code 615 3. Interpreting Complex Calls 617 4. 9.4 Inheritance and Design 620 1. A Misuse of Inheritance 620 2. Is-a Versus Has-a Relationships 623 3. Graphics2D 624 5. 9.5 Interfaces 626 1. An Interface for Shapes 627 2. Implementing an Interface 629 3. Benefits of Interfaces 632 6. 9.6 Case Study: Financial Class Hierarchy 634 1. Designing the Classes 635 2. Redundant Implementation 639 3. Abstract Classes 642 11. Chapter 10 ArrayLists 662 1. 10.1 ArrayLists 663 1. Basic ArrayList Operations 664 2. ArrayList Searching Methods 667  3. A Complete ArrayList Program 670 4. Adding to and Removing from an ArrayList 672 5. Using the For-Each Loop with ArrayLists 676 6. Wrapper Classes 677 2. 10.2 The Comparable Interface 680 1. Natural Ordering and compareTo 682 2. Implementing the Comparable Interface 686 3. 10.3 Case Study: Vocabulary Comparison 692 1. Some Efficiency Considerations 692 2. Version 1: Compute Vocabulary 695 3. Version 2: Compute Overlap 698 4. Version 3: Complete Program 703 12. Chapter 11 Java Collections Framework 715 1. 11.1 Lists 716 1. Collections 716 2. LinkedList versus ArrayList 717 3. Iterators 720 4. Abstract Data Types (ADTs) 724 5. LinkedList Case Study: Sieve 726 2. 11.2 Sets 729  1. Set Concepts 730 2. TreeSet versus HashSet 732 3. Set Operations 733 4. Set Case Study: Lottery 735 3. 11.3 Maps 737 1. Basic Map Operations 738 2. Map Views (keySet and values) 740 3. TreeMap versus HashMap 741 4. Map Case Study: WordCount 742 5. Collection Overview 745 13. Chapter 12 Recursion 754 1. 12.1 Thinking Recursively 755 1. A Nonprogramming Example 755 2. An Iterative Solution Converted to Recursion 758 3. Structure of Recursive Solutions 760 2. 12.2 A Better Example of Recursion 762 1. Mechanics of Recursion 764 3. 12.3 Recursive Functions and Data 772 1. Integer Exponentiation 772 2. Greatest Common Divisor 775  3. Directory Crawler 781 4. Helper Methods 785 4. 12.4 Recursive Graphics 788 5. 12.5 Recursive Backtracking 792 1. A Simple Example: Traveling North/East 793 2. 8 Queens Puzzle 798 3. Solving Sudoku Puzzles 805 6. 12.6 Case Study: Prefix Evaluator 809 1. Infix, Prefix, and Postfix Notation 809 2. Evaluating Prefix Expressions 810 3. Complete Program 813 14. Chapter 13 Searching and Sorting 832 1. 13.1 Searching and Sorting in the Java Class Libraries 833 1. Binary Search 834 2. Sorting 837 3. Shuffling 838 4. Custom Ordering with Comparators 839 2. 13.2 Program Complexity 843 1. Empirical Analysis 846 2. Complexity Classes 850  3. 13.3 Implementing Searching and Sorting Algorithms 852 1. Sequential Search 853 2. Binary Search 854 3. Recursive Binary Search 857 4. Searching Objects 860 5. Selection Sort 861 4. 13.4 Case Study: Implementing Merge Sort 864 1. Splitting and Merging Arrays 865 2. Recursive Merge Sort 868 3. Complete Program 871 15. Chapter 14 Stacks and Queues 884 1. 14.1 Stack/Queue Basics 885 1. Stack Concepts 885 2. Queue Concepts 888 2. 14.2 Common Stack/Queue Operations 889 1. Transferring Between Stacks and Queues 891 2. Sum of a Queue 892 3. Sum of a Stack 893 3. 14.3 Complex Stack/Queue Operations 896 1. Removing Values from a Queue 896  2. Comparing Two Stacks for Similarity 898 4. 14.4 Case Study: Expression Evaluator 900 1. Splitting into Tokens 901 2. The Evaluator 906 16. Chapter 15 Implementing a Collection Class 922 1. 15.1 Simple ArrayIntList 923 1. Adding and Printing 923 2. Thinking about Encapsulation 929 3. Dealing with the Middle of the List 930 4. Another Constructor and a Constant 935 5. Preconditions and Postconditions 936 2. 15.2 A More Complete ArrayIntList 940 1. Throwing Exceptions 940 2. Convenience Methods 943 3. 15.3 Advanced Features 946 1. Resizing When Necessary 946 2. Adding an Iterator 948 4. 15.4 ArrayList<E> 954 17. Chapter 16 Linked Lists 965 1. 16.1 Working with Nodes 966  1. Constructing a List 967 2. List Basics 969 3. Manipulating Nodes 972 4. Traversing a List 975 2. 16.2 A Linked List Class 979 1. Simple LinkedIntList 979 2. Appending add 981 3. The Middle of the List 985 3. 16.3 A Complex List Operation 992 1. Inchworm Approach 997 4. 16.4 An IntList Interface 998 5. 16.5 LinkedList<E> 1001 1. Linked List Variations 1002 2. Linked List Iterators 1005 3. Other Code Details 1007 18. Chapter 17 Binary Trees 1017 1. 17.1 Binary Tree Basics 1018 1. Node and Tree Classes 1021 2. 17.2 Tree Traversals 1022 1. Constructing and Viewing a Tree 1028  3. 17.3 Common Tree Operations 1037 1. Sum of a Tree 1037 2. Counting Levels 1038 3. Counting Leaves 1040 4. 17.4 Binary Search Trees 1041 1. The Binary Search Tree Property 1042 2. Building a Binary Search Tree 1044 3. The Pattern x = change(x) 1048 4. Searching the Tree 1051 5. Binary Search Tree Complexity 1055 5. 17.5 SearchTree<E> 1056 19. Chapter 18 Advanced Data Structures 1071 1. 18.1 Hashing 1072 1. Array Set Implementations 1072 2. Hash Functions and Hash Tables 1073 3. Collisions 1075 4. Rehashing 1080 5. Hashing Non-Integer Data 1083 6. Hash Map Implementation 1086 2. 18.2 Priority Queues and Heaps 1087  1. Priority Queues 1087 2. Introduction to Heaps 1089 3. Removing from a Heap 1091 4. Adding to a Heap 1092 5. Array Heap Implementation 1094 6. Heap Sort 1098 20. Chapter 19 Functional Programming with Java 8 1107 1. 19.1 Effect-Free Programming 1108 2. 19.2 First-Class Functions 1111 1. Lambda Expressions 1114 3. 19.3 Streams 1117 1. Basic Idea 1117 2. Using Map 1119 3. Using Filter 1120 4. Using Reduce 1122 5. Optional Results 1123 4. 19.4 Function Closures 1124 5. 19.5 Higher-Order Operations on Collections 1127 1. Working with Arrays 1128 2. Working with Lists 1129  3. Working with Files 1133 6. 19.6 Case Study: Perfect Numbers 1134 1. Computing Sums 1135 2. Incorporating Square Root 1138 3. Just Five and Leveraging Concurrency 1141 1. Appendix A Java Summary 1149 2. Appendix B The Java API Specification and Javadoc Comments 1164 3. Appendix C Additional Java Syntax 1170 4. Index 1179 5. Credits 1193  Chapter 1 Introduction to Java Programming 1. 1.1 Basic Computing Concepts 1. Why Programming? 2. Hardware and Software 3. The Digital Realm 4. The Process of Programming 5. Why Java? 6. The Java Programming Environment 2. 1.2 And Now—Java 1. String Literals (Strings) 2. System.out.println 3. Escape Sequences 4. print versus println 5. Identifiers and Keywords 6. A Complex Example: DrawFigures1 7. Comments and Readability 3. 1.3 Program Errors 1. Syntax Errors  2. Logic Errors (Bugs) 4. 1.4 Procedural Decomposition 1. Static Methods 2. Flow of Control 3. Methods That Call Other Methods 4. An Example Runtime Error 5. 1.5 Case Study: DrawFigures 1. Structured Version 2. Final Version without Redundancy 3. Analysis of Flow of Execution  Introduction This chapter begins with a review of some basic terminology about computers and computer programming. Many of these concepts will come up in later chapters, so it will be useful to review them before we start delving into the details of how to program in Java. We will begin our exploration of Java by looking at simple programs that produce output. This discussion will allow us to explore many elements that are common to all Java programs, while working with programs that are fairly simple in structure. After we have reviewed the basic elements of Java programs, we will explore the technique of procedural decomposition by learning how to break up a Java program into several methods. Using this technique, we can break up complex tasks into smaller subtasks that are easier to manage and we can avoid redundancy in our program solutions.  1.1 Basic Computing Concepts Computers are pervasive in our daily lives, and, thanks to the Internet, they give us access to nearly limitless information. Some of this information is essential news, like the headlines at cnn.com. Computers let us share photos with our families and map directions to the nearest pizza place for dinner. Lots of real-world problems are being solved by computers, some of which don't much resemble the one on your desk or lap. Computers allow us to sequence the human genome and search for DNA patterns within it. Computers in recently manufactured cars monitor each vehicle's status and motion. Digital music players such as Apple's iPod actually have computers inside their small casings. Even the Roomba vacuum-cleaning robot houses a computer with complex instructions about how to dodge furniture while cleaning your floors. But what makes a computer a computer? Is a calculator a computer? Is a human being with a paper and pencil a computer? The next several sections attempt to address this question while introducing some basic terminology that will help prepare you to study programming.  Why Programming? At most universities, the first course in computer science is a programming course. Many computer scientists are bothered by this because it leaves people with the impression that computer science is programming. While it is true that many trained computer scientists spend time programming, there is a lot more to the discipline. So why do we study programming first? A Stanford computer scientist named Don Knuth answers this question by saying that the common thread for most computer scientists is that we all in some way work with algorithms.  Algorithm A step-by-step description of how to accomplish a task. Knuth is an expert in algorithms, so he is naturally biased toward thinking of them as the center of computer science. Still, he claims that what is most important is not the algorithms themselves, but rather the thought process that computer scientists employ to develop them. According to Knuth, It has often been said that a person does not really understand something until after teaching it to someone else. Actually a person does not really understand something until after teaching it to a computer, i.e., expressing it as an algorithm.1 1  Knuth, Don. Selected Papers on Computer Science. Stanford, CA: Center for the Study of Language and Information, 1996. Knuth is describing a thought process that is common to most of computer science, which he refers to as algorithmic thinking. We study programming not because it is the most important aspect of computer science, but because it is the best way to explain the approach that computer scientists take to solving problems. The concept of algorithms is helpful in understanding what a computer is and what computer science is all about. The Merriam-Webster dictionary defines the word "computer" as "one that computes." Using that definition, all sorts of devices qualify as computers, including calculators, GPS navigation systems, and children's toys like the Furby. Prior to the invention of electronic computers, it was common to refer to humans as computers. The nineteenth-century mathematician Charles Peirce, for example, was originally hired to work for the U.S. government as an "Assistant Computer" because his job involved performing mathematical computations. In a broad sense, then, the word "computer" can be applied to many devices. But when computer scientists refer to a computer, we are usually thinking of a universal computation device that can be programmed to execute any algorithm. Computer science, then, is the study of computational devices and  the study of computation itself, including algorithms. Algorithms are expressed as computer programs, and that is what this book is all about. But before we look at how to program, it will be useful to review some basic concepts about computers.  Hardware and Software A computer is a machine that manipulates data and executes lists of instructions known as programs.  Program A list of instructions to be carried out by a computer. One key feature that differentiates a computer from a simpler machine like a calculator is its versatility. The same computer can perform many different tasks (playing games, computing income taxes, connecting to other computers around the world), depending on what program it is running at a given moment. A computer can run not only the programs that exist on it currently, but also new programs that haven't even been written yet. The physical components that make up a computer are collectively called hardware. One of the most important pieces of hardware is the central processing unit, or CPU. The CPU is the "brain" of the computer: It is what executes the instructions. Also important is the computer's memory (often called random access memory, or RAM, because the computer can access any part of that memory at any time). The computer uses its memory to store programs that are being executed, along with their data. RAM is limited in size and does not retain its contents when the computer is turned off. Therefore, computers generally also use a hard disk as a larger permanent storage area. Computer programs are collectively called software. The primary piece of software running on a computer is its operating system. An operating system  provides an environment in which many programs may be run at the same time; it also provides a bridge between those programs, the hardware, and the user (the person using the computer). The programs that run inside the operating system are often called applications. When the user selects a program for the operating system to run (e.g., by double-clicking the program's icon on the desktop), several things happen: The instructions for that program are loaded into the computer's memory from the hard disk, the operating system allocates memory for that program to use, and the instructions to run the program are fed from memory to the CPU and executed sequentially.  The Digital Realm In the last section, we saw that a computer is a general-purpose device that can be programmed. You will often hear people refer to modern computers as digital computers because of the way they operate.  Digital Based on numbers that increase in discrete increments, such as the integers 0, 1, 2, 3, etc. Because computers are digital, everything that is stored on a computer is stored as a sequence of integers. This includes every program and every piece of data. An MP3 file, for example, is simply a long sequence of integers that stores audio information. Today we're used to digital music, digital pictures, and digital movies, but in the 1940s, when the first computers were built, the idea of storing complex data in integer form was fairly unusual. Not only are computers digital, storing all information as integers, but they are also binary, which means they store integers as binary numbers.  Binary Number A number composed of just 0s and 1s, also known as a base-2 number. Humans generally work with decimal or base-10 numbers, which match our physiology (10 fingers and 10 toes). However, when we were designing the first computers, we wanted systems that would be easy to create and very reliable. It turned out to be simpler to build these systems on top of binary phenomena (e.g., a circuit being open or closed) rather than having 10 different states that would have to be distinguished from one another (e.g., 10 different voltage levels). From a mathematical point of view, you can store things just as easily using binary numbers as you can using base-10 numbers. But since it is easier to construct a physical device that uses binary numbers, that's what computers use. This does mean, however, that people who aren't used to computers find their conventions unfamiliar. As a result, it is worth spending a little time reviewing how binary numbers work. To count with binary numbers, as with base-10 numbers, you start with 0 and count up, but you run out of digits much faster. So, counting in binary, you say 0 1  And already you've run out of digits. This is like reaching 9 when you count in base-10. After you run out of digits, you carry over to the next digit. So, the next two binary numbers are 10 11  And again, you've run out of digits. This is like reaching 99 in base-10. Again, you carry over to the next digit to form the three-digit number 100. In binary, whenever you see a series of ones, such as 111111, you know you're  just one away from the digits all flipping to 0s with a 1 added in front, the same way that, in base-10, when you see a number like 999999, you know that you are one away from all those digits turning to 0s with a 1 added in front. Table 1.1 shows how to count up to the base-10 number 8 using binary.  Table 1.1 Decimal vs. Binary Decimal Binary 0 0 1 1 2 10 3 11 4 100 5 101 6 110 7 111 8 1000 We can make several useful observations about binary numbers. Notice in the table that the binary numbers 1, 10, 100, and 1000 are all perfect powers of 2 (20, 21, 22, 23). In the same way that in base-10 we talk about a ones digit, tens digit, hundreds digit, and so on, we can think in binary of a ones digit, twos digit, fours digit, eights digit, sixteens digit, and so on. Computer scientists quickly found themselves needing to refer to the sizes of different binary quantities, so they invented the term bit to refer to a single binary digit and the term byte to refer to 8 bits. To talk about large amounts of memory, they invented the terms "kilobytes" (KB), "megabytes" (MB), "gigabytes" (GB), and so on. Many people think that these correspond to the metric system, where "kilo" means 1000, but that is only approximately true. We use the fact that 210 is approximately equal to 1000 (it actually equals 1024). Table 1.2 shows some common units of memory storage:  Table 1.2 Units of Memory Storage Measurement  Power of 2  kilobyte (KB) 210 megabyte (MB)  220  gigabyte (GB) 230 terabyte (TB) 240 petabyte (PB) 250  Actual Value  Example  500-word paper (3 KB) typical book (1 MB) 1,048,576 or song (5 MB) typical movie (4.7 1,073,741,824 GB) 20 million books in 1,099,511,627,776 the Library of Congress (20 TB) 10 billion photos on 1,125,899,906,842,624 Facebook (1.5 PB) 1024  The Process of Programming The word code describes program fragments ("these four lines of code") or the act of programming ("Let's code this into Java"). Once a program has been written, you can execute it.  Program Execution The act of carrying out the instructions contained in a program. The process of execution is often called running. This term can also be used as a verb ("When my program runs it does something strange") or as a noun ("The last run of my program produced these results").  A computer program is stored internally as a series of binary numbers known as the machine language of the computer. In the early days, programmers entered numbers like these directly into the computer. Obviously, this is a tedious and confusing way to program a computer, and we have invented all sorts of mechanisms to simplify this process. Modern programmers write in what are known as high-level programming languages, such as Java. Such programs cannot be run directly on a computer: They first have to be translated into a different form by a special program known as a compiler.  Compiler A program that translates a computer program written in one language into an equivalent program in another language (often, but not always, translating from a high-level language into machine language). A compiler that translates directly into machine language creates a program that can be executed directly on the computer, known as an executable. We refer to such compilers as native compilers because they compile code to the lowest possible level (the native machine language of the computer). This approach works well when you know exactly what computer you want to use to run your program. But what if you want to execute a program on many different computers? You'd need a compiler that generates different machine language output for each of them. The designers of Java decided to use a different approach. They cared a lot about their programs being able to run on many different computers, because they wanted to create a language that worked well for the Web. Instead of compiling into machine language, Java programs compile into what are known as Java bytecodes. One set of bytecodes can execute on many different machines. These bytecodes represent an intermediate level: They aren't quite as high-level as Java or as low-level as machine language. In fact, they are the machine language of a theoretical computer known as the Java Virtual Machine (JVM).  Java Virtual Machine A theoretical computer whose machine language is the set of Java bytecodes. A JVM isn't an actual machine, but it's similar to one. When we compile programs to this level, there isn't much work remaining to turn the Java bytecodes into actual machine instructions. To actually execute a Java program, you need another program that will execute the Java bytecodes. Such programs are known generically as Java runtimes, and the standard environment distributed by Oracle Corporation is known as the Java Runtime Environment (JRE).  Java Runtime A program that executes compiled Java bytecodes. Most people have Java runtimes on their computers, even if they don't know about them. For example, Apple's Mac OS X includes a Java runtime, and many Windows applications install a Java runtime.  Why Java? When Sun Microsystems released Java in 1995, it published a document called a "white paper" describing its new programming language. Perhaps the key sentence from that paper is the following: Java: A simple, object-oriented, network-savvy, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded, dynamic language.2 2http://www.oracle.com/technetwork/java/langenv-140151.html  This sentence covers many of the reasons why Java is a good introductory  programming language. For starters, Java is reasonably simple for beginners to learn, and it embraces object-oriented programming, a style of writing programs that has been shown to be very successful for creating large and complex software systems. Java also includes a large amount of prewritten software that programmers can utilize to enhance their programs. Such off-the-shelf software components are often called libraries. For example, if you wish to write a program that connects to a site on the Internet, Java contains a library to simplify the connection for you. Java contains libraries to draw graphical user interfaces (GUIs), retrieve data from databases, and perform complex mathematical computations, among many other things. These libraries collectively are called the Java class libraries.  Java Class Libraries The collection of preexisting Java code that provides solutions to common programming problems. The richness of the Java class libraries has been an extremely important factor in the rise of Java as a popular language. The Java class libraries in version 1.7 include over 4000 entries. Another reason to use Java is that it has a vibrant programmer community. Extensive online documentation and tutorials are available to help programmers learn new skills. Many of these documents are written by Oracle, including an extensive reference to the Java class libraries called the API Specification (API stands for Application Programming Interface). Java is extremely platform independent; unlike programs written in many other languages, the same Java program can be executed on many different operating systems, such as Windows, Linux, and Mac OS X. Java is used extensively for both research and business applications, which means that a large number of programming jobs exist in the marketplace today for skilled Java programmers. A sample Google search for the phrase  "Java jobs" returned around 180,000,000 hits at the time of this writing.  The Java Programming Environment You must become familiar with your computer setup before you start programming. Each computer provides a different environment for program development, but there are some common elements that deserve comment. No matter what environment you use, you will follow the same basic three steps: 1. Type in a program as a Java class. 2. Compile the program file. 3. Run the compiled version of the program. The basic unit of storage on most computers is a file. Every file has a name. A file name ends with an extension, which is the part of a file's name that follows the period. A file's extension indicates the type of data contained in the file. For example, files with the extension .doc are Microsoft Word documents, and files with the extension .mp3 are MP3 audio files. The Java program files that you create must use the extension .java. When you compile a Java program, the resulting Java bytecodes are stored in a file with the same name and the extension .class. Most Java programmers use what are known as Integrated Development Environments, or IDEs, which provide an all-in-one environment for creating, editing, compiling, and executing program files. Some of the more popular choices for introductory computer science classes are Eclipse, jGRASP, DrJava, BlueJ, and TextPad. Your instructor will tell you what environment you should use. Try typing the following simple program in your IDE (the line numbers are  not part of the program but are used as an aid): 1 2 3 4 5  public class Hello { public static void main(String[] args) { System.out.println("Hello, world!"); } }  Don't worry about the details of this program right now. We will explore those in the next section. Once you have created your program file, move to step 2 and compile it. The command to compile will be different in each development environment, but the process is the same (typical commands are "compile" or "build"). If any errors are reported, go back to the editor, fix them, and try to compile the program again. (We'll discuss errors in more detail later in this chapter.) Once you have successfully compiled your program, you are ready to move to step 3, running the program. Again, the command to do this will differ from one environment to the next, but the process is similar (the typical command is "run"). The diagram in Figure 1.1 summarizes the steps you would follow in creating a program called Hello.java. In some IDEs (most notably Eclipse), the first two steps are combined. In these environments the process of compiling is more incremental; the compiler will warn you about errors as you type in code. It is generally not necessary to formally ask such an environment to compile your program because it is compiling as you type. When your program is executed, it will typically interact with the user in some way. The Hello.java program involves an onscreen window known as the console.  Console Window A special text-only window in which Java programs interact with the user.  The console window is a classic interaction mechanism wherein the computer displays text on the screen and sometimes waits for the user to type responses. This is known as console or terminal interaction. The text the computer prints to the console window is known as the output of the program. Anything typed by the user is known as the console input.  Figure 1.1 Creation and execution of a Java program Description To keep things simple, most of the sample programs in this book involve console interaction. Keeping the interaction simple will allow you to focus your attention and effort on other aspects of programming.  1.2 And Now—Java It's time to look at a complete Java program. In the Java programming language, nothing can exist outside of a class.  Class A unit of code that is the basic building block of Java programs. The notion of a class is much richer than this, as you'll see when we get to Chapter 8, but for now all you need to know is that each of your Java programs will be stored in a class. It is a tradition in computer science that when you describe a new programming language, you should start with a program that produces a single line of output with the words, "Hello, world!" The "hello world" tradition has been broken by many authors of Java books because the program turns out not to be as short and simple when it is written in Java as when it is written in other languages, but we'll use it here anyway. Here is our "hello world" program: 1 2 3 4 5  public class Hello { public static void main(String[] args) { System.out.println("Hello, world!"); } }  This program defines a class called Hello. Oracle has established the convention that class names always begin with a capital letter, which makes it easy to recognize them. Java requires that the class name and the file name match, so this program must be stored in a file called Hello.java. You don't have to understand all the details of this program just yet, but you do need to understand the basic structure.  The basic form of a Java class is as follows: public class <name> { <method> <method> ... <method> }  This type of description is known as a syntax template because it describes the basic form of a Java construct. Java has rules that determine its legal syntax or grammar. Each time we introduce a new element of Java, we'll begin by looking at its syntax template. By convention, we use the less-than (<) and greater-than (>) characters in a syntax template to indicate items that need to be filled in (in this case, the name of the class and the methods). When we write "..." in a list of elements, we're indicating that any number of those elements may be included. The first line of the class is known as the class header. The word public in the header indicates that this class is available to anyone to use. Notice that the program code in a class is enclosed in curly brace characters ({ }). These characters are used in Java to group together related bits of code. In this case, the curly braces are indicating that everything defined within them is part of this public class. So what exactly can appear inside the curly braces? What can be contained in a class? All sorts of things, but for now, we'll limit ourselves to methods. Methods are the next-smallest unit of code in Java, after classes. A method represents a single action or calculation to be performed.  Method A program unit that represents a particular action or computation. Simple methods are like verbs: They command the computer to perform some action. Inside the curly braces for a class, you can define several different methods. At a minimum, a complete program requires a special  method that is known as the main method. It has the following syntax: public static void main(String[] args) { <statement>; <statement>; ... <statement>; }  Just as the first line of a class is known as a class header, the first line of a method is known as a method header. The header for main is rather complicated. Most people memorize this as a kind of magical incantation. You want to open the door to Ali Baba's cave? You say, "Open Sesame!" You want to create an executable Java program? You say, public static void main(String[] args). A group of Java teachers make fun of this with a website called publicstaticvoidmain.com. Just memorizing magical incantations is never satisfying, especially for computer scientists who like to know everything that is going on in their programs. But this is a place where Java shows its ugly side, and you'll just have to live with it. New programmers, like new drivers, must learn to use something complex without fully understanding how it works. Fortunately, by the time you finish this book, you'll understand every part of the incantation. Notice that the main method has a set of curly braces of its own. They are again used for grouping, indicating that everything that appears between them is part of the main method. The lines in between the curly braces specify the series of actions the computer should perform when it executes the method. We refer to these as the statements of the method. Just as you put together an essay by stringing together complete sentences, you put together a method by stringing together statements.  Statement An executable snippet of code that represents a complete command.  Each statement is terminated by a semicolon. The sample "hello world" program has just a single statement that is known as a println statement: System.out.println("Hello, world!");  Notice that this statement ends with a semicolon. The semicolon has a special status in Java; it is used to terminate statements in the same way that periods terminate sentences in English. In the basic "hello world" program there is just a single command to produce a line of output, but consider the following variation (called Hello2), which has four lines of code to be executed in the main method: 1 2 3 4 5 6 7 8  public class Hello2 { public static void main(String[] args) { System.out.println("Hello, world!"); System.out.println(); System.out.println("This program produces four"); System.out.println("lines of output."); } }  Notice that there are four semicolons in the main method, one at the end of each of the four println statements. The statements are executed in the order in which they appear, from first to last, so the Hello2 program produces the following output: Hello, world! This program produces four lines of output.  Let's summarize the different levels we just looked at: A Java program is stored in a class. Within the class, there are methods. At a minimum, a complete program requires a special method called main. Inside a method like main, there is a series of statements, each of which  represents a single command for the computer to execute. It may seem odd to put the opening curly brace at the end of a line rather than on a line by itself. Some people would use this style of indentation for the program instead: 1 2 3 4 5 6 7  public class Hello3 { public static void main(String[] args) { System.out.println("Hello, world!"); } }  Different people will make different choices about the placement of curly braces. The style we use follows Oracle's official Java coding conventions, but the other style has its advocates too. Often people will passionately argue that one way is much better than the other, but it's really a matter of personal taste because each choice has some advantages and some disadvantages. Your instructor may require a particular style; if not, you should choose a style that you are comfortable with and then use it consistently. Now that you've seen an overview of the structure, let's examine some of the details of Java programs.  Did You Know? Hello, World! The "hello world" tradition was started by Brian Kernighan and Dennis Ritchie. Ritchie invented a programming language known as C in the 1970s and, together with Kernighan, coauthored the first book describing C, published in 1978. The first complete program in their book was a "hello world" program. Kernighan and Ritchie, as well as their book The C Programming Language, have been affectionately referred to as "K & R" ever since. Many major programming languages have borrowed the basic C syntax as a way to leverage the popularity of C and to encourage programmers to switch  to it. The languages C++ and Java both borrow a great deal of their core syntax from C. Kernighan and Ritchie also had a distinctive style for the placement of curly braces and the indentation of programs that has become known as "K & R style." This is the style that Oracle recommends and that we use in this book.  String Literals (Strings) When you are writing Java programs (such as the preceding "hello world" program), you'll often want to include some literal text to send to the console window as output. Programmers have traditionally referred to such text as a string because it is composed of a sequence of characters that we string together. The Java language specification uses the term string literals. In Java you specify a string literal by surrounding the literal text in quotation marks, as in "This is a bunch of text surrounded by quotation marks."  You must use double quotation marks, not single quotation marks. The following is not a valid string literal:  'Bad stuff here.'  The following is a valid string literal: "This is a string even with 'these' quotes inside."  String literals must not span more than one line of a program. The following is not a valid string literal:  "This is really  bad stuff right here."  System.out.println As you have seen, the main method of a Java program contains a series of statements for the computer to carry out. They are executed sequentially, starting with the first statement, then the second, then the third, and so on until the final statement has been executed. One of the simplest and most common statements is System.out.println, which is used to produce a line of output. This is another "magical incantation" that you should commit to memory. As of this writing, Google lists around 8,000,000 web pages that mention System.out.println. The key thing to remember about this statement is that it's used to produce a line of output that is sent to the console window. The simplest form of the println statement has nothing inside its parentheses and produces a blank line of output: System.out.println();  You need to include the parentheses even if you don't have anything to put inside them. Notice the semicolon at the end of the line. All statements in Java must be terminated with a semicolon. More often, however, you use println to output a line of text: System.out.println("This line uses the println method.");  The above statement commands the computer to produce the following line of output: This line uses the println method.  Each println statement produces a different line of output. For example, consider the following three statements:  System.out.println("This is the first line of output."); System.out.println(); System.out.println("This is the third, below a blank line.");  Executing these statements produces the following three lines of output (the second line is blank): This is the first line of output. This is the third, below a blank line.  Escape Sequences Any system that involves quoting text will lead you to certain difficult situations. For example, string literals are contained inside quotation marks, so how can you include a quotation mark inside a string literal? String literals also aren't allowed to break across lines, so how can you include a line break inside a string literal? The solution is to embed what are known as escape sequences in the string literals. Escape sequences are two-character sequences that are used to represent special characters. They all begin with the backslash character (\). Table 1.3 lists some of the more common escape sequences.  Table 1.3 Common Escape Sequences Sequence \t \n \" \\  Represents tab character new line character quotation mark backslash character  Keep in mind that each of these two-character sequences actually stands for just a single character. For example, consider the following statement: System.out.println("What \"characters\" does this \\ print?");  If you executed this statement, you would get the following output: What "characters" does this \ print?  The string literal in the println has three escape sequences, each of which is two characters long and produces a single character of output. While string literals themselves cannot span multiple lines (that is, you cannot use a carriage return within a string literal to force a line break), you can use the \n escape sequence to embed new line characters in a string. This leads to the odd situation where a single println statement can produce more than one line of output. For example, consider this statement: System.out.println("This\nproduces 3 lines\nof output.");  If you execute it, you will get the following output: This produces 3 lines of output.  The println itself produces one line of output, but the string literal contains two new line characters that cause it to be broken up into a total of three lines of output. To produce the same output without new line characters, you would have to issue three separate println statements. This is another programming habit that tends to vary according to taste. Some people (including the authors) find it hard to read string literals that contain \n escape sequences, but other people prefer to write fewer lines of code. Once again, you should make up your own mind about when to use the new  line escape sequence.  print versus println Java has a variation of the println command called print that allows you to produce output on the current line without going to a new line of output. The println command really does two different things: It sends output to the current line, and then it moves to the beginning of a new line. The print command does only the first of these. Thus, a series of print commands will generate output all on the same line. Only a println command will cause the current line to be completed and a new line to be started. For example, consider these six statements: System.out.print("To be "); System.out.print("or not to be."); System.out.print("That is "); System.out.println("the question."); System.out.print("This is"); System.out.println(" for the whole family!");  These statements produce two lines of output. Remember that every println statement produces exactly one line of output; because there are two println statements here, there are two lines of output. After the first statement executes, the current line looks like this:  The arrow below the output line indicates the position where output will be sent next. We can simplify our discussion if we refer to the arrow as the output cursor. Notice that the output cursor is at the end of this line and that it appears after a space. The reason is that the command was a print (doesn't go to a new line) and the string literal in the print ended with a space. Java will not insert a space for you unless you specifically request it. After the next print, the line looks like this:  There's no space at the end now because the string literal in the second print command ends in a period, not a space. After the next print, the line looks like this:  There is no space between the period and the word "That" because there was no space in the print commands, but there is a space at the end of the string literal in the third statement. After the next statement executes, the output looks like this:  Because this fourth statement is a println command, it finishes the output line and positions the cursor at the beginning of the second line. The next statement is another print that produces this:  The final println completes the second line and positions the output cursor at the beginning of a new line:  These six statements are equivalent to the following two single statements: System.out.println("To be or not to be.That is the question."); System.out.println("This is for the whole family!");  Using the print and println commands together to produce lines like these may seem a bit silly, but you will see that there are more interesting applications of print in the next chapter.  Remember that it is possible to have an empty println command: System.out.println();  Because there is nothing inside the parentheses to be written to the output line, this command positions the output cursor at the beginning of the next line. If there are print commands before this empty println, it finishes out the line made by those print commands. If there are no previous print commands, it produces a blank line. An empty print command is meaningless and illegal.  Identifiers and Keywords The words used to name parts of a Java program are called identifiers.  Identifier A name given to an entity in a program, such as a class or method. Identifiers must start with a letter, which can be followed by any number of letters or digits. The following are all legal identifiers: first  hiThere  numStudents  The Java language specification defines the set of letters to include the underscore and dollar-sign characters (_ and $), which means that the following are legal identifiers as well: two_plus_two  _count  $2donuts  MAX_COUNT  The following are illegal identifiers:  two+two  hi there  hi-There  2by4  Java has conventions for capitalization that are followed fairly consistently by programmers. All class names should begin with a capital letter, as with the Hello, Hello2, and Hello3 classes introduced earlier. The names of methods should begin with lowercase letters, as in the main method. When you are putting several words together to form a class or method name, capitalize the first letter of each word after the first. In the next chapter we'll discuss constants, which have yet another capitalization scheme, with all letters in uppercase and words separated by underscores. These different schemes might seem like tedious constraints, but using consistent capitalization in your code allows the reader to quickly identify the various code elements. For example, suppose that you were going to put together the words "all my children" into an identifier. The result would be AllMyChildren  for a class name (each word starts with a capital)  for a method name (starts with a lowercase letter, subsequent words capitalized) allMyChildren  for a constant name (all uppercase, with words separated by underscores; described in Chapter 2) ALL_MY_CHILDREN  Java is case sensitive, so the identifiers class, Class, CLASS, and cLASs are all considered different. Keep this in mind as you read error messages from the compiler. People are good at understanding what you write, even if you misspell words or make little mistakes like changing the capitalization of a word. However, mistakes like these cause the Java compiler to become hopelessly confused. Don't hesitate to use long identifiers. The more descriptive your names are, the easier it will be for people (including you) to read your programs. Descriptive identifiers are worth the time they take to type. Java's String class, for example, has a method called compareToIgnoreCase. Be aware, however, that Java has a set of predefined identifiers called keywords that are reserved for particular uses. As you read this book, you will learn many of these keywords and their uses. You can only use keywords for their intended purposes. You must be careful to avoid using these words in  the names of identifiers. For example, if you name a method short or try, this will cause a problem, because short and try are reserved keywords. Table 1.4 shows the complete list of reserved keywords.  Table 1.4 List of Java Keywords 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  A Complex Example: DrawFigures1 The println statement can be used to draw text figures as output. Consider the following more complicated program example (notice that it uses two empty println statements to produce blank lines): 1 2 3 4 5 6 7 8 9 10 11  public class DrawFigures1 { public static void main(String[] args) { System.out.println(" /\\"); System.out.println(" / \\"); System.out.println(" / \\"); System.out.println(" \\ /"); System.out.println(" \\ /"); System.out.println(" \\/"); System.out.println(); System.out.println(" \\ /"); System.out.println(" \\ /");  12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34  System.out.println(" \\/"); System.out.println(" /\\"); System.out.println(" / \\"); System.out.println(" / \\"); System.out.println(); System.out.println(" /\\"); System.out.println(" / \\"); System.out.println(" / \\"); System.out.println("+------+"); System.out.println("| |"); System.out.println("| |"); System.out.println("+------+"); System.out.println("|United|"); System.out.println("|States|"); System.out.println("+------+"); System.out.println("| |"); System.out.println("| |"); System.out.println("+------+"); System.out.println(" /\\"); System.out.println(" / \\"); System.out.println(" / \\"); } }  The following is the output the program generates. Notice that the program includes double backslash characters (\\), but the output has single backslash characters. This is an example of an escape sequence, as described previously.  Comments and Readability Java is a free-format language. This means you can put in as many or as few spaces and blank lines as you like, as long as you put at least one space or other punctuation mark between words. However, you should bear in mind that the layout of a program can enhance (or detract from) its readability. The following program is legal but hard to read:  2  1 public class Ugly{public static void main(String[] args) {System.out.println("How short I am!");}}  Here are some simple rules to follow that will make your programs more readable: Put class and method headers on lines by themselves. Put no more than one statement on each line. Indent your program properly. When an opening brace appears, increase the indentation of the lines that follow it. When a closing brace appears, reduce the indentation. Indent statements inside curly braces by a consistent number of spaces (a common choice is four spaces per level of indentation). Use blank lines to separate parts of the program (e.g., methods). Using these rules to rewrite the Ugly program yields the following code: 1 2 3 4 5  public class Ugly { public static void main(String[] args) { System.out.println("How short I am!"); } }  Well-written Java programs can be quite readable, but often you will want to include some explanations that are not part of the program itself. You can annotate programs by putting notes called comments in them.  Comment Text that programmers include in a program to explain their code. The compiler ignores comments. There are two comment forms in Java. In the first form, you open the comment with a slash followed by an asterisk and you close it with an asterisk followed by a slash: /* like this */  You must not put spaces between the slashes and the asterisks:  / * this is bad * /  You can put almost any text you like, including multiple lines, inside the comment: /* Thaddeus Martin Assignment #1 Instructor: Professor Walingford Grader: Bianca Montgomery  */  The only things you aren't allowed to put inside a comment are the comment end characters. The following code is not legal: /* This comment has an asterisk/slash /*/ in it, which prematurely closes the comment. This is bad. */  Java also provides a second comment form for shorter, single-line comments. You can use two slashes in a row to indicate that the rest of the current line (everything to the right of the two slashes) is a comment. For example, you can put a comment after a statement: System.out.println("You win!"); // Good job!  Or you can create a comment on its own line: // give an introduction to the user System.out.println("Welcome to the game of blackjack."); System.out.println(); System.out.println("Let me explain the rules.");  You can even create blocks of single-line comments: // // // //  Thaddeus Martin Assignment #1 Instructor: Professor Walingford Grader: Bianca Montgomery  Some people prefer to use the first comment form for comments that span multiple lines but it is safer to use the second form because you don't have to remember to close the comment. It also makes the comment stand out more. This is another case in which, if your instructor does not tell you to use a particular comment style, you should decide for yourself which style you prefer and use it consistently. Don't confuse comments with the text of println statements. The text of your comments will not be displayed as output when the program executes. The comments are there only to help readers examine and understand the program. It is a good idea to include comments at the beginning of each class file to indicate what the class does. You might also want to include information about who you are, what course you are taking, your instructor and/or grader's name, the date, and so on. You should also comment each method to indicate what it does. Commenting becomes more useful in larger and more complicated programs, as well as in programs that will be viewed or modified by more than one programmer. Clear comments are extremely helpful to explain to another person, or to yourself at a later time, what your program is doing and why it is doing it.  In addition to the two comment forms already discussed, Java supports a particular style of comments known as Javadoc comments. Their format is more complex, but they have the advantage that you can use a program to extract the comments to make HTML files suitable for reading with a web browser. Javadoc comments are useful in more advanced programming and are discussed in more detail in Appendix B.  1.3 Program Errors In 1949, Maurice Wilkes, an early pioneer of computing, expressed a sentiment that still rings true today: As soon as we started programming, we found out to our surprise that it wasn't as easy to get programs right as we had thought. Debugging had to be discovered. I can remember the exact instant when I realized that a large part of my life from then on was going to be spent in finding mistakes in my own programs. You also will have to face this reality as you learn to program. You're going to make mistakes, just like every other programmer in history, and you're going to need strategies for eliminating those mistakes. Fortunately, the computer itself can help you with some of the work. There are three kinds of errors that you'll encounter as you write programs: Syntax errors occur when you misuse Java. They are the programming equivalent of bad grammar and are caught by the Java compiler. Logic errors occur when you write code that doesn't perform the task it is intended to perform. Runtime errors are logic errors that are so severe that Java stops your program from executing.  Syntax Errors Human beings tend to be fairly forgiving about minor mistakes in speech. For example, we might find it to be odd phrasing, but we generally understand Master Yoda when he says, "Unfortunate that you rushed to face him . . . that incomplete was your training. Not ready for the burden were you."  The Java compiler will be far less forgiving. The compiler reports syntax errors as it attempts to translate your program from Java into bytecodes if your program breaks any of Java's grammar rules. For example, if you misplace a single semicolon in your program, you can send the compiler into a tailspin of confusion. The compiler may report several error messages, depending on what it thinks is wrong with your program. A program that generates compilation errors cannot be executed. If you submit your program to the compiler and the compiler reports errors, you must fix the errors and resubmit the program. You will not be able to proceed until your program is free of compilation errors. Some development environments, such as Eclipse, help you along the way by underlining syntax errors as you write your program. This makes it easy to spot exactly where errors occur. It's possible for you to introduce an error before you even start writing your program, if you choose the wrong name for its file.  Common Programming Error File Name Does Not Match Class Name As mentioned earlier, Java requires that a program's class name and file name match. For example, a program that begins with public class Hello must be stored in a file called Hello.java. If you use the wrong file name (for example, saving it as WrongFileName.java), you'll get an error message like this: WrongFileName.java:1: error: class Hello is public, should be declared in a file named Hello.java public class Hello { ^ 1 error  The file name is just the first hurdle. A number of other errors may exist in  your Java program. One of the most common syntax errors is to misspell a word. You may have punctuation errors, such as missing semicolons. It's also easy to forget an entire word, such as a required keyword. The error messages the compiler gives may or may not be helpful. If you don't understand the content of the error message, look for the caret marker (⁁) below the line, which points at the position in the line where the compiler became confused. This can help you pinpoint the place where a required keyword might be missing.  Common Programming Error Misspelled Words Java (like most programming languages) is very picky about spelling. You need to spell each word correctly, including proper capitalization. Suppose, for example, that you were to replace the println statement in the "hello world" program with the following:  System.out.pruntln("Hello, world!");  When you try to compile this program, it will generate an error message similar to the following: Hello.java:3: error: cannot find symbol symbol : method pruntln(java.lang.String) location: variable out of type PrintStream System.out.pruntln("Hello, world!"); ^ 1 error  The first line of this output indicates that the error occurs in the file Hello.java on line 3 and that the error is that the compiler cannot find a symbol. The second line indicates that the symbol it can't find is a method called pruntln. That's because there is no such method; the method is called  println.  The error message can take slightly different forms depending on what you have misspelled. For example, you might forget to capitalize the word System:  system.out.println("Hello, world!");  You will get the following error message: Hello.java:3: error: package system does not exist system.out.println("Hello, world!"); ^ 1 error  Again, the first line indicates that the error occurs in line 3 of the file Hello.java. The error message is slightly different here, though, indicating that it can't find a package called system. The second and third lines of this error message include the original line of code with an arrow (caret) pointing to where the compiler got confused. The compiler errors are not always very clear, but if you pay attention to where the arrow is pointing, you'll have a pretty good sense of where the error occurs. If you still can't figure out the error, try looking at the error's line number and comparing the contents of that line with similar lines in other programs. You can also ask someone else, such as an instructor or lab assistant, to examine your program.  Common Programming Error Forgetting a Semicolon All Java statements must end with semicolons, but it's easy to forget to put a semicolon at the end of a statement, as in the following program:  1 2 3 4 5 6  public class MissingSemicolon { public static void main(String[] args) { System.out.println("A rose by any other name") System.out.println("would smell as sweet"); } }  In this case, the compiler produces output similar to the following: MissingSemicolon.java:3: error: ';' expected System.out.println("would smell as sweet"); ^ 1 error  Some versions of the Java compiler list line 4 as the cause of the problem, not line 3, where the semicolon was actually forgotten. This is because the compiler is looking forward for a semicolon and isn't upset until it finds something that isn't a semicolon, which it does when it reaches line 4. Unfortunately, as this case demonstrates, compiler error messages don't always direct you to the correct line to be fixed.  Common Programming Error Forgetting a Required Keyword Another common syntax error is to forget a required keyword when you are typing your program, such as static or class. Double-check your programs against the examples in the textbook to make sure you haven't omitted an important keyword. The compiler will give different error messages depending on which keyword is missing, but the messages can be hard to understand. For example, you might write a program called Bug4 and forget the keyword class when writing its class header. In this case, the compiler will provide the following error message: Bug4.java:1: error:  class, interface, or enum expected  public Bug4 { ^ 1 error  However, if you forget the keyword void when declaring the main method, the compiler generates a different error message: Bug5.java:2: error: invalid method declaration; return type required public static main(String[] args) { ^ 1 error  Yet another common syntax error is to forget to close a string literal. A good rule of thumb to follow is that the first error reported by the compiler is the most important one. The rest might be the result of that first error. Many programmers don't even bother to look at errors beyond the first, because fixing that error and recompiling may cause the other errors to disappear.  Logic Errors (Bugs) Logic errors are also called bugs. Computer programmers use words like "bug-ridden" and "buggy" to describe poorly written programs, and the process of finding and eliminating bugs from programs is called debugging. The word "bug" is an old engineering term that predates computers; early computing bugs sometimes occurred in hardware as well as software. Admiral Grace Hopper, an early pioneer of computing, is largely credited with popularizing the use of the term in the context of computer programming. She often told the true story of a group of programmers at Harvard University in the mid-1940s who couldn't figure out what was wrong with their programs until they opened up the computer and found an actual moth trapped inside. The form that a bug takes may vary. Sometimes your program will simply behave improperly. For example, it might produce the wrong output. Other  times it will ask the computer to perform some task that is clearly a mistake, in which case your program will have a runtime error that stops it from executing. In this chapter, since your knowledge of Java is limited, generally the only type of logic error you will see is a mistake in program output from an incorrect println statement or method call. We'll look at an example of a runtime error in the next section.  1.4 Procedural Decomposition Brian Kernighan, coauthor of The C Programming Language, has said, "Controlling complexity is the essence of computer programming." People have only a modest capacity for detail. We can't solve complex problems all at once. Instead, we structure our problem solving by dividing the problem into manageable pieces and conquering each piece individually. We often use the term decomposition to describe this principle as applied to programming.  Decomposition A separation into discernible parts, each of which is simpler than the whole. With procedural programming languages like C, decomposition involves dividing a complex task into a set of subtasks. This is a very verb- or actionoriented approach, involving dividing up the overall action into a series of smaller actions. This technique is called procedural decomposition.  Common Programming Error Not Closing a String Literal or Comment Every string literal has to have an opening quote and a closing quote, but it's easy to forget the closing quotation mark. For example, you might say:  System.out.println("Hello, world!);  This produces three different error messages, even though there is only one  underlying syntax error: Hello.java:3: error: unclosed string literal System.out.println("hello world); ^ Hello.java:3: error: ';' expected System.out.println("hello world); ^ Hello.java:5: error: reached end of file while parsing } ^ 3 errors  In this case, the first error message is quite clear, including an arrow pointing at the beginning of the string literal that wasn't closed. The second error message was caused by the first. Because the string literal was not closed, the compiler didn't notice the right parenthesis and semicolon that appear at the end of the line. A similar problem occurs when you forget to close a multiline comment by writing */, as in the first line of the following program: /* This is a bad program. public class Bad { public static void main(String[] args){ System.out.println("Hi there."); } } /* end of program */  The preceding file is not a program; it is one long comment. Because the comment on the first line is not closed, the entire program is swallowed up. Luckily, many Java editor programs color the parts of a program to help you identify them visually. Usually, if you forget to close a string literal or comment, the rest of your program will turn the wrong color, which can help you spot the mistake. Java was designed for a different kind of decomposition that is more noun- or object-oriented. Instead of thinking of the problem as a series of actions to be performed, we think of it as a collection of objects that have to interact.  As a computer scientist, you should be familiar with both types of problem solving. This book begins with procedural decomposition and devotes many chapters to mastering various aspects of the procedural approach. Only after you have thorougly practiced procedural programming will we turn our attention back to object decomposition and object-oriented programming. As an example of procedural decomposition, consider the problem of baking a cake. You can divide this problem into the following subproblems: Make the batter. Bake the cake. Make the frosting. Frost the cake. Each of these four tasks has details associated with it. To make the batter, for example, you follow these steps: Mix the dry ingredients. Cream the butter and sugar. Beat in the eggs. Stir in the dry ingredients. Thus, you divide the overall task into subtasks, which you further divide into even smaller subtasks. Eventually, you reach descriptions that are so simple they require no further explanation (i.e., primitives). A partial diagram of this decomposition is shown in Figure 1.2. "Make cake" is the highest-level operation. It is defined in terms of four lower-level operations called "Make batter," "Bake," "Make frosting," and "Frost cake." The "Make batter" operation is defined in terms of even lower-level operations, and the same could be done for the other three operations. This diagram is called a structure diagram and is intended to show how a problem  is broken down into subproblems. In this diagram, you can also tell in what order operations are performed by reading from left to right. That is not true of most structure diagrams. To determine the actual order in which subprograms are performed, you usually have to refer to the program itself.  Figure 1.2 Decomposition of "Make cake" task One final problem-solving term has to do with the process of programming. Professional programmers develop programs in stages. Instead of trying to produce a complete working program all at once, they choose some piece of the problem to implement first. Then they add another piece, and another, and another. The overall program is built up slowly, piece by piece. This process is known as iterative enhancement or stepwise refinement.  Iterative Enhancement The process of producing a program in stages, adding new functionality at each stage. A key feature of each iterative step is that you can test it to make sure that piece works before moving on. Now, let's look at a construct that will allow you to iteratively enhance your Java programs to improve their structure and reduce their redundancy: static methods.  Static Methods  Java is designed for objects, and programming in Java usually involves decomposing a problem into various objects, each with methods that perform particular tasks. You will see how this works in later chapters, but for now, we are going to explore procedural decomposition. We will postpone examining some of Java's details while we discuss programming in general. Consider the following program, which draws two text boxes on the console: 1 2 3 4 5 6 7 8 9 10 11 12 13  public class DrawBoxes { public static void main(String[] args) { System.out.println("+------+"); System.out.println("| |"); System.out.println("| |"); System.out.println("+------+"); System.out.println(); System.out.println("+------+"); System.out.println("| |"); System.out.println("| |"); System.out.println("+------+"); } }  The program works correctly, but the four lines used to draw the box appear twice. This redundancy is undesirable for several reasons. For example, you might wish to change the appearance of the boxes, in which case you'll have to make all of the edits twice. Also, you might wish to draw additional boxes, which would require you to type additional copies of (or copy and paste) the redundant lines. A preferable program would include a Java command that specifies how to draw the box and then executes that command twice. Java doesn't have a "draw a box" command, but you can create one. Such a named command is called a static method.  Static Method A block of Java statements that is given a name. Static methods are units of procedural decomposition. We typically break a class into several static methods, each of which solves some piece of the overall problem. For example, here is a static method to draw a box: public static void drawBox() { System.out.println("+------+"); System.out.println("| |"); System.out.println("| |"); System.out.println("+------+"); }  You have already seen a static method called main in earlier programs. Recall that the main method has the following form: public static void main(String[] args) { <statement>; <statement>; ... <statement>; }  The static methods you'll write have a similar structure: public static void <name>() { <statement>; <statement>; ... <statement>; }  The first line is known as the method header. You don't yet need to fully understand what each part of this header means in Java; for now, just remember that you'll need to write public static void, followed by the name you wish to give the method, followed by a set of parentheses. Briefly,  here is what the words in the header mean: The keyword public indicates that this method is available to be used by all parts of your program. All methods you write will be public. The keyword static indicates that this is a static (procedural-style, not object-oriented) method. For now, all methods you write will be static, until you learn about defining objects in Chapter 8. The keyword void indicates that this method executes statements but does not produce any value. (Other methods you'll see later compute and return values.) <name> (e.g., drawBox) is the name of the method. The empty parentheses specify a list (in this case, an empty list) of values that are sent to your method as input; such values are called parameters and will not be included in your methods until Chapter 3. Including the keyword static for each method you define may seem cumbersome. Other Java textbooks often do not discuss static methods as early as we do here; instead, they show other techniques for decomposing problems. But even though static methods require a bit of work to create, they are powerful and useful tools for improving basic Java programs. After the header in our sample method, a series of println statements makes up the body of this static method. As in the main method, the statements of this method are executed in order from first to last. By defining the method drawBox, you have given a simple name to this sequence of println statements. It's like saying to the Java compiler, "Whenever I tell you to 'drawBox,' I really mean that you should execute the println statements in the drawBox method." But the command won't actually be executed unless our main method explicitly says that it wants to do so. The act of executing a static method is called a method call.  Method Call  A command to execute another method, which causes all of the statements inside that method to be executed. To execute the drawBox command, include this line in your program's main method: drawBox();  Since we want to execute the drawBox command twice (to draw two boxes), the main method should contain two calls to the drawBox method. The following program uses the drawBox method to produce the same output as the original DrawBoxes program: 1 2 3 4 5 6 7 8 9 10 11 12 13 14  public class DrawBoxes2 { public static void main(String[] args) { drawBox(); System.out.println(); drawBox(); } public static void drawBox() { System.out.println("+------+"); System.out.println("| |"); System.out.println("| |"); System.out.println("+------+"); } }  Flow of Control The most confusing thing about static methods is that programs with static methods do not execute sequentially from top to bottom. Rather, each time the program encounters a static method call, the execution of the program "jumps" to that static method, executes each statement in that method in order, and then "jumps" back to the point where the call began and resumes executing. The order in which the statements of a program are executed is called the program's flow of control.  Flow of Control The order in which the statements of a Java program are executed. Let's look at the control flow of the DrawBoxes2 program shown previously. It has two methods. The first method is the familiar main method, and the second is drawBox. As in any Java program, execution starts with the main method: public static void main(String[] args) { drawBox(); System.out.println(); drawBox(); }  In a sense, the execution of this program is sequential: Each statement listed in the main method is executed in turn, from first to last. But this main method includes two different calls on the drawBox method. This program will do three different things: execute drawBox, execute a println, then execute drawBox again. The diagram below indicates the flow of control produced by this program.  Following the diagram, you can see that nine println statements are executed. First you transfer control to the drawBox method and execute its four statements. Then you return to main and execute its println statement. Then you transfer control a second time to drawBox and once again execute its four statements. Making these method calls is almost like copying and pasting the code of the method into the main method. As a result, this program has the exact same behavior as the nine-line main method of the DrawBoxes program:  This version is simpler in terms of its flow of control, but the first version avoids the redundancy of having the same println statements appear multiple times. It also gives a better sense of the structure of the solution. In the original version, it is clear that there is a subtask called drawBox that is being performed twice. Also, while the last version of the main method contains fewer lines              

Posted by: shirleypollande0206417.blogspot.com

Source: https://b-ok.cc/book/3600850/102d23