ebook img

Fundamentals of Java AP Computer Science Essentials PDF

723 Pages·2011·12.244 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Fundamentals of Java AP Computer Science Essentials

This page intentionally left blank 0538744928_ifc_se.qxd 11/13/09 9:47 AM Page 1 This Book Is the Property of: State_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ Book No._ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ Province_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ County_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ Parish_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ EEnntteerr iinnffoorrmmaattiioonn iinn ssppaacceess ttoo tthhee School District_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ lleefftt aass iinnssttrruucctteedd Other_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ Condition Issued to Year Used Issued Returned PPUUPPIILLSS ttoo wwhhoomm tthhiiss tteexxttbbooookk iiss iissssuueedd mmuusstt nnoott wwrriittee oonn aannyy ppaaggee oorr mmaarrkk aannyy ppaarrtt ooff iitt iinn aannyy wwaayy;;ccoonnssuummaabbllee tteexxttbbooookkss eexxcceepptteedd.. 1. Teachers should see that the pupil’s name is clearly written in ink in the spaces above in every book issued 2. The following terms should be used in recording the condition of the book:New, Good, Fair, Poor, Bad This is an electronic version of the print textbook. Due to electronic rights restrictions, some third party content may be suppressed. Editorial review has deemed that any suppressed content does not materially a ffect the overall learning experience. The publisher reserves the right to remove content from this title at any time if subsequent rights restrictions require it. For valuable information on pricing, previous editions, changes to current editions, and alternate formats, please visit w ww.cengage.com/highered to search by ISBN#, author, title, or keyword for materials in your areas of interest. A_C7068_FM.4c 12/2/09 2:50 PM Page i F UNDAMENTALS J ™ OF AVA AP® Computer Science Essentials, Fourth Edition Kenneth Lambert and Martin Osborne Australia • Brazil • Japan • Korea • Mexico • Singapore • Spain • United Kingdom • United States A_C7068_FM.4c 12/2/09 10:48 AM Page ii Fundamentals of Java™: AP®Computer Science © 2011,2007Course Technology, Cengage Learning Essentials, Fourth Edition ALL RIGHTS RESERVED. No part of this work covered by the copyright herein may be Kenneth Lambert, Martin Osborne reproduced, transmitted, stored or used in any form or by any means graphic, elec- tronic, or mechanical, including but not limited to photocopying, recording, scanning, Executive Editor: Donna Gridley digitizing, taping, Web distribution, information networks, or information storage and Product Manager: Alyssa Pratt retrieval systems, except as permitted under Section 107or 108of the 1976United Development Editor: Ann Shaffer States Copyright Act, without the prior written permission of the publisher. Associate Product Manager: Amanda Lyons Editorial Assistant: Kim Klasner For product information and technology assistance, contact us at Cengage Learning Customer &Sales Support, 1-800-354-9706 Content Project Manager: Matthew Hutchinson For permission to use material from this text or product, submit all Marketing Associate: Julie Schuster requests online at www.cengage.com/permissions Director of Manufacturing: Denise Powers Further permissions questions can be emailed to [email protected] Manuscript Quality Assurance Lead: Jeff Schwartz Manuscript Quality Assurance Reviewers: SergePalladino, Danielle Shaw, John Freitas ISBN-13:978-0-538-74492-8 Art Director: Faith Brosnan ISBN-10:0-538-74492-8 Cover Designer: © Wing-ip Ngan, Ink design, Inc. Course Technology Cover Image: Indivision 07Grow A/Getty Images 20Channel Center Street Compositor: GEX Publishing Services Boston, MA 02210 USA Cengage Learning is a leading provider of customized learning solutions with office locations around the globe, including Singapore, the United Kingdom, Australia, Mexico, Brazil, and Japan. Locate your local office at: international.cengage.com/region Cengage Learning products are represented in Canada by Nelson Education, Ltd. To learn more about Course Technology, visit www.cengage.com/ coursetechnology To learn more about Cengage Learning, visit www.cengage.com Any fictional data related to persons or companies or URLs used throughout this book is intended for instructional purposes only. At the time this book was printed, any such data was fictional and not belonging to any real persons or companies. Printed in the United States of America 1 2 3 4 5 6 16 15 14 13 12 11 A_C7068_FM.4c 12/2/09 10:48 AM Page iii Overview of This Book iii Overview of This Book Sample lesson pages CHAPTER 7 C S ONTROL TATEMENTS C ONTINUED Objectives—At the beginning of each OBJECTIVES VOCABULARY Upon completion of this chapter,you should be able to: Arithmetic overflow chapter, objectives ■ Construct complex Boolean expressions using the Boundary condition logical operators &&(AND),||(OR),and !(NOT). Combinatorial explosion help you preview and ■ Construct truth tables for Boolean expressions. Complete code ■ Understand the logic of nested ifstatements and coverage review chapter topics. extended ifstatements. Equivalence class ■ Test ifstatements in a comprehensive manner. Extended ifstatement ■ Construct nested loops. Extreme condition Vocabulary Terms— ■ Create appropriate test cases for ifstatements Input assertion andloops. Logical operator This chapter-opening ■ Understand the purpose of assertions,invariants, Loop invariant list draws your and loop verification. Estimated Time: 5 hours LNoeospte vda riifansttatement Chapter 7 Control Statements Continued 253 attention to impor- whilSueypspNO(telereuom stpw.=teueo dtrur tealo!.aso=pdsp ree-irrt1n.io)tnn{(e“xEtnItnetr( )t;he upper limit: “); tant terms. stateTmhenist sc hinatprotedru ecxedp loinr eCs hmaoprteer a4d.v Tanocpeicds ainspcelucdtse olof gtihcea l coopnetrroa-lforQRifon(ournnbae uli(r=tsydL t ila=mos iws2teu; rra =;nd c (ne<i =n< t=)i Mnuanptephre.Lrsi;qm rintt+ ;+( )nd{)+;+){ tors, nested ifstatements, and nested loops. The chapter also Truthi fta(bnle % d == 0) describes strategies for testing programs that contain control state- break; Code Samples— ments. Programmers try to write programs that are free of logic } errors, but they seldom succeed. Consequently, they must test their proigfram(ds t>h oirnonuegrhLlyi mbietfo)re Plentiful examples releasing them—and even so, errors will still slip through. Notice that we Ssyays t“ewm.ilol”u tin.pstreiandt olnf (n + “ is prime”); “might.” Software is so incredibly complex that no significant soft}ware product has ever been show how to write rthelee aimsepdo frrteaen coef oefr rtoerssti;n hgo.wever, the situation would be much w}orsSle yoiswf tewerem .=so tourptep.aepddre iren.mtnp(eh“xEtasnIitnzetinr(g )t;he lower limit or -1 to quit: “); effective Java code. 7.1 Logical Operators Short Essays on and JNaOvaT i.n Tclhuedsees o tpherreaet loorgsi caarle oupseerda tino rtsh eeq Buoivoalleeannt einx pmreesasnioinngs Attoh atht ecN oEonnttgreloi slo htf h wIen obtreedhsra eAvsiNotrD o, fO iRf,, Special Topics—These RELIABILITY OF COMPUTER SYSTEMS The next time you step onto an airplane or lie down inside an MRI machine,you notes of interest 229 might ask yourself about the quality of the software system that helps to run them. There are several measures of software quality,such as readability,maintainability,cor- throughout the book 430 Unit 3 Arrays,Recursion,and Complexity Rreecltianbeislisty, asnhdo uroldb unsottn bees sc.o Bnfuuts peedr hwaitphs ctohrer emctonsets ism. pSoorfttawnat rme eisa scuorrere icst rief liitasb dileitsyi.gn and implementation are consistent with its specifications. That means that the soft- elaborate on impor- 11.13 Graphics and GUIs: Drawiwannagarely saMicst.u uHalollyw tdeiovpeers,l sewoh faStwt haitr eais c psaunep bpseo sceodrr etoc td ion, tahsis d seesncsrieb eyde ti ns twilhl abte wuen rhealivaeb lcea.lled tant programming The TurtleGraphicspackage used earlier in this the Dusuerirn wg athnets a tnhael yssoisft wpahraes eto o df os,oaftnwda frreo mde tvheilso pmmoednetl, wwee bcuoinlds taru mcto ad eml oofd ewlh oaft wthheat issues. cwwhieat hpe txaeanrm ya iiunmteoa gmthease t tirhceaalltal ytteh der e ppfrerenos bhhleaessm dt hroaef w ghnro.a wIpnh titochs i sm wsaeiincntditooaniwn, ETgsrmehioxvocifestttdlwsr yeGa ,alysrb roaCe uudp th wuh ttarihihiclnleles lgd e o saonapon.n gpfdOtaoe wulGryatrsUu rdieInsse i— tmssyi eagtthnycoa t siato tniinsldl , biimfe wpuelne rmhealeivanebt almeti.io sInut nimsd aeuyrns rrteeolfoilaedbc ltte ht ehif i usw sesee rhc’sao vnreed q bmuueiolstd tte h(lh eca owvrer-o tnhge multiple shapes in graphics programs such as those dis- ewxrpolnogr em coodnecle opft sth aen uds perro) gorra mwe- have built a model of the software that does not do cussed in Chapters 3 through 7. mwhinagt wteec hcnoirqreucetsly r ehqauveir eudn dtoerstood the user to require. Graphics and GUIs— deveFloorp e mxaomdeprlne ,gsreavpehriacls daepcpaldi-es ago,the Navy contracted with a software firm to build Ogivpet iyoonua lt sheec toiopnpsortu- Jathareav tpA aacs’iso nw mtFeepod so rainngwe ean it tnGf’s uU plgrI e rBcvaoipiomthumipsco sac nhpceaonpntt tbeeryxs t,s .e imnTdahigniseg s i msa nensdso asrghmeaasp lteloys cfrtaiiwnnaeha hs cqestditeiou caoeToshfilnhtrttl. eewahse kTcdte iarilahet olrriei ni ennnschdd gs h as o m savgymareepsdrasvai ttet sbeeepewrsermr hreaisteiliaolle cln t.ol psao pfOmia l sr bdttnou aihueneecsnettone e yeo wtte rbcsfr da eoit tn a sphotwt oehkeftie.r hetrmthw-r smoo yworoeefnv a s etrorosmaff ftgae wibgncayo t rcs.teah osuefen psmrer ieilssisa stebhilniealictstey .o iTofn hft hcetoeh sm exo -mmrfatewyor aocmrniaea li c nwsh ooicnfretekwre tTaadhri eneju rcsaatc s-f2ien5se,. done in the component’s paintComponentmethod, which the JVA Mcla rsusnics dwishceunsesvieorn t hoef scoofmtwpaor-e reliability in military applications can be found in nity to focus on top- nent’s window needs to be refreshed. The method repaintalsAol aanc cBoomrnpilnisgh,e“sC ao rmefpruetsehr uSnydsetre mpr oR-eliability and Nuclear War,” Communications of the gram control. For example, the programmer can call repAaCinMt,Vaoftleurm aen 3 i0m,aNguem obre rs h2a (pFee bhruasary 1987):112–131. Almost every textbook on com- ics related to modern ccohlaonrg aedn dp oresditriaown.s Tahlli so fm ietst hsohda pceasl las npda iimntaCgoemsp.onent, which pgpouaotiendrt spe tltahhceice cs ot ohm aspstoa cnrate sniset ’ sSs batuaradc ikeBgsar aoosunen c,doAm Gpifutt oefr Freirleia,bSielictyo nind cEodmitmioner(cUiaplp aepr pSliacdadtiloen Rs.iv Aer, graphics applications. shapTehs ea bftietrm tahpe yo fa rae Jdarvaaw gnr atpoh aic sw cinodnotewx.t Tdhoiess pnhoetn roemtaeinno NtnhJ :ei s P irnkefnnootriwmcena tHaioasn lla , a2fbo0or0ug2te )t,ifmuClah gbaeiptstm eaarn p4d.. That’s why the programmer must write a paintComponentmethod and use repaintfor window refreshes. Actually, the forgetful bitmap is not much of a problem, as long as paintComponent knows where to go to find information about the images and shapes to paint. We now consider some simple solutions to this problem. A Database of Circles To guarantee that all images and shapes are painted on each refresh, a graphics application must maintain information about them in a database. In this section, we show how to set up and manage a simple database of circles. In Chapter 6, we designed and implemented a class for representing circles. We then showed how to use this class in a sample application, which draws two circles in a panel. At startup, the panel instantiates the two circles and saves references to them in two instance variables. When the panel needs refreshing, the method paintComponentsends the appropriate messages to the two variables to paint the circles. (A note of caution: The Circleclass discussed here is different from the one introduced in Section 11.4, which uses a turtle graphics pen to draw itself.) When there are more than one or two circles to be accessed, we can store them in an array. The method paintComponenttraverses the array to paint all of the circles. In addition, we can use the array to perform other functions, such as search for a circle that contains the current mouse coordinates. Our first example program is a revised version of Example 6.5. This program displays two circles at startup and allows the user to move them around by dragging the mouse. In the new version of the program, an array of 10 circles replaces the two Circleinstance variables in the ColorPanelclass. The panel’s constructor instantiates the array and fills it with circles of equal size and randomly generated color. paintComponentpaints all of the circles. The method mousePressedin the class PanelListenersearches the array for a circle that contains the mouse A_C7068_FM.4c 12/2/09 10:48 AM Page iv iv Overview of This Book Overview of This Book Sample end-of-lesson pages 52 Unit 1 Getting Started with Java Section Exercises— EXERCISE2.7 Review questions at 1.Write the integer values of red,green,and blue for the following RGB colors: the end of each sec- a.white b.black tion check your c.highest intensity blue d.medium gray understanding of 2.Describe the roles and responsibilities of a frame,a panel,and a layout manager in a GUI application. essential concepts. 3.Where are panels displayed when a border layout is used to control their placement in a window? 4.Write a code segment that would be used to set the layout for adding panels to a 5-by-5 grid in a win- Summary—End-of- dow. You may assume that the panel’s content pane is named pane. chapter recap sum- SUMMARY marizes what you In this chapter, you learned: learned. ■ Java is the fastest growing programming language in the world. It is secure, robust, and portable. It is also similar to C++, the world’s most popular programming language. Chapter 7 Control Statements Continued 279 ■ The Java compiler translates Java into a pseudomachine language called Java byte code. Vocabulary Review— Bviyrtteu aclo mdea ccahnin be e( JrVunM o) nis a an yp rcoogmrapmut tehr atth bate hhaavse as VJliakOvea Ca v ciArotmuBaplU umtLearcA—hiRanneY iinnRtsetraepllvreedit.ee rT.whe Java ■ Java programs include variables, arithmetic expressions, statements, objects, messages, and End-of-chapter list methods. Define the following terms: reminds you to check ■ Ta hJarevea bdaesviecl ostpempse nint ethnev icroodnimnge nptr. oPcreosgs raarme medeirtsin sgh,o ABcuoorliumdthn ppmdiaaleyirnt yiagc tc, t ooaevnnnedtdrii oftrlinuoo nwnton ian gp rao pgrroagmrEI’asnmx pfto ururetmsm ianasegst ceortniodnition NOeusttpeudt laosospertion to ensure readability. Combinatorial explosion Logical operator Quality assurance your knowledge of ■ Java programs accomplish many tasks by sending mCEqeosumsiavpgaleelesten t coceo odcbleaj esccsotvs.e rEaxgaemples arLLeoo sooeppn divn-avraiarniatnt RTroubtuhs ttable important terms. ing text to the terminal window for output and recEeixvtienngd iendp uift dsatatate fmroemnt the keyboNaersdt.ed ifstatement ■ There are several user interface styles, among them terminal based and graphical based. Review Questions— VOCABULARYReview REVIEWQuestions End-of-chapter ques- Define the following terms: Applet Import statement WRITTENP QanUesESTIONS tions test your AByssteig cnomdeent operator Inetengvriarotendm deenvte (lIoDpEmW)enritt e a briefPS aoanursarwmceee rct eotrod eeach of the following questions. understanding of DOS development Interpreter 1. List the tShtraetee mloegnitcal operators. environment Java virtual machine (JVM) Terminal I/O interface chapter concepts. GHraacpkhinicgal user interface (GUI) JPuasnte-iln-time compilation (JIT) Variable 2. Construct a truth table for the expression P OR NOT Q. 282 Unit 2 The Next Step with Java PROJECT 7-7 Write a program to print the perimete3r. anSdu paproease oPf irse tcrtuaen galneds Qus iins gfa alslel . cWomhabti nisa ttihoen sv aolufe of the expression P AND NOT Q? heights and widths running from 1 foot to 10 feet in increments of 1 foot. Print the output in Programming headed, formatted columns. Projects—Numerous PROJECT 7-8 Write a program that uses a scanner to4 r.epWorrt itseo mane isftasttiasttiecms eanbto tuhta wt doirsdpsl aiyns awnh ientphuetr soern n-ot a given number is between a lower end-of-chapter tence (see Section 7.8). The outputs should be tbhoe unnudm mbienr aonf dw aonr dusp ipne rth beo suenndte mnacxe,, itnhcel uasvievrea.g Uese a logical operator in the condition. word length, and the length of the sentence. projects allow you PROJECT 7-9 to apply what you’ve Write a program that allows the user to search for a given word in a text file. The two inputs are the file’s name and the target word. If th5e. tarRgeewt irsi tneo tth feo iufndst,a ttheem pernotg irna mQ uoeusttpiounts 4 a t mo eusssea ag enested ifstatement. learned. to that effect. Otherwise, the program outputs the number of times that this word occurs in the file and the position where it is first encountered (counting from position 0). The program should ignore case when it compares words. PROJECT 7-10 Modify the example program of Section 7.8 so that the circle stops moving when the user clicks the mouse. When the user clicks the mouse again, the circle should resume moving. (Hint: Define a mouse listener class as shown in Chapter 6.) PROJECT 7-11 Add another circle to the program of Project 7-10. The second circle should be placed at the Critical Thinking— right margin of the panel at program startup, exactly opposite the first circle. Both circles should reverse direction when they hit a boundary. Each chapter con- PROJECT 7-12 cludes with an Use your knowledge of physics to make an interesting change to the program of Project 7-11. Set the initial directions of the two circles to angles other than horizontal (say, 120 degrees for exercise that asks you one and 30 degrees for the other). When a circle hits a boundary, it should rebound at the appro- priate angle. (Hint: The angle of reflection should equal the angle of incidence.) to use creative analy- CRITICALThinking sis to solve a problem. Read the sections of the ACM Code of Ethics that deal with designing and testing reliable computer systems. Prepare and present a report that explains how the ACM Code deals with this issue. A_C7068_FM.4c 12/2/09 10:48 AM Page v Preface v P REFACE T his text is intended for a complete course in programming and problem solving. It covers the material of typical Computer Science 1 courses at the undergraduate level, but it is intended for the high school audience. It covers all the A-level Advanced Placement (AP) Java topics. We present six major aspects of computing, some in standalone chapters and others spread across several chapters: 1. Programming Basics. This deals with the basic ideas related to solving problems with com- puters, including primitive data types, control structures, methods, algorithm development, and complexity analysis. 2. Object-Oriented Programming. OOP is today’s dominant programming paradigm. All the essentials of this subject are covered. 3. Data and Information Processing. Fundamental data structures are discussed. These include strings, arrays, files, and lists. The general concept of abstract data type is introduced, and complexity analysis is used to evaluate the running times of different implementations of algorithms. 4. Software Development Life Cycle. Rather than isolate software development techniques in one or two chapters, the book deals with them throughout in the context of numerous case studies. 5. Graphical User Interfaces and Event-Driven Programming. Many books at this level restrict themselves to character-based terminal I/O. The reason is simple. Graphical user interfaces and event-driven programming usually are considered too complex for beginning students. In this book, we circumvent the complexity barrier and show how to develop programs with graphical user interfaces with almost the same ease as their terminal-based counterparts. 6. Web Basics. The programming of Web pages with HTML and applets is introduced. Focus on Fundamental Computer Science Topics T here seem to be two types of introductory Java textbooks. The first emphasizes basic problem-solving and programming techniques, and the second emphasizes language features. This book takes the former approach and introduces Java features as they are needed to support programming concepts. In this way, we cover all the AP-required syntax without allowing the book to be syntax-driven. Some more advanced Java features, not part of the AP requirement, are covered in end-of-chapter sections and in the appendices. A_C7068_FM.4c 12/2/09 10:48 AM Page vi vi Preface Methods and Objects, Early or Late? O ccasionally, people argue about whether methods and objects should be introduced early or late in the first course. In Java, even the simplest program involves both methods and objects, so the problem really becomes one of how to introduce these concepts in a clear and meaningful manner from the outset. Starting with the first program, we show how to instantiate and send messages to objects. The book’s early chapters (2 through 5) focus on the use of objects, arith- metic expressions, control constructs, and algorithms in the context of short, simple programs. As programs become more complex, it becomes advantageous to decompose them into cooperat- ing components. With this end in mind, Chapter 6 shows how to develop systems of cooperating classes and methods. Thus, we take a pragmatic rather than an ideological approach to the ques- tion of when to introduce methods and objects, having complete confidence that students will master both by the end of the course. Revisiting Control Structures, Classes, and Arrays Y ears of teaching experience have demonstrated that beginning programming students struggle most with control structures, classes, and arrays. In this text, we have sought to soften the blow by introducing these ideas in two steps. First, a chapter gives an initial overview of a topic using the most basic features in simple but realistic applications. A follow-up chapter then revisits the topic to fill in and refine the details. New in This Edition A P computer science now has a single exam, which still covers the material typically offered in the first college course in programming and problem solving with Java. Starting in 2010, the exam will include the following items: 1. The Java constants Integer.MAX_VALUE and Integer.MIN_VALUE 2. Static variables and methods 3. Two-dimensional arrays 4. The java.util.List interface The first three items were already covered in the third edition of this book. This new edition has been updated to offer substantial coverage of two-dimensional arrays and the Listinterface. Two-dimensional arrays are explored in a new chapter (Chapter 12) on advanced array opera- tions. The List interface is examined in a new chapter (Chapter 14) on Java collections, which include the single collection class, java.util.ArrayList, which is covered by the AP exam. Chapter 14 also includes a non-required preview of other collections that would typically be covered in the next college-level course following this one. (Some of this material was formerly included in the old AP AB course.) The new edition also includes two entirely new chapters that provide examples of program- ming and problem solving in two contemporary areas of computing, media processing (Chapter 5) and networked applications (Chapter 15). The chapter on media computing provides an early

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.