introduction.to.java.programming.8th.edition

756

Upload: nyversity

Post on 19-Jun-2015

360 views

Category:

Education


13 download

TRANSCRIPT

  • 1. JAVAINTRODUCTION TO TMPROGRAMMING

2. This page intentionally left blank 3. INTRODUCTION TO JAVAPROGRAMMINGBRIEF VERSIONEighth EditionY. Daniel LiangArmstrong Atlantic State UniversityTMPrentice HallBoston Columbus Indianapolis New York San Francisco Upper Saddle RiverAmsterdam Cape Town Dubai London Madrid Milan Munich Paris Montreal TorontoDelhi Mexico City Sao Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo 4. Vice President and Editorial Director, ECS: Marcia J. HortonEditor in Chief, Computer Science: Michael HirschExecutive Editor: Tracy DunkelbergerAssistant Editor: Melinda HaggertyEditorial Assistant: Allison MichaelVice President, Production: Vince OBrienSenior Managing Editor: Scott DisannoProduction Editor: Irwin ZuckerSenior Operations Specialist: Alan FischerMarketing Manager: Erin DavisMarketing Assistant: Mack PattersonArt Director: Kenny BeckCover Image: Male Ruby-throated Hummingbird / Steve Byland / Shutterstock;Hummingbird, Nazca Lines / Gary Yim / ShutterstockArt Editor: Greg DullesMedia Editor: Daniel SandinCopyright 2011, 2009, 2007, 2004 by Pearson Higher Education. Upper Saddle River, New Jersey, 07458.All right reserved. Manufactured in the United States of America. This publication is protected by Copyright andpermission should be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval sys-tem,or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. Toobtain permission(s) to use materials from this work, please submit a written request to Pearson Higher Education,Permissions Department, 1 Lake Street, Upper Saddle River, NJ 07458.The author and publisher of this book have used their best efforts in preparing this book. These efforts include thedevelopment, research, and testing of the theories and programs to determine their effectiveness. The author andpublisher make no warranty of any kind, expressed or implied, with regard to these programs or the documentationcontained in this book. The author and publisher shall not be liable in any event for incidental or consequentialdamages in connection with, or arising out of, the furnishing, performance, or use of these programs.Library of Congress Cataloging-in-Publication Data on file.10 9 8 7 6 5 4 3 2 1ISBN-13: 978-0-13-213079-0ISBN-10: 0-13-213079-3 5. This book is dedicated to Dr. S. K. Dhall andDr. S. Lakshmivarahan of the University of Oklahoma,who inspired me in teaching and research. Thank you for beingmy mentors and advisors.To Samantha, Michael, and Michelle 6. This page intentionally left blank 7. PREFACEviiThis book is a brief version of Introduction to Java Programming, Comprehensive Version,8E. This version is designed for an introductory programming course, commonly known asCS1. This version contains the first twenty chapters in the comprehensive version.This book uses the fundamentals-first approach and teaches programming concepts andtechniques in a problem-driven way.The fundamentals-first approach introduces basic programming concepts and techniquesbefore objects and classes. My own experience, confirmed by the experiences of many col-leagues,demonstrates that new programmers in order to succeed must learn basic logic andfundamental programming techniques such as loops and stepwise refinement. The funda-mentalconcepts and techniques of loops, methods, and arrays are the foundation for pro-gramming.Building the foundation prepares students to learn object-oriented programming,GUI, database, and Web programming.Problem-driven means focused on problem-solving rather than syntax. We make introduc-toryprogramming interesting by using interesting problems. The central thread of this bookis on solving problems. Appropriate syntax and library are introduced to support the writingof a program for solving the problems. To support teaching programming in a problem-drivenway, the book provides a wide variety of problems at various levels of difficulty tomotivate students. In order to appeal to students in all majors, the problems cover many appli-cationareas in math, science, business, financials, gaming, animation, and multimedia.Whats New in This Edition?This edition substantially improves Introduction to Java Programming, Seventh Edition. Themajor improvements are as follows: This edition is completely revised in every detail to enhance clarity, presentation, content,examples, and exercises. In the examples and exercises, which are provided to motivate and stimulate student inter-estin programming, one-fifth of the problems are new. In the previous edition, console input was covered at the end of Chapter 2. The new edi-tionintroduces console input early in Chapter 2 so that students can write interactive pro-gramsearly. The hand trace box is added for many programs in early chapters to help noive studentsto read and trace programs. Single-dimensional arrays and multidimensional arrays are covered in two chapters togive instructors the flexibility to cover multidimensional arrays later. The case study for the Sudoku problem has been moved to the Companion Website. Amore pedagogically effective simple version of the Sudoku problem is presented instead. The design of the API for Java GUI programming is an excellent example of how theobject-oriented principle is applied. Students learn better with concrete and visual exam-ples.So basic GUI now precedes the introduction of abstract classes and interfaces. Theinstructor, however, can still choose to cover abstract classes and interfaces before GUI.brief versioncomprehensive versionfundamentals-firstproblem-drivencomplete revisionnew problemsearly console inputhand trace boxmultidimensional arraysSudoku problem simplifiedbasic GUI earlier 8. viii Preface Exception handling is covered before abstract classes and interfaces. The instructor canstill choose to cover exception handling later. Chapter 12, Object-Oriented Design and Patterns, in the previous edition has beenreplaced by spreading the design guidelines and patterns into several chapters so that thesetopics can be covered in appropriate context.Learning StrategiesA programming course is quite different from other courses. In a programming course, youlearn from examples, from practice, and from mistakes. You need to devote a lot of time towriting programs, testing them, and fixing errors.For first-time programmers, learning Java is like learning any high-level programming lan-guage.The fundamental point is to develop the critical skills of formulating programmaticsolutions for real problems and translating them into programs using selection statements,loops, methods, and arrays.Once you acquire the basic skills of writing programs using loops, methods, and arrays,you can begin to learn how to develop large programs and GUI programs using the object-orientedapproach.When you know how to program and you understand the concept of object-oriented pro-gramming,learning Java becomes a matter of learning the Java API. The Java API establish-esa framework for programmers to develop applications using Java. You have to use theclasses and interfaces in the API and follow their conventions and rules to create applications.The best way to learn the Java API is to imitate examples and do exercises.Pedagogical FeaturesThe book uses the following elements to get the most from the material: Objectives list what students should have learned from the chapter. This will help themdetermine whether they have met the objectives after completing the chapter. Introduction opens the discussion with representative problems to give the reader anoverview of what to expect from the chapter. Problems carefully chosen and presented in an easy-to-follow style, teach problem solv-ingand programming concepts. The book uses many small, simple, and stimulating exam-plesto demonstrate important ideas. Chapter Summary reviews the important subjects that students should understand andremember. It helps them reinforce the key concepts they have learned in the chapter. Review Questions are grouped by sections to help students track their progress and eval-uatetheir learning. Programming Exercises are grouped by sections to provide students with opportunitiesto apply on their own the new skills they have learned. The level of difficulty is rated aseasy (no asterisk), moderate (*), hard (**), or challenging (***). The trick of learningprogramming is practice, practice, and practice. To that end, the book provides a greatmany exercises. LiveLab is a programming course assessment and management system. Students cansubmit programs/quizzes online. The system automatically grades the programs/quizzesand gives students instant feedback. Notes, Tips, and Cautions are inserted throughout the text to offer valuable advice andinsight on important aspects of program development.exception handling earlierdesign guidelineslearn from mistakesprogrammatic solutionobject-oriented programmingJava API 9. Preface ixNoteProvides additional information on the subject and reinforces important concepts.TipTeaches good programming style and practice.CautionHelps students steer away from the pitfalls of programming errors.Design GuideProvides the guidelines for designing programs.Flexible Chapter OrderingsThe book is designed to provide flexible chapter orderings to enable GUI, exception handling,and recursion to be covered earlier or later. The diagram shows the chapter dependencies.Part I: Fundamentals ofProgrammingChapter 1 Introduction toComputers, Programs, andJavaChapter 2 ElementaryProgrammingChapter 3 SelectionsChapter 4 LoopsChapter 5 MethodsChapter 7 MultidimensionalArraysChapter 20 RecursionChapter 8 Objects and ClassesChapter 9 Strings and Text I/OChapter 10 Thinking in ObjectsChapter 11 Inheritance andPolymorphismChapter 13 ExceptionHandlingChapter 14 Abstract Classesand InterfacesChapter 19 Binary I/OChapter 6 Single-DimensionalArraysPart II: Object-OrientedProgrammingPart III: GUI ProgrammingChapter 12 GUI BasicsChapter 15 GraphicsChapter 16 Event-DrivenProgrammingChapter 17 Creating GraphicalUser InterfacesChapter 18 Applets andMultimediaOrganization of the BookThe chapters in the brief version can be grouped into three parts that, taken together, form asolid introduction to Java programming. Because knowledge is cumulative, the early chaptersprovide the conceptual basis for understanding programming and guide students through 10. x Prefacesimple examples and exercises; subsequent chapters progressively present Java programmingin detail, culminating with the development of comprehensive Java applications.Part I: Fundamentals of Programming (Chapters 17, 20)The first part of the book is a stepping stone, preparing you to embark on the journey of learn-ingJava. You will begin to know Java (Chapter 1), and will learn fundamental programmingtechniques with primitive data types, variables, constants, expressions, and operators (Chapter2), control statements (Chapters 34), methods (Chapter 5), and arrays (Chapters 67). AfterChapter 6, you may jump to Chapter 20 to learn how to write recursive methods for solvinginherently recursive problems.Part II: Object-Oriented Programming (Chapters 811, 1314, 19)This part introduces object-oriented programming. Java is an object-oriented programminglanguage that uses abstraction, encapsulation, inheritance, and polymorphism to provide greatflexibility, modularity, and reusability in developing software. You will learn programmingwith objects and classes (Chapters 810), class inheritance (Chapter 11), polymorphism(Chapter 11), exception handling (Chapter 13), abstract classes (Chapter 14), and interfaces(Chapter 14). Processing strings will be introduced in Chapter 9 along with text I/O. BinaryI/O is introduced in Chapter 19.Part III: GUI Programming (Chapters 12, 1518)This part introduces elementary Java GUI programming in Chapters 12 and 1518. Majortopics include GUI basics (Chapter 12), drawing shapes (Chapter 15), event-driven program-ming(Chapter 16), creating graphical user interfaces (Chapter 17), and writing applets(Chapter 18). You will learn the architecture of Java GUI programming and use the GUI com-ponentsto develop applications and applets from these elementary GUI chapters.Java Development ToolsYou can use a text editor, such as the Windows Notepad or WordPad, to create Java programsand to compile and run the programs from the command window. You can also use a Javadevelopment tool, such as TextPad, NetBeans, or Eclipse. These tools support an integrateddevelopment environment (IDE) for rapidly developing Java programs. Editing, compiling,building, executing, and debugging programs are integrated in one graphical user interface.Using these tools effectively can greatly increase your programming productivity. TextPad isa primitive IDE tool. NetBeans and Eclipse are more sophisticated, but they are easy to use ifyou follow the tutorials. Tutorials on TextPad, NetBeans, and Eclipse can be found in the sup-plementson the Companion Website.LiveLabThis book is accompanied by an improved faster Web-based course assessment and manage-mentsystem. The system has three main components: Automatic Grading System: It can automatically grade exercises from the text or createdby instructors. Quiz Creation/Submission/Grading System: It enables instructors to create/modifyquizzes that students can take and be graded upon automatically. Tracking grades, attendance, etc: The system enables the students to track grades andinstructors to view the grades of all students, and to track attendance.IDE tutorials 11. Preface xiThe main features of the Automatic Grading System are as follows: Allows students to compile, run and submit exercises. (The system checks whether theirprogram runs correctlystudents can continue to run and submit the program before thedue date.) Allows instructors to review submissions; run programs with instructor test cases; correctthem; and provide feedback to students. Allows instructors to create/modify their own exercises, create public and secret test cases,assign exercises, and set due dates for the whole class or for individuals. All the exercises in the text can be assigned to students. Additionally, LiveLab providesextra exercises that are not printed in the text. Allows instructors to sort and filter all exercises and check grades (by time frame, student,and/or exercise). Allows instructors to delete students from the system. Allows students and instructors to track grades on exercises.The main features of the Quiz System are as follows: Allows instructors to create/modify quizzes from test bank or a text file or to create com-pletenew tests online. Allows instructors to assign the quizzes to students and set a due date and test time limitfor the whole class or for individuals. Allows students and instructors to review submitted quizzes. Allows students and instructors to track grades on quizzes.Video Notes are Pearsons new visual tool designed for teaching students key programming con-ceptsand techniques. These short step-by-step videos demonstrate how to solve problems fromdesign through coding. Video Notes allows for self-paced instruction with easy navigation includ-ingthe ability to select, play, rewind, fast-forward, and stop within each Video Note exercise.Video Note margin icons in your textbook let you know what a Video Notes video is avail-ablefor a particular concept or homework problem.Video Notes are free with the purchase of a new textbook. To purchase access to VideoNotes, please go to www.pearsonhighered.com/liang.Student Resource MaterialsThe student resources can be accessed through the Publishers Web site(www.pearsonhighered.com/liang) and the Companion Web site (www.cs.armstrong.edu/liang/intro8e).The resources include: Answers to review questions Solutions to even-numbered programming exercises Source code for book examples Interactive self-test (organized by chapter sections) LiveLab Resource links Errata 12. xii Preface Video Notes Web ChaptersTo access the Video Notes and Web Chapters, students must log onto www.pearsonhighered.com/liangand use the access card located in the front of the book to register and access the material. If there isno access card in the front of this textbook, students can purchase access by visitingwww.pearsonhighered.com/liang and selecting purchase access to premium content.Additional SupplementsThe text covers the essential subjects. The supplements extend the text to introduce addition-altopics that might be of interest to readers. The supplements listed in this table are availablefrom the Companion Web site.Supplements on the Companion Web sitePart I General SupplementsA GlossaryB Installing and Configuring JDKC Compiling and Running Java from theCommand WindowD Java Coding Style GuidelinesE Creating Desktop Shortcuts for JavaApplications on WindowsF Using Packages to Organize the Classesin the TextPart II IDE SupplementsA TextPad TutorialB NetBeans Tutorial | One Page StartupInstructionC Learning Java Effectively withNetBeansD Eclipse Tutorial | One Page StartupInstructionE Learning Java Effectively with EclipsePart III Java SupplementsA Java CharacteristicsB Discussion on Operator and OperandEvaluationsC The & and | OperatorsD Bitwise OperationsE Statement Labels with break and continueF Enumerated TypesG PackagesH Regular ExpressionsI Formatted StringsJ The Methods in the Object ClassK Hiding Data Fields and Static MethodsL Initialization BlocksM Extended Discussions on OverridingMethodsN Design PatternsO Text I/O Prior to JDK 1.5 (Reader andWriter Classes)P AssertionsQ Packaging and Deploying Java ProjectsR Java Web StartS GridBagLayout | OverlayLayout |SpringLayoutT Networking Using Datagram ProtocolU Creating Internal FramesV Pluggable Look and FeelW UML Graphical NotationsX Testing Classes Using JUnitY JNIZ The StringTokenizer ClassPart IV Database SupplementsA SQL Statements for Creating andInitializing Tables Used in the BookB MySQL TutorialC Oracle TutorialD Microsoft Access TutorialE Introduction to Database SystemsF Relational Database ConceptG Database DesignH SQL BasicsI Advanced SQLPart V Web Programming SupplementsA HTML and XHTML TutorialB CSS TutorialC XMLD Java and XMLE Tomcat TutorialF More Examples on JSF and Visual WebDevelopment 13. Preface xiiiInstructor Resource MaterialsThe instructor resources can be accessed through the Publishers Web site(www.pearsonhighered.com/liang) and the Companion Web site (www.cs.armstrong.edu/liang/intro8e).For username and password information to the Liang 8e site, please contact your PearsonRepresentative.The resources include: PowerPoint lecture slides with source code and run program capacity Instructor solutions manual Computerized test generator Sample exams using multiple choice and short answer questions, write and trace pro-grams,and correcting programming errors. LiveLab Errata Video Notes Web ChaptersTo access the Video Notes and Web Chapters, instructors must log onto www.pearsonhighered.com/liangand register.AcknowledgmentsI would like to thank Armstrong Atlantic State University for enabling me to teach what Iwrite and for supporting me in writing what I teach. Teaching is the source of inspiration forcontinuing to improve the book. I am grateful to the instructors and students who have offeredcomments, suggestions, bug reports, and praise.This book has been greatly enhanced thanks to outstanding reviews for this and previouseditions. The reviewers are: Elizabeth Adams (James Madison University), Syed Ahmed(North Georgia College and State University), Omar Aldawud (Illinois Institute ofTechnology), Yang Ang (University of Wollongong, Australia), Kevin Bierre (RochesterInstitute of Technology), David Champion (DeVry Institute), James Chegwidden (TarrantCounty College), Anup Dargar (University of North Dakota), Charles Dierbach (TowsonUniversity), Frank Ducrest (University of Louisiana at Lafayette), Erica Eddy (University ofWisconsin at Parkside), Deena Engel (New York University), Henry A Etlinger (RochesterInstitute of Technology), James Ten Eyck (Marist College), Olac Fuentes (University ofTexas at El Paso), Harold Grossman (Clemson University), Barbara Guillot (Louisiana StateUniversity), Ron Hofman (Red River College, Canada), Stephen Hughes (Roanoke College),Vladan Jovanovic (Georgia Southern University), Edwin Kay (Lehigh University), LarryKing (University of Texas at Dallas), Nana Kofi (Langara College, Canada), GeorgeKoutsogiannakis (Illinois Institute of Technology), Roger Kraft (Purdue University atCalumet), Hong Lin (DeVry Institute), Dan Lipsa (Armstrong Atlantic State University),James Madison (Rensselaer Polytechnic Institute), Frank Malinowski (Darton College), TimMargush (University of Akron), Debbie Masada (Sun Microsystems), Blayne Mayfield(Oklahoma State University), John McGrath (J.P. McGrath Consulting), Shyamal Mitra(University of Texas at Austin), Michel Mitri (James Madison University), Kenrick Mock(University of Alaska Anchorage), Jun Ni (University of Iowa), Benjamin Nystuen(University of Colorado at Colorado Springs), Maureen Opkins (CA State University, LongBeach), Gavin Osborne (University of Saskatchewan), Kevin Parker (Idaho StateUniversity), Dale Parson (Kutztown University), Mark Pendergast (Florida Gulf Coast 14. xiv PrefaceUniversity), Richard Povinelli (Marquette University), Roger Priebe (University of Texas atAustin), Mary Ann Pumphrey (De Anza Junior College), Pat Roth (Southern PolytechnicState University), Ronald F. Taylor (Wright State University), Carolyn Schauble (ColoradoState University), David Scuse (University of Manitoba), Ashraf Shirani (San Jose StateUniversity), Daniel Spiegel (Kutztown University), Amr Sabry (Indiana University), LixinTao (Pace University), Russ Tront (Simon Fraser University), Deborah Trytten (Universityof Oklahoma), Kent Vidrine (George Washington University), and Bahram Zartoshty(California State University at Northridge).It is a great pleasure, honor, and privilege to work with Pearson. I would like to thank TracyDunkelberger and her colleagues Marcia Horton, Margaret Waples, Erin Davis, Michael Hirsh,Matt Goldstein, Jake Warde, Melinda Haggerty, Allison Michael, Scott Disanno, Irwin Zucker,and their colleagues for organizing, producing, and promoting this project, and Robert Lentzfor copy editing.As always, I am indebted to my wife, Samantha, for her love, support, and encouragement.Y. Daniel [email protected]/liangwww.pearsonhighered.com/liang 15. BRIEF CONTENTS1 Introduction to Computers, Programs,and Java 12 Elementary Programming 233 Selections 714 Loops 1155 Methods 1556 Single-Dimensional Arrays 1977 Multidimensional Arrays 2358 Objects and Classes 2639 Strings and Text I/O 30110 Thinking in Objects 34311 Inheritance and Polymorphism 37312 GUI Basics 40513 Exception Handling 43114 Abstract Classes and Interfaces 45715 Graphics 49716 Event-Driven Programming 53317 Creating Graphical User Interfaces 57118 Applets and Multimedia 61319 Binary I/O 64920 Recursion 677APPENDIXESA Java Keywords 707B The ASCII Character Set 710C Operator Precedence Chart 712D Java Modifiers 714E Special Floating-Point Values 716F Number Systems 717INDEX 721xv 16. CONTENTSChapter 1 Introduction to Computers, Programs,and Java 11.1 Introduction 21.2 What Is a Computer? 21.3 Programs 51.4 Operating Systems 71.5 Java, World Wide Web, and Beyond 81.6 The Java Language Specification, API, JDK, and IDE 101.7 A Simple Java Program 111.8 Creating, Compiling, and Executing a Java Program 131.9 (GUI) Displaying Text in a Message Dialog Box 16Chapter 2 Elementary Programming 232.1 Introduction 242.2 Writing Simple Programs 242.3 Reading Input from the Console 262.4 Identifiers 292.5 Variables 292.6 Assignment Statements and Assignment Expressions 302.7 Named Constants 312.8 Numeric Data Types and Operations 322.9 Problem: Displaying the Current Time 372.10 Shorthand Operators 392.11 Numeric Type Conversions 412.12 Problem: Computing Loan Payments 432.13 Character Data Type and Operations 442.14 Problem: Counting Monetary Units 472.15 The String Type 502.16 Programming Style and Documentation 512.17 Programming Errors 532.18 (GUI) Getting Input from Input Dialogs 55Chapter 3 Selections 713.1 Introduction 723.2 boolean Data Type 723.3 Problem: A Simple Math Learning Tool 733.4 if Statements 74xvi 17. Contents xvii3.5 Problem: Guessing Birthdays 753.6 Two-Way if Statements 793.7 Nested if Statements 803.8 Common Errors in Selection Statements 813.9 Problem: An Improved Math Learning Tool 823.10 Problem: Computing Body Mass Index 843.11 Problem: Computing Taxes 853.12 Logical Operators 883.13 Problem: Determining Leap Year 903.14 Problem: Lottery 913.15 switch Statements 933.16 Conditional Expressions 953.17 Formatting Console Output 953.18 Operator Precedence and Associativity 973.19 (GUI) Confirmation Dialogs 98Chapter 4 Loops 1154.1 Introduction 1164.2 The while Loop 1164.3 The do-while Loop 1244.4 The for Loop 1264.5 Which Loop to Use? 1284.6 Nested Loops 1294.7 Minimizing Numeric Errors 1304.8 Case Studies 1314.9 Keywords break and continue 1354.10 (GUI) Controlling a Loop with a Confirmation Dialog 139Chapter 5 Methods 1555.1 Introduction 1565.2 Defining a Method 1565.3 Calling a Method 1585.4 void Method Example 1605.5 Passing Parameters by Values 1625.6 Modularizing Code 1655.7 Problem: Converting Decimals to Hexadecimals 1675.8 Overloading Methods 1685.9 The Scope of Variables 1715.10 The Math Class 1725.11 Case Study: Generating Random Characters 1755.12 Method Abstraction and Stepwise Refinement 176 18. xviii ContentsChapter 6 Single-Dimensional Arrays 1976.1 Introduction 1986.2 Array Basics 1986.3 Problem: Lotto Numbers 2046.4 Problem: Deck of Cards 2066.5 Copying Arrays 2086.6 Passing Arrays to Methods 2096.7 Returning an Array from a Method 2126.8 Variable-Length Argument Lists 2156.9 Searching Arrays 2166.10 Sorting Arrays 2196.11 The Arrays Class 223Chapter 7 Multidimensional Arrays 2357.1 Introduction 2367.2 Two-Dimensional Array Basics 2367.3 Processing Two-Dimensional Arrays 2387.4 Passing Two-Dimensional Arrays to Methods 2407.5 Problem: Grading a Multiple-Choice Test 2417.6 Problem: Finding a Closest Pair 2427.7 Problem: Sudoku 2447.8 Multidimensional Arrays 248Chapter 8 Objects and Classes 2638.1 Introduction 2648.2 Defining Classes for Objects 2648.3 Example: Defining Classes and Creating Objects 2668.4 Constructing Objects Using Constructors 2708.5 Accessing Objects via Reference Variables 2708.6 Using Classes from the Java Library 2748.7 Static Variables, Constants, and Methods 2788.8 Visibility Modifiers 2828.9 Data Field Encapsulation 2838.10 Passing Objects to Methods 2868.11 Array of Objects 287Chapter 9 Strings and Text I/O 3019.1 Introduction 3029.2 The String Class 3029.3 The Character Class 313 19. 9.4 The StringBuilder/StringBuffer Class 3159.5 Command-Line Arguments 3209.6 The File Class 3229.7 File Input and Output 3259.8 (GUI) File Dialogs 329Chapter 10 Thinking in Objects 34310.1 Introduction 34410.2 Immutable Objects and Classes 34410.3 The Scope of Variables 34510.4 The this Reference 34610.5 Class Abstraction and Encapsulation 34710.6 Object-Oriented Thinking 35110.7 Object Composition 35310.8 Designing the Course Class 35510.9 Designing a Class for Stacks 35710.10 Designing the GuessDate Class 35910.11 Class Design Guidelines 362Chapter 11 Inheritance and Polymorphism 37311.1 Introduction 37411.2 Superclasses and Subclasses 37411.3 Using the super Keyword 38011.4 Overriding Methods 38211.5 Overriding vs. Overloading 38311.6 The Object Class and Its toString() Method 38411.7 Polymorphism 38411.8 Dynamic Binding 38511.9 Casting Objects and the instanceof Operator 38711.10 The Objects equals() Method 38911.11 The ArrayList Class 39011.12 A Custom Stack Class 39311.13 The protected Data and Methods 39411.14 Preventing Extending and Overriding 396Chapter 12 GUI Basics 40512.1 Introduction 40612.2 Swing vs. AWT 40612.3 The Java GUI API 40612.4 Frames 40812.5 Layout Managers 411Contents xix 20. 12.6 Using Panels as Subcontainers 41712.7 The Color Class 41912.8 The Font Class 41912.9 Common Features of Swing GUI Components 42012.10 Image Icons 422Chapter 13 Exception Handling 43113.1 Introduction 43213.2 Exception-Handling Overview 43213.3 Exception-Handling Advantages 43413.4 Exception Types 43713.5 More on Exception Handling 43913.6 The finally Clause 44513.7 When to Use Exceptions 44713.8 Rethrowing Exceptions 44713.9 Chained Exceptions 44713.10 Creating Custom Exception Classes 448Chapter 14 Abstract Classes and Interfaces 45714.1 Introduction 45814.2 Abstract Classes 45814.3 Example: Calendar and GregorianCalendar 46214.4 Interfaces 46514.5 Example: The Comparable Interface 46714.6 Example: The ActionListener Interface 46914.7 Example: The Cloneable Interface 47114.8 Interfaces vs. Abstract Classes 47314.9 Processing Primitive Data Type Values as Objects 47614.10 Sorting an Array of Objects 47914.11 Automatic Conversion between Primitive Types andWrapper Class Types 48114.12 The BigInteger and BigDecimal Classes 48114.13 Case Study: The Rational Class 482Chapter 15 Graphics 49715.1 Introduction 49815.2 Graphical Coordinate Systems 49815.3 The Graphics Class 49915.4 Drawing Strings, Lines, Rectangles, and Ovals 50115.5 Case Study: The FigurePanel Class 50215.6 Drawing Arcs 506xx Contents 21. Contents xxi15.7 Drawing Polygons and Polylines 50715.8 Centering a String Using the FontMetrics Class 51015.9 Case Study: The MessagePanel Class 51215.10 Case Study: The StillClock Class 51615.11 Displaying Images 52015.12 Case Study: The ImageViewer Class 522Chapter 16 Event-Driven Programming 53316.1 Introduction 53416.2 Event and Event Source 53416.3 Listeners, Registrations, and Handling Events 53516.4 Inner Classes 54116.5 Anonymous Class Listeners 54216.6 Alternative Ways of Defining Listener Classes 54416.7 Problem: Loan Calculator 54716.8 Window Events 54916.9 Listener Interface Adapters 55116.10 Mouse Events 55216.11 Key Events 55516.12 Animation Using the Timer Class 557Chapter 17 Creating Graphical User Interfaces 57117.1 Introduction 57217.2 Buttons 57217.3 Check Boxes 57817.4 Radio Buttons 58117.5 Labels 58317.6 Text Fields 58417.7 Text Areas 58617.8 Combo Boxes 59017.9 Lists 59317.10 Scroll Bars 59617.11 Sliders 59917.12 Creating Multiple Windows 602Chapter 18 Applets and Multimedia 61318.1 Introduction 61418.2 Developing Applets 61418.3 The HTML File and the Tag 61518.4 Applet Security Restrictions 61818.5 Enabling Applets to Run as Applications 618 22. 18.6 Applet Life-Cycle Methods 62018.7 Passing Strings to Applets 62018.8 Case Study: Bouncing Ball 62418.9 Case Study: TicTacToe 62818.10 Locating Resources Using the URL Class 63218.11 Playing Audio in Any Java Program 63318.12 Case Study: Multimedia Animations 634Chapter 19 Binary I/O 64919.1 Introduction 65019.2 How is I/O Handled in Java? 65019.3 Text I/O vs. Binary I/O 65019.4 Binary I/O Classes 65219.5 Problem: Copying Files 66019.6 Object I/O 66219.7 Random-Access Files 666Chapter 20 Recursion 67720.1 Introduction 67820.2 Problem: Computing Factorials 67820.3 Problem: Computing Fibonacci Numbers 68120.4 Problem Solving Using Recursion 68320.5 Recursive Helper Methods 68420.6 Problem: Finding the Directory Size 68720.7 Problem: Towers of Hanoi 68820.8 Problem: Fractals 69220.9 Problem: Eight Queens 69520.10 Recursion vs. Iteration 69720.11 Tail Recursion 697APPENDIXESAppendix A Java Keywords 707Appendix B The ASCII Character Set 710Appendix C Operator Precedence Chart 712Appendix D Java Modifiers 714Appendix E Special Floating-Point Values 716Appendix F Number Systems 717INDEX 721xxii Contents 23. JAVAINTRODUCTION TO TMPROGRAMMING 24. This page intentionally left blank 25. CHAPTER 1INTRODUCTION TO COMPUTERS,PROGRAMS, AND JAVAObjectives To review computer basics, programs, and operating systems (1.21.4). To explore the relationship between Java and the World Wide Web (1.5). To distinguish the terms API, IDE, and JDK (1.6). To write a simple Java program (1.7). To display output on the console (1.7). To explain the basic syntax of a Java program (1.7). To create, compile, and run Java programs (1.8). (GUI) To display output using the JOptionPaneoutput dialog boxes (1.9). 26. 2 Chapter 1 Introduction to Computers, Programs, and Java1.1 IntroductionYou use word processors to write documents, Web browsers to explore the Internet, and emailprograms to send email. These are all examples of software that runs on computers. Softwareis developed using programming languages. There are many programming languagessowhy Java? The answer is that Java enables users to develop and deploy applications on theInternet for servers, desktop computers, and small hand-held devices. The future of comput-ingis being profoundly influenced by the Internet, and Java promises to remain a big part ofthat future. Java is the Internet programming language.You are about to begin an exciting journey, learning a powerful programming language. Atthe outset, it is helpful to review computer basics, programs, and operating systems and tobecome familiar with number systems. If you are already familiar with such terms as CPU,memory, disks, operating systems, and programming languages, you may skip the review in1.21.4.1.2 What Is a Computer?A computer is an electronic device that stores and processes data. It includes both hardwareand software. In general, hardware comprises the visible, physical elements of the computer,and software provides the invisible instructions that control the hardware and make it performspecific tasks. Writing instructions for computers to perform is called computer program-ming.Knowing computer hardware isnt essential to your learning a programming language,but it does help you understand better the effect of the program instructions. This sectionintroduces computer hardware components and their functions.A computer consists of the following major hardware components (Figure 1.1): Central processing unit (CPU) Memory (main memory) Storage devices (e.g., disks, CDs, tapes) Input and output devices (e.g., monitors, keyboards, mice, printers) Communication devices (e.g., modems and network interface cards (NICs))The components are connected through a subsystem called a bus that transfers data orpower between them.1.2.1 Central Processing UnitThe central processing unit (CPU) is the computers brain. It retrieves instructions frommemory and executes them. The CPU usually has two components: a control unit and anarithmetic/logic unit. The control unit controls and coordinates the actions of the otherwhy Java?hardwaresoftwarebusCPUMemorye.g., Disk, CD,and Tapee.g., Modemand NICe.g., Keyboard,Mousee.g., Monitor,PrinterCPUBusStorageDevicesCommunicationDevicesInputDevicesOutputDevicesFIGURE 1.1 A computer consists of CPU, memory, storage devices, input devices, outputdevices, and communication devices. 27. 1.2 What Is a Computer? 3components. The arithmetic/logic unit performs numeric operations (addition, subtraction,multiplication, division) and logical operations (comparisons).Todays CPU is built on a small silicon semiconductor chip having millions of transistors.Every computer has an internal clock, which emits electronic pulses at a constant rate. Thesepulses are used to control and synchronize the pace of operations. The higher the clock speed,the more instructions are executed in a given period of time. The unit of measurement of clockspeed is the hertz (Hz), with 1 hertz equaling 1 pulse per second. The clock speed of a com-puteris usually stated in megahertz (MHz) (1 MHz is 1 million Hz). CPU speed has beenimproved continuously. Intels Pentium 3 Processor runs at about 500 megahertz and Pentium4 Processor at about 3 gigahertz (GHz) (1 GHz is 1000 MHz).1.2.2 MemoryTo store and process information, computers use off and on electrical states, referred to byconvention as 0 and 1. These 0s and 1s are interpreted as digits in the binary number systemand called bits (binary digits). Data of various kinds, such as numbers, characters, and strings,are encoded as series of bits. Data and program instructions for the CPU to execute are storedas groups of bits, or bytes, each byte composed of eight bits, in a computers memory. Amemory unit is an ordered sequence of bytes, as shown in Figure 1.2.Memory address Memory contentThe programmer need not be concerned about the encoding and decoding of data, whichthe system performs automatically, based on the encoding scheme. In the popular ASCIIencoding scheme, for example, character 'J' is represented by 01001010 in one byte.A byte is the minimum storage unit. A small number such as 3 can be stored in a singlebyte. To store a number that cannot fit into a single byte, the computer uses several adjacentbytes. No two data items can share or split the same byte.A memory byte is never empty, but its initial content may be meaningless to your program.The current content of a memory byte is lost whenever new information is placed in it.A program and its data must be brought to memory before they can be executed.Every byte has a unique address. The address is used to locate the byte for storing andretrieving data. Since bytes can be accessed in any order, the memory is also referred to asrandom-access memory (RAM). Todays personal computers usually have at least 1 gigabyteof RAM. Computer storage size is measured in bytes, kilobytes (KB), megabytes (MB), giga-bytes210 = 1024,(GB), and terabytes (TB). A kilobyte is about 1000 bytes, a megabyte isabout 1 million bytes, a gigabyte is about 1 billion bytes, and a terabyte is220 = 1048576,about 1000 gigabytes. Like the CPU, memory is built on silicon semiconductor chips havingthousands of transistors embedded on their surface. Compared to CPU chips, memory chipsare less complicated, slower, and less expensive.speedhertzmegahertzgigahertzbitbyte0100101001100001011101100110000100000011Encoding for character JEncoding for character aEncoding for character vEncoding for character aEncoding for number 320002001200220032004FIGURE 1.2 Memory stores data and program instructions.RAMmegabyte 28. 4 Chapter 1 Introduction to Computers, Programs, and Java1.2.3 Storage DevicesMemory is volatile, because information is lost when the power is turned off. Programs anddata are permanently stored on storage devices and are moved, when the computer actuallyuses them, to memory, which is much faster than storage devices.There are four main types of storage devices: Disk drives CD drives (CD-R, CD-RW, and DVD) Tape drives USB flash drivesDrives are devices for operating a medium, such as disks, CDs, and tapes.DisksEach computer has at least one hard drive. Hard disks are for permanently storing data andprograms. The hard disks of the latest PCs store from 80 to 250 gigabytes. Often disk drivesare encased inside the computer. Removable hard disks are also available.CDs and DVDsCD stands for compact disk. There are two types of CD drives: CD-R and CD-RW. A CD-R isfor read-only permanent storage; the user cannot modify its contents once they are recorded.A CD-RW can be used like a hard disk and can be both read and rewritten. A single CD canhold up to 700 MB. Most software is distributed through CD-ROMs. Most new PCs areequipped with a CD-RW drive that can work with both CD-R and CD-RW.DVD stands for digital versatile disc or digital video disk. DVDs and CDs look alike, andyou can use either to store data. A DVD can hold more information than a CD. A standardDVDs storage capacity is 4.7 GB.TapesTapes are mainly used for backup of data and programs. Unlike disks and CDs, tapes storeinformation sequentially. The computer must retrieve information in the order it was stored.Tapes are very slow. It would take one to two hours to back up a 1-gigabyte hard disk. Thenew trend is to back up data using flash drives or external hard disks.USB Flash DrivesUSB flash drives are devices for storing and transporting data. A flash drive is smallaboutthe size of a pack of gum. It acts like a portable hard drive that can be plugged into your com-putersUSB port. USB flash drives are currently available with up to 32 GB storage capacity.1.2.4 Input and Output DevicesInput and output devices let the user communicate with the computer. The common inputdevices are keyboards and mice. The common output devices are monitors and printers.The KeyboardA computer keyboard resembles a typewriter keyboard with extra keys added for certain spe-cialfunctions.Function keys are located at the top of the keyboard and are numbered with prefix F. Theiruse depends on the software.A modifier key is a special key (e.g., Shift, Alt, Ctrl) that modifies the normal action ofanother key when the two are pressed in combination.drivehard diskCD-RCD-RWfunction keymodifier key 29. 1.3 Programs 5The numeric keypad, located on the right-hand corner of the keyboard, is a separate set ofkeys for quick input of numbers.Arrow keys, located between the main keypad and the numeric keypad, are used to movethe cursor up, down, left, and right.The Insert, Delete, Page Up, and Page Down keys, located above the arrow keys, are usedin word processing for performing insert, delete, page up, and page down.The MouseA mouse is a pointing device. It is used to move an electronic pointer called a cursor aroundthe screen or to click on an object on the screen to trigger it to respond.The MonitorThe monitor displays information (text and graphics). The screen resolution and dot pitchdetermine the quality of the display.The screen resolution specifies the number of pixels per square inch. Pixels (short for pic-tureelements) are tiny dots that form an image on the screen. A common resolution for a 17-inch screen, for example, is 1024 pixels wide and 768 pixels high. The resolution can be setmanually. The higher the resolution, the sharper and clearer the image is.The dot pitch is the amount of space between pixels in millimeters. The smaller the dotpitch, the better the display.1.2.5 Communication DevicesComputers can be networked through communication devices, such as the dialup modem(modulator/demodulator), DSL, cable modem, network interface card, and wireless. A dialupmodem uses a phone line and can transfer data at a speed up to 56,000 bps (bits per second).A DSL (digital subscriber line) also uses a phone line and can transfer data twenty timesfaster. A cable modem uses the TV cable line maintained by the cable company and is as fastas a DSL. A network interface card (NIC) is a device that connects a computer to a local areanetwork (LAN). The LAN is commonly used in universities and business and governmentorganizations. A typical NIC called 10BaseT can transfer data at 10 mbps (million bits persecond). Wireless is becoming popular. Every laptop sold today is equipped with a wirelessadapter that enables the computer to connect with the Internet.1.3 ProgramsComputer programs, known as software, are instructions to the computer, telling it what to do.Computers do not understand human languages, so you need to use computer languages incomputer programs. Programming is the creation of a program that is executable by a com-puterand performs the required tasks.A computers native language, which differs among different types of computers, is itsmachine languagea set of built-in primitive instructions. These instructions are in the formof binary code, so in telling the machine what to do, you have to enter binary code. Program-mingin machine language is a tedious process. Moreover, the programs are highly difficult toread and modify. For example, to add two numbers, you might have to write an instruction inbinary like this:1101101010011010Assembly language is a low-level programming language in which a mnemonic is used torepresent each of the machine-language instructions. For example, to add two numbers, youmight write an instruction in assembly code like this:ADDF3 R1, R2, R3numeric keypadscreen resolutiondot pitchmodemDSLNICLANmbpssoftwareprogrammingmachine languageassembly language 30. 6 Chapter 1 Introduction to Computers, Programs, and JavaAssembly languages were developed to make programming easy. However, since the com-putercannot understand assembly language, a program called an assembler is used to convertassembly-language programs into machine code, as shown in Figure 1.3.Assembly programs are written in terms of machine instructions with easy-to-remembermnemonic names. Since assembly language is machine dependent, an assembly program canbe executed only on a particular kind of machine. The high-level languages were developed inorder to transcend platform specificity and make programming easier.The high-level languages are English-like and easy to learn and program. Here, for exam-ple,is a high-level language statement that computes the area of a circle with radius 5:area = 5 * 5 * 3.1415;Among the more than one hundred high-level languages, the following are well known: COBOL (COmmon Business Oriented Language) FORTRAN (FORmula TRANslation) BASIC (Beginners All-purpose Symbolic Instruction Code) Pascal (named for Blaise Pascal) Ada (named for Ada Lovelace) C (developed by the designer of B) Visual Basic (Basic-like visual language developed by Microsoft) Delphi (Pascal-like visual language developed by Borland) C++ (an object-oriented language, based on C) C# (a Java-like language developed by Microsoft) JavaEach of these languages was designed for a specific purpose. COBOL was designed for busi-nessapplications and is used primarily for business data processing. FORTRAN wasdesigned for mathematical computations and is used mainly for numeric computations.BASIC was designed to be learned and used easily. Ada was developed for the Departmentof Defense and is used mainly in defense projects. C combines the power of an assembly lan-guagewith the ease of use and portability of a high-level language. Visual Basic and Delphiare used in developing graphical user interfaces and in rapid application development. C++is popular for system software projects such as writing compilers and operating systems. TheMicrosoft Windows operating system was coded using C++. C# (pronounced C sharp) is anew language developed by Microsoft for developing applications based on the Microsoft.NET platform. Java, developed by Sun Microsystems, is widely used for developing plat-form-independent Internet applications.assemblerhigh-level languageAssembly Source File..ADDF3 R1, R2, R3..Machine-Code File..1101101010011010..AssemblerFIGURE 1.3 Assembler translates assembly-language instructions to machine code. 31. 1.4 Operating Systems 7A program written in a high-level language is called a source program or source code.Since a computer cannot understand a source program, a program called a compiler is used totranslate it into a machine-language program. The machine-language program is then linkedwith other supporting library code to form an executable file, which can be run on themachine, as shown in Figure 1.4. On Windows, executable files have extension .exe.1.4 Operating SystemsThe operating system (OS) is the most important program that runs on a computer, whichmanages and controls a computers activities. The popular operating systems are MicrosoftWindows, Mac OS, and Linux. Application programs, such as a Web browser or a wordprocessor, cannot run without an operating system. The interrelationship of hardware, operat-ingsystem, application software, and the user is shown in Figure 1.5.The major tasks of an operating system are: Controlling and monitoring system activities Allocating and assigning system resources Scheduling operations1.4.1 Controlling and Monitoring System ActivitiesOperating systems perform basic tasks, such as recognizing input from the keyboard, sendingoutput to the monitor, keeping track of files and directories on the disk, and controllingperipheral devices, such as disk drives and printers. They also make sure that different pro-gramsand users running at the same time do not interfere with each other, and they areresponsible for security, ensuring that unauthorized users do not access the system.source programcompilerOSSource File Compiler Machine-language LinkerFileExecutableFileLibrary CodeFIGURE 1.4 A source program is compiled into a machine-language file, which is thenlinked with the system library to form an executable file.UserApplication ProgramsOperating SystemHardwareFIGURE 1.5 The operating system is the software that controls and manages the system. 32. 8 Chapter 1 Introduction to Computers, Programs, and Java1.4.2 Allocating and Assigning System ResourcesThe operating system is responsible for determining what computer resources a programneeds (e.g., CPU, memory, disks, input and output devices) and for allocating and assigningthem to run the program.1.4.3 Scheduling OperationsThe OS is responsible for scheduling programs to make efficient use of system resources. Manyof todays operating systems support such techniques as multiprogramming, multithreading, ormultiprocessing to increase system performance.Multiprogramming allows multiple programs to run simultaneously by sharing the CPU.The CPU is much faster than the computers other components. As a result, it is idle most ofthe timefor example, while waiting for data to be transferred from the disk or from othersources. A multiprogramming OS takes advantage of this situation by allowing multiple pro-gramsto use the CPU when it would otherwise be idle. For example, you may use a wordprocessor to edit a file at the same time as the Web browser is downloading a file.Multithreading allows concurrency within a program, so that its subtasks can run at thesame time. For example, a word-processing program allows users to simultaneously edit textand save it to a file. In this example, editing and saving are two tasks within the same applica-tion.These two tasks may run on separate threads concurrently.Multiprocessing, or parallel processing, uses two or more processors together to perform atask. It is like a surgical operation where several doctors work together on one patient.1.5 Java, World Wide Web, and BeyondThis book introduces Java programming. Java was developed by a team led by JamesGosling at Sun Microsystems. Originally called Oak, it was designed in 1991 for use inembedded chips in consumer electronic appliances. In 1995, renamed Java, it wasredesigned for developing Internet applications. For the history of Java, seejava.sun.com/features/1998/05/birthday.html.Java has become enormously popular. Its rapid rise and wide acceptance can be traced toits design characteristics, particularly its promise that you can write a program once and run itanywhere. As stated by Sun, Java is simple, object oriented, distributed, interpreted, robust,secure, architecture neutral, portable, high performance, multithreaded, and dynamic. For theanatomy of Java characteristics, see www.cs.armstrong.edu/liang/JavaCharacteristics.pdf.Java is a full-featured, general-purpose programming language that can be used to developrobust mission-critical applications. Today, it is employed not only for Web programming, butalso for developing standalone applications across platforms on servers, desktops, and mobiledevices. It was used to develop the code to communicate with and control the robotic rover onMars. Many companies that once considered Java to be more hype than substance are nowusing it to create distributed applications accessed by customers and partners across the Inter-net.For every new project being developed today, companies are asking how they can useJava to make their work easier.The World Wide Web is an electronic information repository that can be accessed on theInternet from anywhere in the world. The Internet, the Webs infrastructure, has been aroundfor more than thirty years. The colorful World Wide Web and sophisticated Web browsers arethe major reason for the Internets popularity.The primary authoring language for the Web is the Hypertext Markup Language (HTML).HTML is a simple language for laying out documents, linking documents on the Internet, andbringing images, sound, and video alive on the Web. However, it cannot interact with the userexcept through simple forms. Web pages in HTML are essentially static and flat.Java initially became attractive because Java programs can be run from a Web browser.Such programs are called applets. Applets employ a modern graphical interface with buttons,multiprogrammingmultithreadingmultiprocessingapplet 33. 1.5 Java, World Wide Web, and Beyond 9text fields, text areas, radio buttons, and so on, to interact with users on the Web and processtheir requests. Applets make the Web responsive, interactive, and fun to use. Figure 1.6 showsan applet running from a Web browser for playing a Tic Tac Toe game.Enter this URL from a Web browserFIGURE 1.6 A Java applet for playing TicTacToe is embedded in an HTML page.TipFor a demonstration of Java applets, visit java.sun.com/applets. This site provides a rich Javaresource as well as links to other cool applet demo sites. java.sun.com is the official Sun Java Web-site.Java can also be used to develop applications on the server side. These applications can berun from a Web server to generate dynamic Web pages. The automatic grading system for thisbook, as shown in Figure 1.7, was developed using Java.Enter this URL from a Web browserFIGURE 1.7 Java was used to develop an automatic grading system to accompany this book. 34. 10 Chapter 1 Introduction to Computers, Programs, and JavaJava is a versatile programming language. You can use it to develop applications onyour desktop and on the server. You can also use it to develop applications for small hand-helddevices. Figure 1.8 shows a Java-programmed calendar displayed on a BlackBerryand on a cell phone.1.6 The Java Language Specification, API, JDK, and IDEComputer languages have strict rules of usage. If you do not follow the rules when writing aprogram, the computer will be unable to understand it. The Java language specification andJava API define the Java standard.The Java language specification is a technical definition of the language that includes thesyntax and semantics of the Java programming language. The complete Java language speci-ficationcan be found at java.sun.com/docs/books/jls.The application program interface (API) contains predefined classes and interfaces fordeveloping Java programs. The Java language specification is stable, but the API is stillexpanding. At the Sun Java Website (java.sun.com), you can view and download the latest ver-sionof the Java API.Java is a full-fledged and powerful language that can be used in many ways. It comes inthree editions: Java Standard Edition (Java SE), Java Enterprise Edition (Java EE), and JavaMicro Edition (Java ME). Java SE can be used to develop client-side standalone applicationsor applets. Java EE can be used to develop server-side applications, such as Java servlets andJavaServer Pages. Java ME can be used to develop applications for mobile devices, such ascell phones. This book uses Java SE to introduce Java programming.There are many versions of Java SE. The latest, Java SE 6, will be used in this book. Sunreleases each version with a Java Development Toolkit (JDK). For Java SE 6, the Java Devel-opmentToolkit is called JDK 1.6 (also known as Java 6 or JDK 6).JDK consists of a set of separate programs, each invoked from a command line, for devel-opingand testing Java programs. Besides JDK, you can use a Java development tool (e.g., Net-Beans, Eclipse, and TextPad)software that provides an integrated development environment(IDE) for rapidly developing Java programs. Editing, compiling, building, debugging, andJava language specificationAPIJava SE, EE, and MEJDK 1.6 = JDK 6FIGURE 1.8 Java can be used to develop applications for hand-held and wireless devices,such as a BlackBerry (left) and a cell phone (right).Java IDE 35. 1.7 A Simple Java Program 11online help are integrated in one graphical user interface. Just enter source code in one windowor open an existing file in a window, then click a button, menu item, or function key to compileand run the program.1.7 A Simple Java ProgramLet us begin with a simple Java program that displays the message Welcome to Java! on theconsole. Console refers to text entry and display device of a computer. The program is shownin Listing 1.1.LISTING 1.1 Welcome.java1 public class Welcome {2 public static void main(String[] args) {3 // Display message Welcome to Java! to the console4 System.out.println("Welcome to Java!");5 }6 }consoleVideo NoteFirst Java programclassmain methoddisplay messageWelcome to Java!The line numbers are displayed for reference purposes but are not part of the program. So,dont type line numbers in your program.Line 1 defines a class. Every Java program must have at least one class. Each class has aname. By convention, class names start with an uppercase letter. In this example, the classname is Welcome.Line 2 defines the main method. In order to run a class, the class must contain a methodnamed main. The program is executed from the main method.A method is a construct that contains statements. The main method in this program con-tainsthe System.out.println statement. This statement prints a message "Welcome toJava!" to the console (line 4). Every statement in Java ends with a semicolon (;), known asthe statement terminator.Reserved words, or keywords, have a specific meaning to the compiler and cannot be usedfor other purposes in the program. For example, when the compiler sees the word class, itunderstands that the word after class is the name for the class. Other reserved words in thisprogram are public, static, and void.Line 3 is a comment that documents what the program is and how it is constructed. Com-mentshelp programmers to communicate and understand the program. They are not pro-grammingstatements and thus are ignored by the compiler. In Java, comments are precededby two slashes (//) on a line, called a line comment, or enclosed between /* and */ on one orseveral lines, called a block comment. When the compiler sees //, it ignores all text after //on the same line. When it sees /*, it scans for the next */ and ignores any text between /*and */. Here are examples of comments:// This application program prints Welcome to Java!/* This application program prints Welcome to Java! *//* This application programprints Welcome to Java! */A pair of braces in a program forms a block that groups the programs components. In Java,each block begins with an opening brace ({) and ends with a closing brace (}). Every classhas a class block that groups the data and methods of the class. Every method has a methodline numbersclass namemain methodstatement terminatorreserved wordcommentblock 36. 12 Chapter 1 Introduction to Computers, Programs, and Javablock that groups the statements in the method. Blocks can be nested, meaning that one blockcan be placed within another, as shown in the following code.public class Welcome {public static void main(String[] args) {System.out.println("Welcome to Java!");}}TipAn opening brace must be matched by a closing brace. Whenever you type an opening brace,immediately type a closing brace to prevent the missing-brace error. Most Java IDEs automaticallyinsert the closing brace for each opening brace.NoteYou are probably wondering why the main method is declared this way and whySystem.out.println(...) is used to display a message to the console. For the time being,simply accept that this is how things are done. Your questions will be fully answered in subse-quentchapters.CautionJava source programs are case sensitive. It would be wrong, for example, to replace main in theprogram with Main.NoteLike any programming language, Java has its own syntax, and you need to write code that obeysthe syntax rules. If your program violates the rulesfor example if the semicolon is missing, abrace is missing, a quotation mark is missing, or String is misspelledthe Java compiler willreport syntax errors. Try to compile the program with these errors and see what the compilerreports.The program in Listing 1.1 displays one message. Once you understand the program, it iseasy to extend it to display more messages. For example, you can rewrite the program to dis-playthree messages, as shown in Listing 1.2.LISTING 1.2 Welcome1.java1 public class Welcome1 {2 public static void main(String[] args) {3 System.out.println("Programming is fun!");4 System.out.println("Fundamentals First");5 System.out.println("Problem Driven");6 }7 }matching bracessyntax rulesclassmain methoddisplay messageProgramming is fun!Fundamentals FirstProblem DrivenMethod blockClass blockFurther, you can perform mathematical computations and display the result to the console.Listing 1.3 gives an example of evaluating10.5 + 2 * 345 - 3.5.case sensitive 37. 1.8 Creating, Compiling, and Executing a Java Program 13classmain methodcompute expressionLISTING 1.3 ComputeExpression.java1 public class ComputeExpression {2 public static void main(String[] args) {3 System.out.println((10.5 + 2 * 3) / (45 3.5));4 }5 }0.39759036144578314The multiplication operator in Java is *. As you see, it is a straightforward process to trans-latean arithmetic expression to a Java expression. We will discuss Java expressions further inChapter 2.1.8 Creating, Compiling, and Executing a Java ProgramYou have to create your program and compile it before it can be executed. This process isrepetitive, as shown in Figure 1.9. If your program has compilation errors, you have to mod-ifythe program to fix them, then recompile it. If your program has runtime errors or does notproduce the correct result, you have to modify the program, recompile it, and execute itagain.Create/Modify Source CodeSaved on the diskSource CodeCompile Source Codee.g., javac Welcome.javaStored on the diskIf compilation errorsBytecodeResultIf runtime errors or incorrect resultSource code (developed by the programmer)public class Welcome {public static void main(String[] args) {System.out.println("Welcome to Java!");Bytecode (generated by the compiler for JVMto read and interpret, not for you to understand)}Method Welcome()0 aload_0Method void main(java.lang.String[])0 getstatic #2 3 ldc #3 5 invokevirtual #4 8 return}Run Bytecodee.g., java WelcomeWelcome to Java is printed on the consoleWelcome to Java!FIGURE 1.9 The Java program-development process consists of repeatedly creating/modifying source code, compiling,and executing programs. 38. 14 Chapter 1 Introduction to Computers, Programs, and JavaYou can use any text editor or IDE to create and edit a Java source-code file. This sectiondemonstrates how to create, compile, and run Java programs from a command window. If youwish to use an IDE such as Eclipse, NetBeans, or TextPad, please refer to Supplement II fortutorials. From the command window, you can use the NotePad to create the Java source codefile, as shown in Figure 1.10.NoteThe source file must end with the extension .java and must have exactly the same name as thepublic class name. For example, the file for the source code in Listing 1.1 should be namedWelcome.java, since the public class name is Welcome.A Java compiler translates a Java source file into a Java bytecode file. The following com-mandcompiles Welcome.java:javac Welcome.javaNoteYou must first install and configure JDK before compiling and running programs. See SupplementI.B, Installing and Configuring JDK 6, on how to install JDK and set up the environment tocompile and run Java programs. If you have trouble compiling and running programs, please seeSupplement I.C, Compiling and Running Java from the Command Window. This supplementalso explains how to use basic DOS commands and how to use Windows NotePad and WordPadto create and edit files. All the supplements are accessible from the Companion Website.If there are no syntax errors, the compiler generates a bytecode file with a .class extension. Sothe preceding command generates a file named Welcome. class, as shown in Figure 1.11(a). TheJava language is a high-level language while Java bytecode is a low-level language. The bytecodeis similar to machine instructions but is architecture neutral and can run on any platform that hasa Java Virtual Machine (JVM), as shown in Figure 1.11(b). Rather than a physical machine, thevirtual machine is a program that interprets Java bytecode. This is one of Javas primary advan-tages:Java bytecode can run on a variety of hardware platforms and operating systems.editorVideo NoteBrief Eclipse Tutorialfile namecompileSupplement I.BSupplement I.C.class bytecode fileFIGURE 1.10 You can create the Java source file using Windows NotePad.Java BytecodeJava Virtual MachineAnyComputerWelcome.java(Java sourcecode file)Welcome.class(Java bytecodeexecutable file)Java JVMcompiled Compilerbygenerates executedby(a) (b)FIGURE 1.11 (a) Java source code is translated into bytecode. (b) Java bytecode can be executed on any computer with aJava Virtual Machine. 39. 1.8 Creating, Compiling, and Executing a Java Program 15To execute a Java program is to run the programs bytecode. You can execute the bytecodeon any platform with a JVM. Java bytecode is interpreted. Interpreting translates the individ-ualsteps in the bytecode into the target machine-language code one at a time rather than trans-latingthe whole program as a single unit. Each step is executed immediately after it istranslated.The following command runs the bytecode:java WelcomeFigure 1.12 shows the javac command for compiling Welcome.java. The compiler gener-atedthe Welcome.class file. This file is executed using the java command.NoteFor simplicity and consistency, all source code and class files are placed under c:book unlessspecified otherwise.CautionDo not use the extension .class in the command line when executing the program. Use javaClassName to run the program. If you use java ClassName.class in the command line, thesystem will attempt to fetch ClassName.class.class.TipIf you execute a class file that does not exist, a NoClassDefFoundError will occur. If you exe-cutea class file that does not have a main method or you mistype the main method (e.g., bytyping Main instead of main), a NoSuchMethodError will occur.NoteWhen executing a Java program, the JVM first loads the bytecode of the class to memory using aprogram called the class loader. If your program uses other classes, the class loader dynamicallyloads them just before they are needed. After a class is loaded, the JVM uses a program calledbytecode verifier to check the validity of the bytecode and ensure that the bytecode does not vio-lateJavas security restrictions. Java enforces strict security to make sure that Java programs arriv-ingfrom the network do not harm your computer.interpreting bytecoderunc:bookjava ClassNameNoClassDefFoundErrorNoSuchMethodErrorclass loaderbytecode verifierCompileShow filesRunFIGURE 1.12 The output of Listing 1.1 displays the message Welcome to Java!Video NoteCompile and run a Java program 40. 16 Chapter 1 Introduction to Computers, Programs, and JavaPedagogical NoteInstructors may require students to use packages for organizing programs. For example, you mayplace all programs in this chapter in a package named chapter1. For instructions on how to usepackages, please see Supplement I.F, Using Packages to Organize the Classes in the Text.1.9 (GUI) Displaying Text in a Message Dialog BoxThe program in Listing 1.1 displays the text on the console, as shown in Figure 1.12. You canrewrite the program to display the text in a message dialog box. To do so, you need to use theshowMessageDialog method in the JOptionPane class. JOptionPane is one of the manypredefined classes in the Java system that you can reuse rather than reinventing the wheel.You can use the showMessageDialog method to display any text in a message dialog box,as shown in Figure 1.13. The new program is given in Listing 1.4.LISTING 1.4 WelcomeInMessageDialogBox.java1 /* This application program displays Welcome to Java!2 * in a message dialog box.3 */4import javax.swing.JOptionPane;56 public class WelcomeInMessageDialogBox {7 public static void main(String[] args) {8 // Display Welcome to Java! in a message dialog box9JOptionPane.showMessageDialog(null, "Welcome to Java!");10 }11 }This program uses a Java class JOptionPane (line 9). Javas predefined classes are groupedinto packages. JOptionPane is in the javax.swing package. JOptionPane is imported tothe program using the import statement in line 4 so that the compiler can locate the classwithout the full name javax.swing.JOptionPane.NoteIf you replace JOptionPane on line 9 with javax.swing.JOptionPane, you dont need toimport it in line 4. javax.swing.JOptionPane is the full name for the JOptionPane class.The showMessageDialog method is a static method. Such a method should be invokedby using the class name followed by a dot operator (.) and the method name with arguments.Methods will be introduced in Chapter 5, Methods. The showMessageDialog method canbe invoked with two arguments, as shown below.using packageJOptionPaneshowMessageDialogblock commentimportmain methodpackageTitle barMessageClick the OK button todismiss the dialog boxTitleFIGURE 1.13 Welcome to Java! is displayed in a message box.display messageJOptionPane.showMessageDialog(null,"Welcome to Java!"); 41. Key Terms 17The first argument can always be null. null is a Java keyword that will be fully intro-ducedin Chapter 8, Objects and Classes. The second argument is a string for text to bedisplayed.There are several ways to use the showMessageDialog method. For the time being, youneed to know only two ways. One is to use a statement, as shown in the example:JOptionPane.showMessageDialog(null, x);where x is a string for the text to be displayed.The other is to use a statement like this one:JOptionPane.showMessageDialog(null, x,y, JOptionPane.INFORMATION_MESSAGE);where x is a string for the text to be displayed, and y is a string for the title of the messagebox. The fourth argument can be JOptionPane.INFORMATION_MESSAGE, which causes theicon ( ) to be displayed in the message box, as shown in the following example.two versions ofshowMessageDialogspecific importwildcard importno performance differencejava.langimplicitly importedNoteThere are two types of import statements: specific import and wildcard import. The specificimport specifies a single class in the import statement. For example, the following statementimports JOptionPane from package javax.swing..class file 14.java file 14assembly language 5bit 3block 12block comment 11bus 2JOptionPane.showMessageDialog(null,"Welcome to Java!","Display Message",JOptionPane.INFORMATION_MESSAGE);byte 3bytecode 14bytecode verifier 15cable modem 5central processing unit (CPU) 2class loader 15comment 11import javax.swing.JOptionPane;The wildcard import imports all the classes in a package. For example, the following statementimports all classes from package javax.swing.import javax.swing.*;The information for the classes in an imported package is not read in at compile time or runtimeunless the class is used in the program. The import statement simply tells the compiler where tolocate the classes. There is no performance difference between a specific import and a wildcardimport declaration.NoteRecall that you have used the System class in the statement System.out.println(Welcometo Java); in Listing 1.1. The System class is not imported because it is in the java.langpackage. All the classes in the java.lang package are implicitly imported in every Java program.KEY TERMS 42. 18 Chapter 1 Introduction to Computers, Programs, and Javacompiler 7console 11dot pitch 5DSL (digital subscriber line) 5hardware 2high-level language 6Integrated Development Environment(IDE) 10java command 15javac command 15Java Development Toolkit (JDK) 10Java Virtual Machine (JVM) 14keyword (or reserved word) 11line comment 11machine language 5main method 11memory 3modem 5network interface card (NIC) 5operating system (OS) 7pixel 5program 5programming 5resolution 5software 5source code 7source file 14specific import 17storage devices 4statement 11wildcard import 17NoteThe above terms are defined in the present chapter. Supplement I.A, Glossary, lists all thekey terms and descriptions in the book, organized by chapters.CHAPTER SUMMARY1. A computer is an electronic device that stores and processes data.2. A computer includes both hardware and software.3. Hardware is the physical aspect of the computer that can be seen.4. Computer programs, known as software, are the invisible instructions that control thehardware and make it perform tasks.5. Computer programming is the writing of instructions (i.e., code) for computers toperform.6. The central processing unit (CPU) is a computers brain. It retrieves instructions frommemory and executes them.7. Computers use zeros and ones because digital devices have two stable states, referredto by convention as zero and one.8. A bit is a binary digit 0 or 1.9. A byte is a sequence of 8 bits.10. A kilobyte is about 1000 bytes, a megabyte about 1 million bytes, a gigabyte about 1billion bytes, and a terabyte about 1000 gigabytes.11. Memory stores data and program instructions for the CPU to execute.12. A memory unit is an ordered sequence of bytes.13. Memory is volatile, because information is lost when the power is turned off.Supplement I.A 43. Chapter Summary 1914. Programs and data are permanently stored on storage devices and are moved to mem-orywhen the computer actually uses them.15. The machine language is a set of primitive instructions built into every computer.16. Assembly language is a low-level programming language in which a mnemonic isused to represent each machine-language instruction.17. High-level languages are English-like and easy to learn and program.18. A program written in a high-level language is called a source program.19. A compiler is a software program that translates the source program into a machine-languageprogram.20. The operating system (OS) is a program that manages and controls a computersactivities.21. Java is platform independent, meaning that you can write a program once and run itanywhere.22. Java programs can be embedded in HTML pages and downloaded by Web browsersto bring live animation and interaction to Web clients.23. Java source files end with the .java extension.24. Every class is compiled into a separate bytecode file that has the same name as theclass and ends with the .class extension.25. To compile a Java source-code file from the command line, use the javac command.26. To run a Java class from the command line, use the java command.27. Every Java program is a set of class definitions. The keyword class introduces aclass definition. The contents of the class are included in a block.28. A block begins with an opening brace ({) and ends with a closing brace (}). Methodsare contained in a class.29. A Java program must have a main method. The main method is the entry point wherethe program starts when it is executed.30. Every statement in Java ends with a semicolon (;), known as the statement terminator.31. Reserved words, or keywords, have a specific meaning to the compiler and cannot beused for other purposes in the program.32. In Java, comments are preceded by two slashes (//) on a line, called a line comment,or enclosed between /* and */ on one or several lines, called a block comment.33. Java source programs are case sensitive.34. There are two types of import statements: specific import and wildcard import. Thespecific import specifies a single class in the import statement. The wildcard importimports all the classes in a package. 44. 20 Chapter 1 Introduction to Computers, Programs, and JavaREVIEW QUESTIONSNoteAnswers to review questions are on the Companion Website.Sections 1.21.41.1 Define hardware and software.1.2 List the main components of the computer.1.3 Define machine language, assembly language, and high-level programminglanguage.1.4 What is a source program? What is a compiler?1.5 What is the JVM?1.6 What is an operating system?Sections 1.51.61.7 Describe the history of Java. Can Java run on any machine? What is needed to runJava on a computer?1.8 What are the input and output of a Java compiler?1.9 List some Java development tools. Are tools like NetBeans and Eclipse differentlanguages from Java, or are they dialects or extensions of Java?1.10 What is the relationship between Java and HTML?Sections 1.71.91.11 Explain the Java keywords. List some Java keywords you learned in this chapter.1.12 Is Java case sensitive? What is the case for Java keywords?1.13 What is the Java source filename extension, and what is the Java bytecode file-nameextension?1.14 What is a comment? Is the comment ignored by the compiler? How do you denotea comment line and a comment paragraph?1.15 What is the statement to display a string on the console? What is the statement todisplay the message Hello world in a message dialog box?1.16 The following program is wrong. Reorder the lines so that the program displaysmorning followed by afternoon.public static void main(String[] args) {}public class Welcome {System.out.println("afternoon");System.out.println("morning");}1.17 Identify and fix the errors in the following code:1 public class Welcome {2 public void Main(String[] args) {3 System.out.println('Welcome to Java!);4 }5 ) 45. Programming Exercises 211.18 What is the command to compile a Java program? What is the command to run aJava program?1.19 If a NoClassDefFoundError occurs when you run a program, what is the causeof the error?1.20 If a NoSuchMethodError occurs when you run a program, what is the cause ofthe error?1.21 Why does the System class not need to be imported?1.22 Are there any performance differences between the following two importstatements?import javax.swing.JOptionPane;import javax.swing.*;1.23 Show the output of the following code:public class Test {public static void main(String[] args) {System.out.println("3.5 * 4 / 2 2.5 is ");System.out.println(3.5 * 4 / 2 2.5);}}PROGRAMMING EXERCISESNoteSolutions to even-numbered exercises are on the Companion Website. Solutions to all exer-cisesare on the Instructor Resource Website. The level of difficulty is rated easy (no star),moderate (*), hard (**), or challenging (***).1.1 (Displaying three messages) Write a program that displays Welcome to Java,Welcome to Computer Science, and Programming is fun.1.2 (Displaying five messages) Write a program that displays Welcome to Java fivetimes.1.3* (Displaying a pattern) Write a program that displays the following pattern:J A V V AJ A A V V A AJ J AAAAA V V AAAAAJ J A A V A A1.4 (Printing a table) Write a program that displays the following table:a a^2 a^31 1 12 4 83 9 274 16 641.5 (Computing expressions) Write a program that displays the result of9.5 * 4.5 - 2.5 * 345.5 - 3.5.level of difficulty 46. 22 Chapter 1 Introduction to Computers, Programs, and Java1.6 (Summation of a series) Write a program that displays the result of1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9.1.7 (Approximating ) can be computed using the following formula:Write a program that displays the result ofUse 1.0 instead of 1 in your program.19-111+113b.4 * a1 -13+15-17+p = 4 * a1 -13+15-17+19-111+113+ bp p 47. CHAPTER 2ELEMENTARY PROGRAMMINGObjectives To write Java programs to perform simple calculations (2.2). To obtain input from the console using the Scannerclass (2.3). To use identifiers to name variables, constants, methods,and classes (2.4). To use variables to store data (2.52.6). To program with assignment statements and assignmentexpressions (2.6). To use constants to store permanent data (2.7). To declare Java primitive data types: byte, short,int, long, float, double, and char (2.8.1). To use Java operators to write numericexpressions (2.8.22.8.3). To display the current time (2.9). To use shorthand operators (2.10). To cast the value of one type to another type (2.11). To compute loan payments (2.12). To represent characters using the char type (2.13). To compute monetary changes (2.14). To represent a string using the String type (2.15). To become familiar with Java documentation,programming style, and naming conventions (2.16). To distinguish syntax errors, runtime errors, and logicerrors and debug errors (2.17). (GUI) To obtain input using the JOptionPane inputdialog boxes (2.18). 48. 24 Chapter 2 Elementary Programming2.1 IntroductionIn Chapter 1 you learned how to create, compile, and run a Java program. Now you will learnhow to solve practical problems programmatically. Through these problems, you will learn ele-mentaryprogramming using primitive data types, variables, constants, operators, expressions,and input and output.2.2 Writing Simple ProgramsTo begin, lets look at a simple problem for computing the area of a circle. How do we write aprogram for solving this problem?Writing a program involves designing algorithms and translating algorithms into code. Analgorithm describes how a problem is solved in terms of the actions to be executed and theorder of their execution. Algorithms can help the programmer plan a program before writingit in a programming language. Algorithms can be described in natural languages or inpseudocode (i.e., natural language mixed with programming code). The algorithm for thisprogram can be described as follows:1. Read in the radius.2. Compute the area using the following formula:3. Display the area.area = radius * radius * pMany of the problems you will encounter when taking an introductory course in program-mingcan be described with simple, straightforward algorithms.When you code, you translate an algorithm into a program. You already know that everyJava program begins with a class declaration in which the keyword class is followed by theclass name. Assume that you have chosen ComputeArea as the class name. The outline of theprogram would look like this:public class ComputeArea {// Details to be given later}As you know, every Java program must have a main method where program executionbegins. So the program is expanded as follows:public class ComputeArea {public static void main(String[] args) {// Step 1: Read in radius// Step 2: Compute area// Step 3: Display the area}}The program needs to read the radius entered by the user from the keyboard. This raises twoimportant issues: Reading the radius. Storing the radius in the program.Lets address the second issue first. In order to store the radius, the program needs to declare a sym-bolcalled a variable. A variable designates a location in memory for storing data and computa-tionalresults in the program. A variable has a name that can be used to access the memory location.problemalgorithmpseudocodevariable 49. 2.2 Writing Simple Programs 25Rather than using x and y as variable names, choose descriptive names: in this case,radius for radius, and area for area. To let the compiler know what radius and area are,specify their data types. Java provides simple data types for representing integers, floating-pointnumbers (i.e., numbers with a decimal point), characters, and Boolean types. Thesetypes are known as primitive data types or fundamental types.Declare radius and area as double-precision floating-point numbers. The program canbe expanded as follows:public class ComputeArea {public static void main(String[] args) {double radius;double area;// Step 1: Read in radius// Step 2: Compute area// Step 3: Display the area}}The program declares radius and area as variables. The reserved word double indicatesthat radius and area are double-precision floating-point values stored in the computer.The first step is to read in radius. Reading a number from the keyboard is not a simplematter. For the time being, let us assign a fixed value to radius in the program.The second step is to compute area by assigning the result of the expression radius *radius * 3.14159 to area.In the final step, display area on the console by using the System.out.printlnmethod.The complete program is shown in Listing 2.1. A sample run of the program is shown inFigure 2.1.LISTING 2.1 ComputeArea.java1 public class ComputeArea {2 public static void main(String[] args) {3 double radius; // Declare radius4 double area; // Declare area56 // Assign a radius7 radius = 20; // New value is radius89 // Compute area10 area = radius * radius * 3.14159;1112 // Display resultsdescriptive namesfloating-point numberprimitive data typesCompileRunFIGURE 2.1 The program displays the area of a circle. 50. 26 Chapter 2 Elementary Programming13 System.out.println("The area for the circle of radius " +14 radius + " is " + area);15 }16 }Variables such as radius and area correspond to memory locations. Every variable has aname, a type, a size, and a value. Line 3 declares that radius can store a double value. Thevalue is not defined until you assign a value. Line 7 assigns 20 into radius. Similarly, line 4declares variable area, and line 10 assigns a value into area. The following table shows thevalue in the memory for area and radius as the program is executed. Each row in the tableshows the values of variables after the statement in the corresponding line in the program isexecuted. Hand trace is helpful to understand how a program works, and it is also a useful toolfor finding errors in the program.The plus sign (+) has two meanings: one for addition and the other for concatenatingstrings. The plus sign (+) in lines 1314 is called a string concatenation operator. It combinestwo strings if two operands are strings. If one of the operands is a nonstring (e.g., a number),the nonstring value is converted into a string and concatenated with the other string. So theplus signs (+) in lines 1314 concatenate strings into a longer string, which is then displayedin the output. Strings and string concatenation will be discussed further in 2.15, TheString Type.CautionA string constant cannot cross lines in the source code. Thus the following statement wouldresult in a compile error:System.out.println("Introduction to Java Programming,by Y. Daniel Liang");To fix the error, break the string into separate substrings, and use the concatenation operator (+)to combine them:System.out.println("Introduction to Java Programming, " +"by Y. Daniel Liang");TipThis example consists of three steps. It is a good approach to develop and test these stepsincrementally by adding them one at a time.2.3 Reading Input from the ConsoleIn Listing 2.1, the radius is fixed in the source code. To use a different radius, you have tomodify the source code and recompile it. Obviously, this is not convenient. You can use theScanner class for console input.Java uses System.out to refer to the standard output device and System.in to the stan-dardinput device. By default the output device is the display monitor, and the input device isdeclaring variableassign valueconcatenating stringsconcatenating strings withnumbersbreaking a long stringincremental development andtestingline# radius area3 no value4 no value7 2010 1256.636Video NoteObtain input 51. 2.3 Reading Input from the Console 27the keyboard. To perform console output, you simply use the println method to display aprimitive value or a string to the console. Console input is not directly supported in Java, butyou can use the Scanner class to create an object to read input from System.in, as follows:Scanner input = new Scanner(System.in);The syntax new Scanner(System.in) creates an object of the Scanner type. The syntaxScanner input declares that input is a variable whose type is Scanner. The whole lineScanner input = new Scanner(System.in) creates a Scanner object and assigns its ref-erenceto the variable input. An object may invoke its methods. To invoke a method on anobject is to ask the object to perform a task. You can invoke the methods in Table 2.1 to readvarious types of input.import classcreate a Scannerread a doubleTABLE 2.1 Methods for Scanner ObjectsMethod DescriptionnextByte() reads an integer of the byte type.nextShort() reads an integer of the short type.nextInt() reads an integer of the int type.nextLong() reads an integer of the long type.nextFloat() reads a number of the float type.nextDouble() reads a number of the double type.next() reads a string that ends before a whitespace character.nextLine() reads a line of text (i.e., a string ending with the Enter key pressed).For now, we will see how to read a number that includes a decimal point by invoking thenextDouble() method. Other methods will be covered when they are used. Listing 2.2rewrites Listing 2.1 to prompt the user to enter a radius.LISTING 2.2 ComputeAreaWithConsoleInput.java1 import java.util.Scanner;// Scanner is in the java.util package23 public class ComputeAreaWithConsoleInput {4 public static void main(String[] args) {5 // Create a Scanner object6Scanner input = new Scanner(System.in);78 // Prompt the user to enter a radius9 System.out.print("Enter a number for radius: ");10 double radius = input.nextDouble();1112 // Compute area13 double area = radius * radius * 3.14159;1415 // Display result16 System.out.println("The area for the circle of radius " +17 radius + " is " + area);18 }19 }2.5Enter a number for radius:The area for the circle of radius 2.5 is 19.6349375 52. 28 Chapter 2 Elementary Programming23Enter a number for radius:The area for the circle of radius 23.0 is 1661.90111The Scanner class is in the java.util package. It is imported in line 1. Line 6 creates aScanner object.The statement in line 9 displays a message to prompt the user for input.System.out. ("Enter a number for radius: ");The print method