head first java_second_edition

690
www.it-ebooks.info

Upload: sethnemesisra

Post on 22-Jun-2015

2.746 views

Category:

Documents


27 download

TRANSCRIPT

  • 1. www.it-ebooks.info

2. www.it-ebooks.infoTable of Contents (summary)Intro xxi 1Breaking the Surface: a quick dip 1 2A Trip to Objectville: yes, there will be objects27 3Know Your Variables: primitives and references 49 4How Objects Behave: object state affects method behavior 71 5Extra-Strength Methods: ow control, operations, and more95 6Using the Java Library: so you dont have to write it all yourself125 7Better Living in Objectville: planning for the future 165 8Serious Polymorphism: exploiting abstract classes and interfaces197 9Life and Death of an Object: constructors and memory management 235 10 Numbers Matter: math, formatting, wrappers, and statics 273 11 Risky Behavior: exception handling315 12 A Very Graphic Story: intro to GUI, event handling, and inner classes 353 13 Work on Your Swing: layout managers and components399 14 Saving Objects: serialization and I/O 429 15 Make a Connection: networking sockets and multithreading471 16 Data Structures: collections and generics 529 17 Release Your Code: packaging and deployment 581 18 Distributed Computing: RMI with a dash of servlets, EJB, and Jini 607 AAppendix A: Final code kitchen649 BAppendix B: Top Ten Things that didnt make it into the rest of the book659Index 677Table of Contents (the full version)i IntroYour brain on Java.Who is this book for?xxiiWhat your brain is thinkingxxiiiMetacognition xxvBend your brain into submission xxviiWhat you need for this book xxviiiTechnical editors xxxAcknowledgements xxxi ix 3. www.it-ebooks.info1Breaking the Surface Java takes you to new places.The way Java works 2Virtual Code structure in Java 7MachinesAnatomy of a class 8The main() method9Method Party()Looping 11 0 aload_0Conditional branching (if tests)131 invokespe-cial #1 Phrase-o-matic16 4 returnFireside chat: compiler vs. JVM 18CompiledYou BetShoot MeExercises and puzzles 20bytecode2A Trip to Objectville I was told there would be objects.Chair Wars (Brad the OO guy vs. Larry the procedural guy) 28Inheritance (an introduction) 31Overriding methods (an introduction)32Whats in a class? (methods, instance variables)34Making your rst object 36Using main()38Guessing Game code39Exercises and puzzles 42x 4. www.it-ebooks.info3 Know Your VariablesVariables come in two flavors: primitive and reference.Declaring a variable (Java cares about type) 50 24 size Primitive types (Id like a double with extra foam, please)51Java keywords53intReference variables (remote control to an object)54ctObject declaration and assignment55Dog objeObjects on the garbage-collectible heap57fidoArrays (a rst look) 59Exercises and puzzles63Dog reference4 How Objects BehaveState affects behavior, behavior affects state. Methods use object state (bark different)73pass-by-value meansMethod arguments and return types74pass-by-copy Pass-by-value (the variable is always copied)77 Getters and Setters79copy ofEncapsulation (do it or risk humiliation)80xUsing references in an array 83111 0 111 0000Exercises and puzzles88 0 00 00 XZ intintfoo.go(x);void go(int z){ } xi 5. www.it-ebooks.info5Extra-Strength Methods Lets put some muscle in our methods.e a build there gonnt Com gameWSink a Do Building the Sink a Dot Com game96Starting with the Simple Dot Com game (a simpler version) 98Writing prepcode (pseudocode for the game) 100Test code for Simple Dot Com 102Coding the Simple Dot Com game 103Final code for Simple Dot Com106Generating random numbers with Math.random() 111Ready-bake code for getting user input from the command-line 112Looping with for loops 114Casting primitives from a large size to a smaller size 117Converting a String to an int with Integer.parseInt()117Exercises and puzzles1186Using the Java Library Java ships with hundreds of pre-built classes.Analying the bug in the Simple Dot Com Game126ArrayList (taking advantage of the Java API) 132Fixing the DotCom class code 138Building the real game (Sink a Dot Com)140- Julia, 31, hand modelPrepcode for the real game 144Code for the real game 146boolean expressions151Using the library (Java API) 154Using packages (import statements, fully-qualied names) 155Using the HTML API docs and reference books158Exercises and puzzles161xii 6. www.it-ebooks.info7 Better Living in ObjectvillePlan your programs with the future in mind.Understanding inheritance (superclass and subclass relationships) 168Designing an inheritance tree (the Animal simulation) 170Make it Stick Avoiding duplicate code (using inheritance) 171Overriding methods172IS-A and HAS-A (bathtub girl) 177What do you inherit from your superclass? 180What does inheritance really buy you? 182Polymorphism (using a supertype reference to a subclass object) 183Rules for overriding (dont touch those arguments and return types!)190Method overloading (nothing more than method name re-use) 191Exercises and puzzles 1928 Serious PolymorphismInheritance is just the beginning.Some classes just should not be instantiated200Object o = al.get(id);Abstract classes (cant be instantiated)201Dog d = (Dog) o;Abstract methods (must be implemented)203d.bark(); Polymorphism in action206Class Object (the ultimate superclass of everything)208ObjectTaking objects out of an ArrayList (they come out as type Object) 211 D og t Compiler checks the reference type (before letting you call a method) 213 oobjecGet in touch with your inner object 214cast tPolymorphic references215 back tohe Object ObjectCasting an object reference (moving lower on the inheritance tree)216 dknow is a Dog we there. Deadly Diamond of Death (multiple inheritance problem)223DogUsing interfaces (the best solution!) 224Exercises and puzzles 230 xiii 7. www.it-ebooks.info9 Life and Death of an ObjectObjects are born and objects die.The stack and the heap, where objects and variables live 236 callsWhen someone od, this Methods on the stack 237 eththe go() m oned. HisWhere local variables live 238Duck is aband has been only reference for a Where instance variables live239 reprogrammed k.The miracle of object creation 240Duec different Duc Constructors (the code that runs when you say new) 241t ck objInitializing the state of a new Duck 243 dOverloaded constructors247Du Heap Superclass constructors (constructor chaining) 250 ck objectInvoking overloaded constructors using this()256ing the d is assigned a new Duck object, leav . That Life of an object258 original (first) Duck object abandoned Garbage Collection (and making objects eligible) 260first Duck is toast..Exercises and puzzles266Static variablesare shared by 10 Numbers MatterDo the Math.all instances ofa class. static variable: iceCream Math class (do you really need an instance of it?) 274kid instance twokid instance onestatic methods 275instance variables: static variables 277one per instanceConstants (static nal variables)282Math methods (random(), round(), abs(), etc.)286static variables:one per class Wrapper classes (Integer, Boolean, Character, etc.)287Autoboxing 289Number formatting294Date formatting and manipulation 301Static imports 307Exercises and puzzles310xiv 8. www.it-ebooks.info 11 Risky BehaviorStuff happens.Making a music machine (the BeatBox)316What if you need to call risky code?319 an excepti owson hr2 ba Exceptions say something bad may have happened... 320 cktThe compiler guarantees (it checks) that youre aware of the risks321class Cow {Catching exceptions using a try/catch (skateboarder)322 class Bar {void moo() { void go() {if (serverDown){ }moo();1}explode();Flow control in try/catch blocks326 } int stuff() {}x.beep(); } } calls risky method The nally block (no matter what happens, turn off the oven!) 327Catching multiple exceptions (the order matters)329your code class with a risky method Declaring an exception (just duck it) 335Handle or declare law 337Code Kitchen (making sounds)339Exercises and puzzles 34812A Very Graphic StoryFace it, you need to make GUIs. class MyOuter{ class MyInner {void go() { Your rst GUI 355 }Getting a user event357}Implement a listener interface358 }Getting a buttons ActionEvent360Putting graphics on a GUI 363The outer and inner objectsare now intimately linked.Fun with paintComponent() 365 oute rThe Graphics2D object 366Putting more than one button on a screen370 objects on the These two a special bond. The innerInner classes to the rescue (make your listener an inner class) 376 heap have use the outersinner can (and vice-versa). Animation (move it, paint it, move it, paint it, move it, paint it...)382variables Code Kitchen (painting graphics with the beat of the music) 386Exercises and puzzles 394xv 9. www.it-ebooks.info13Work on your SwingSwing is easy. Swing Components400Components inLayout Managers (they control size and placement) 401the east and Three Layout Managers (border, ow, box)403west get theirth.BorderLayout (cares about ve regions)404 preferred wid FlowLayout (cares about the order and preferred size) 408Things in theBoxLayout (like ow, but can stack components vertically) 411north and The center getsJTextField (for single-line user input) 413south get their whatevers left. JTextArea (for multi-line, scrolling text)414preferred height. JCheckBox (is it selected?) 416 JList (a scrollable, selectable list) 417 Code Kitchen (The Big One - building the BeatBox chat client) 418 Exercises and puzzles 42414 Saving ObjectsObjects can be flattened and inflated.serialized Saving object state 431 Writing a serialized object to a le432 Java input and output streams (connections and chains)433 Object serialization434ions?Any questImplementing the Serializable interface Using transient variables 437 439 deserializedDeserializing an object 441 Writing to a text le 447 java.io.File452 Reading from a text le 454 Splitting a String into tokens with split() 458 CodeKitchen 462 Exercises and puzzles 466xvi 10. www.it-ebooks.info 15 Make a Connection Connect with the outside world.Socket c n to port 5o0nection on the serv 00Chat program overview 473196.164.1.10er atConnecting, sending, and receiving4743 Network sockets 475 TCP ports 476 Reading data from a socket (using BufferedReader) 478 Writing data to a socket (using PrintWriter)479 ClientServernnection Writing the Daily Advice Client program 480Socket oco he client t Writing a simple server 483back t 64.1.100, at 196.1242 Daily Advice Server code484 port 4Writing a chat client 486 Multiple call stacks490 Launching a new thread (make it, start it)492 The Runnable interface (the threads job) 494 Three states of a new Thread object (new, runnable, running)495 The runnable-running loop 496 Thread scheduler (its his decision, not yours) 497 Putting a thread to sleep 501 Making and starting two threads 503 Concurrency issues: can this couple be saved? 505 The Ryan and Monica concurrency problem, in code506 Locking to make things atomic 510 Every object has a lock 511 The dreaded Lost Update problem 512 Synchronized methods (using a lock) 514 Deadlock! 516 Multithreaded ChatClient code 518 Ready-bake SimpleChatServer 520 Exercises and puzzles 524 xvii 11. www.it-ebooks.info16Data StructuresSorting is a snap in Java.Collections533Sorting an ArrayList with Collections.sort() 534List012 3 Generics and type-safety 540Sorting things that implement the Comparable interface 547Sorting things with a custom Comparator552The collection APIlists, sets, and maps 557Set Avoiding duplicates with HashSet 559Overriding hashCode() and equals() 560HashMap567Using wildcards for polymorphism 574Map BallBall1Ball2 FishCar FishCarExercises and puzzles576 17 Release Your CodeIts time to let go.classesDeployment options 582comKeep your source code and class les separate584101101foo10 110 10 11 0Making an executable JAR (Java ARchives) 585MyApp.jar 001 10001 01Running an executable JAR586 MyApp.classPut your classes in a package! 587Packages must have a matching directory structure589 Web Server Compiling and running with packages590 JWS Lorper iureCompiling with -d591 eugue tat vero conse euguero- Making an executable JAR (with packages) 592MyApp.jar MyApp.jnlp MyApp.jarJava Web Start (JWS) for deployment from the web 597How to make and deploy a JWS application 600Exercises and puzzles601xviii 12. www.it-ebooks.info 18Distributed ComputingBeing remote doesnt have to be a bad thing.Client Server Java Remote Method Invocation (RMI), hands-on, very detailed614Servlets (a quick look) 625 RMI STUB RMI SKELETONEnterprise JavaBeans (EJB), a very quick look 631Jini, the best trick of all 632 See r C li ent helper rvice help Service objec tC liBuilding the really cool universal service browser636ent objectThe End 648AAppendix A The final Code Kitchen project.BeatBoxFinal (client code)650MusicServer (server code) 657BAppendix BThe Top Ten Things that didnt make it into the book.Top Ten List660 iIndex 677xix 13. www.it-ebooks.infohow to use thOIS bookIntro-the bl>Yli,,~ ,~tiOf: DID :h11feel something, and keeps your learning from captions for the photos. Groaning over a bad being too connected to a particular place. joke is still better than feeling nothing at all.Make this the last thing you read before. . Type and run the code.bed. Or at least the last challengIng thing.Type and run the code examples. Then youPart of the learning (especially the transfer can experiment with changing and improvingto long-term memory) happens afleryou put the code (or breaking it, which is sometimesthe book down. Your brain needs time on the best way to figure alit whats reallyits own , to do more processing. If you put inhappening). For long examples or Ready-bakesomething new during that processing-time,code, you can download the source files fromsome of what you just learned will be lost. headfirstjava.corn you are here. xxvII 20. www.it-ebooks.infohow to use this bookWhat you heed for this book:You do not need any other development tool. such as an IntegratedDevelopment Environment (IDE). We strongly recommend that you notuse anything but a-basic text editor until you complete this book (andespecially not until after chapter 16). An IDE can protect you from some ofthe details that really matter. so youre much bener off learning from thecommand-line and then. once you really understand whats happening.move to a tool that automates some of the process. SmlNG UP JAVA - - - - - - - - - - - - - - - - - - , If you dont already have a 1.5 orgreater Java 2 Standard Edition SDK (Software Development Kit), you need it. If youre on Linux, Windows, or Solaris, you can gellt for free from java.sun.com (Suns websile forJava developers). It usually takes nomore than two clicks from the main page togel to the J2SE downloads page . Get the latest non-beta version posted. The SDK includes everything you need tocompile and run Java. If youre running Mac OS X10.4. the Java SDK isalready installed. Its partof OS X, and you dont have todo anything else. If youre on an earlier version of OS X. you have an earlier version ofJava that will wor1< for95% of the code in this book. Note: This book is based on Java 1.5, but forstunningly unclear mar14 rerumSourceOutput (code) oCreate a sourceCOIMpiler VirtualMachhudocument. Use anestablished protocol The compiler creates a Run your document new document, coded(In th is case, the Java t hro ugh a source code into Java bytecode.language). Your friends dont have complier. The complierAny device capable of checks for errors and running Java will be able a physical Java Machine, wont let you compile to Interpret/translatebut they all have a until Its satisfied that this file into somethingvirtual Java machine everything will run It can run .The complied(implemented In correctly.bytecode is platform- software) running inside Independent.their electronic gadgets. The virtual mach ine reads and runs thebytecode.2 chapter 1 27. www.it-ebooks.infodive In A Quick DipWhat youll do in Jav~ Youll type a source code file, compile It using the Javac complier, then run the complied bytecode on a .Java virtual machine.java.awl;Method Party()r:.pon java.awtevenL; oaload_O:tass Party (1Invokespedal #1 PartY at Tims1Fl3me r=IlllW FtameO; 4 returnLabell =new LabellParty atTlms1;B tton b =new ButIoII(You ber) ;Method void bulidInviteOButton C =te Button("Shool me): onew #2 Panel p =new PanelO; Virtual p.addO):3 dup} II more code here...4 Invokespec1al #J o oOutput(code)Run the program bystarting the Java VirtualMachine (JVM) with theParty.doss file. The JVMType your source code.translates the bytecodeinto something theSaveas: Party.Javaunderlying platformComplied code: Party.dass understands, and runsyour program . (NoU: U,is is ~ ....e.l"tto be d h-kial... 101CII1500 ..G) .z:. .5 10001ft G)500 1ft 1ftlIlI0 UJava 1.02 Java 2 Java 5.0250 classes 500 classes (wnloKs 1.2 .. t~) (wrsloKs 1.5 attd up)Slow. A little faster.2300dasses 3500 classesCute name and logo. More capable, friendlier. Much faster. More power, ~/e, toFun to use. Lots of Becoming very popultJr. Can (sometimes) run at develop with.bugs. Applets are Better GUI code.native speeds. Serious,Besides adding more than athe Big Thing.powerful. Comes in three thousand additional classes,flavors: Micro Edition (J2ME), Java 5.0 (known as"Tiger")~> Standard Edition (J2SE) andadded major changes to....l-~ Enterprise Edition (J2EE). the language itself, making 2a.0Becomes the langutlge of it easier (at least in theory) III s:~ chola for new enterprise for programmers and giving o.s01(especially web-based) andmobile applications. it new features that were popular in other languages.:c ~ 29. www.it-ebooks.infodive In A Quick Dip Look how easy It Try to guess what each line of code Is doinq.; is towrite Java.(answersare on the next page), .int size= 27; String name = UFido"; Dog rnyDog = new Dog(name, size); x = size - 5j if (x < 15) rnyDog.bark(8); while (x > 3) { myDog.play(); } .int [ ] nurnList = {2,4,6,S}; System. out. print ( u Be110" ) ; System.out.print(UDog:U + name); String nurn = US"; int Z = Integar.parselnt(nurn); -:.....-y { readTheFila(UrnyFile.txt H) ; } catch(FileNotFoundException ex) { syetem.out.print(UFile not found."); }once again that the changes were so dramatic that aQ..:I see Java 2 and Java 5.0, but was there a Java 3 new name was needed (and most developers agreed), so-.d 41 And why Is It Java 5.0 but not Java 2.07 they looked at the options. The next number In the namesequence woul d be 3: but caIIing Java 1.5 Java 3 seemedmore confusing, so they decided to name It Java 5.0 to:The joys of marketing... when the version of Javamatch the "5~ in version "l.S~ed from 1.1 to 1.2, the changes to Java were so So, the original Java was versions 1.02 (the first officialrna t ic that the marketers decided we needed a whole release) through 1.1 were just "Java" Versions 1,2,1.3, and "name: so they started calling It Java 2, even though1.4 were "Java 2~ And beginning with version 1.5, Java isactual version of Java was 1.2. But versions 1.3 and 1.4called "Java 5.0~ But youll also see it called "Java 5 (withoutftfe still considered Java 2. There never was a Java 3 or the ",0") and "Tiger" (its original code-name). We have no~_ Be9inning with Java version 1.5,the marketers decidedidea what will happen with the next release... you are here ~ 5 30. www.it-ebooks.info.why Java Is coolpen your pencil answersDont wotry about whether you understand any ofthis yetilook how easy ItEverything here Is explained in great detall!n the book, mostIs towrite Java.within the first 40 pages).If Java resembles a language youveused in the past, some of th is will be simple. If not, dont worryabout it. Wellget there...int size::; 27;String name = #FidoHjdett.rt ~ ~~ of l~,)lW1"aridbl, Nlr.ed ~ ..c ~r.d ~i" it ~ ."Iot "FidoDog myDog ::; new Dog (name, size);du.lm .1 _D~ v~blc..yD~ a.v:l ~U ~ _ D~ 1Iii~ (~ ..rod siux = size - 5;wbu-att".fro,. 2.1 (.,,,Iot of siu) ~,J it to ~ y~bl, ...a",l1.if (x < 15) myDog .bark(8);while (x > 3) {myDog.play ( l ;}intl] numList = {2,4,6,8};System.out.print(HHello R );System.out.print(HDogl U + name);String num ::; US";fnt z = Integer.parselnt(num);try {try to do ~i~ ...~ybc ~ thi~ IlI(l"t try~ isJ,t ~.lI.Ued to ~ . ~ ~ tot file IIolMCll "..yFile.bi (ar .Ii. lust TRy 1;0 ~e.ld ~ fild}..lIS! be the erod of ~ "I:.h~ to try", so r ~lOC.U f" te 12) x = )( - 1;.. Each statement must end in asemicolon.x=x+1; for (int x ee 0; x < 10; x = x + 1) (System.out.print("x is now+ x);II.. A single-line comment beginswith two forward slashes.e do solttethlttQ uttder this CO.,dltlonBranching: If/else testsx = 22;II this line disturbs meif(x== 10) 1.. Most white space doesnt maner.System.out.print("x mUSt be 10"); x 3 else {System.out.print("x isn t lO ll);.. Variables are declared with aname and a type (youll learn aboutifx < 3)& (name.equals("Dirk ll ) )all the Java types In chapter 3).System.out.println(~Gently ");int weight;Iitype: int, name: weightSystem .out.print("this line runs no matter what ll ) ;.. Classes and methods must bedeflned within a pair of curly braces.public void go ( ) ( II amazing code here}10chapter 1 35. www.it-ebooks.info dive In A Quick Dipwhile (more Balls == true) { keepJugg/ing() ; } ShMple boolean tests .You can do a simple boolean test by checkingLoopit1g a.,d loopi.,g atd... the value of a variable, using a comparison operator including:Java has three standard Looping constructs: uihile; do-iahile, and for. Youll get the full loop scoop later< (less than)in the book, but not for awhile, so lets do whi~for > (greater than) now.The syntax (not to mention logic) is so simple =(equality) (yes, thats two equals signs)youre probably asleep already. As long as someNotice the difference between the assignmentcondition is true, you do everything inside theoperator (a single equals sign) and the equalsloop block. The loop block is bounded by a pair of operator (two equals signs). Lots of programmerscurly braces, so whatever you want to repeat needs accidentally type when they want -. (But notto be inside that block. you.)The key to a loop is the conditional test. lnJava, a iot x ~ 4; II assign 4 to xconditional test is an expression that results in awhile > 3) {(xboolean vaJue-in other words, something that is II loop code will run becauseeither true or false.II x is greater than 3lfyou say something like , "While i.aCnamlnTMTubx = x-I; II or wed loop foreveris true; keep scooping", you have a clear booleantest. There either is ice cream in the cub or thereinc z = 27; IIisnt. But if you were to say. "While Bob keep while (z =~ 17)scooping" , you dont have a real test, To make II loop code will not run becausethat work, youd have to change it to somethinglike. "While Bob is snoring... ~ or "While Bob is notII z is not equal to 17wearing plaid..." you are here ~11 36. www.it-ebooks.infoJava basicsExall1ple of a while looppublic class Loopy {Q: Whydoes everything have public static void main (String[] args) (to be In a dass7 int x .. 1;A: ~avais an object-oriented(00) language. Its not Iikethe System.out.println("Before the Loop"); while (x < 4) { System.out.println("In the loop");old days when you had steam- System.out .prlntln("Value of x is " + x);driven compliers and wrote onemonolithic source file with a pile x = x + 1;of procedures. In chapter 2 youll )learn that a class Is a blueprint forSystem.out.println("This is after the loop");an object, and that nearly every-thing in Java Is an object.Q:Do I have to put a main In% java Loopyevery class I write1Before the LoopIn the loopA:Nope .A Java prog rammight use dozens of classes (evenVa.lueIn the loop ot x is 1hundreds), but you might only Va.lue of x i8 2have one with a maIn method-In th8 loopthe one that starts the program Value of x is 3running.You might wrIte testThis is aft.r the loopclasses, though, that have mainmethods for testing your otherPOI~classes,, - - - - - - BULLD ----------,Q: In my other language I can Statements end ina semicolon;do a boolean test on an Integer.In Java, can I say something like: Code blocks are defined by apair of cu~y braces { }int x .. 1; Declare an int variable with a name and a type: Intx;while (J&:) ( The assignment operator Is one equals sign =A: No.A boolean and an integer are not compatible types In The equals operator uses two equals signs == Awhile loop runs everything within its block (defined by cu~y Java. Since the result of a condi- tional test must be a boolean, the braces) as long as the conditional test Is true. only varIable you can directly test If the conditional test is fa1S8, the while loop code block wont (without using a comparison op- run, and execution will move down to the code Immediately erator) Is a boolean. For example, efterthe loop block. you can say: boolean isBot true; Put a boolean test Inside parentheses: while (x =4)( }while (llIHot) ( )12 chapter 1 37. www.it-ebooks.info dive In A Quick DipConditlo"al bra"chl"QJava, an if test is basically the same as the boolean test in a le loop - except instead of saying, ~UJhile theres still beer.,",u ]] say, ~iftheres still beer.,"cLa s s I f Test (public static void main (String[) args) {int x = 3; i f (x == 3) System.out.println("x must be 3 H ); System.out .println( "This runs no matter what");, java IfrestJI: must be 3This runs no matter what Glv~n the output:The code above executes the line that prints "x must be 3" onlyif the condition (x is equal to 3) is true. Regardless of whether% javaDooBeeits true, though, the line that prints, "This runs no matter what"DooBeeDooBeeDo~ill run. So depending on the value of x; either one statementor two will print out. FJIIln th~ missing code:But we can add an else to the condition, so that we canpublic class DooBee {say something like, "Iftberes still beer, keep coding, else public static void main (StringO args) I(otherwise) get more beer, and then continue on..." intx=l;::lass IfTest2 { while (x < _ _ }{ public static voidmain (String!) a rqs ) ( System.out. ("Doo"); int x = 2; System.out.(MBee");i f (x == 3) System.out.println("x must be 3 H ) ; x = x + 1; else (}System.out.println("x is NOT JH);If(x== _ _ }{H System.o ut.pri nt("Do };System.out.println("This runs no matter what "); I } } , java Iflest2IIis ~ 31hi1 runs no matter what you are here ~13 38. www.it-ebooks.infoserious Java appCoding aSerious fushtessApplicatfottLets put all your"new Java skills to good use withsomething practical. We need a class with a mains); an intand a String variable. a whik loop, and an if test. A littlemore polish, and youll be building that business back-end in no time. But beJoreyou look at the code on thispage, think for a moment about how youwould code thatclassic childrens favorite, "99 bottles of beer." pUblic class BeerSong ( public static void main (String[) args) (int beerNum 99;String word ~ "bottles"; while (beerNum > 0) I if (beerNum == 1) ( word - "bottle H ; II s i ng ul a r , as inONE bo ttl e . System.out.println(beerNum + " H + word + " of beer on the wall H ) ; System.out.println(beerNum + " H + word + " of beer."); System.out.println("Take one down. H ) ; System .out .println( "Pass it around. ") ; beerNum = beerNum - 1;if (beerNum > 0) ( System.out .println(beerNum + " H + word + " of beer on che wall H );else ( System.out.println("No more bottles of beer on the wall H ) ;) II end else f II end while loop ) II end main method II en~ class Theres stili one little flaw In our code. It complies and runs. but the output Isnt 100% perfect. See If you can spot the flaw, and fix It.14chapter 1 39. www.it-ebooks.infodive In A Quick DipBobs alarm clock rings at 8:30 Monday morning, just like every other weekday.But Bob had a wild weekend, and reaches for the SNOOZE button.And thats when the action starts, and the Java-enabled appliancescome to life.First, the alarm clock sends a message to the coffee maker* "Hey, the geekssleeping in again , delay the coffee 12 minutes."The coffee maker sends a message to the Motorola> toaster, "Hold the toast, Bobs snoozing."(- The alarm clock then sends a message to Bobs Nokia Navigator cell phone, "Call Bobs 9 oclock and tell him were running a little late."Finally, the alarm clock sends a message to Sams (Sam is the dog) wireless collar, with the too-familiar signal thatmeans, "Get the paper, but dont expect a walk."A few minutes later, the alarm goes off again . And again Bobhits SNOOZE and the appliances start chattering. Finally,the alarm rings a third time. But just as Bob reaches for thesn ooze button, the clock sends the "jump and bark" signal to Samscollar. Shocked to full consciousness, Bob rises, grateful that hisJavaskills and a Little trip to Radio Sbackn< have enhanced the dailyroutines of his life.His toast is toasted.His coffee steams.His paper awaits.Just another wonderful morning in TheJava--ErUlbled HOMSB.You can have aJava~enabledhome. Stick with a sensible solution using Java,Ethernet, andJini technology. Beware of imitations using other so-called "plugand play" (which actually means "plug and play with it for the next three daystrying to get it to work") or "p ortable" platforms. Bob s sister Berry Died one ofthose others, and the results were, well, not very appealing, or safe.Bit of a shame about her dog, too...Could this story be true? Yes and no.While there are versions of Java running in de-vices Including PDAs cell phones (especially cell phones), pagers, rings, smart cards,,and more -you might not find a Java toaster or dog collar. But even jf you cantfind a Java-enabled version of your favorite gadget. you can stili run it as if it were aJava device by controlling it through some other Interface (say, your laptop) that isrunnIng Java.This Is known as the Jini surrogate architecture. Y~ you con have thatgeek dream home.IPmulticast If youre gonna be all picky about protocolyou are her e ~ 15 40. www.it-ebooks.infolets write a programTry my new phrase-a-matic and youll be a slick talkerjust like the boss orthose guys in marketing. public class PhraseQlatic ( public static void main (String(l args) {/ / iliaD thNt sets of words to choose from. leW yoar own!String[] wordListOne ::: {"24/7" /multi- Tiar","30,OOO foot", "B-to-B" , "win-win" , "front- end" , "web- based" , "pervasive", "smart", "six- sigma", " cri tical -path" , "dynamic"} jStrinq[] wordListTwo ::: I "empowered", "sticky", "value-added.", "oriented", "centric", "distributed", "clustered", "branded", "outaide-the-box", positioned, "networked", " f ocused" / "leveraged", "aligned", "targeted", "shared" / "cooperative", "accelerated"};Strinq[] wordListThree = {"process", "tipping- OK, so the beer song wasnt really a serious business application. Still need something point", "solution", "architecture", "core competency" , practical to show the boss? Check out the "strategy", "mindshare", "portal" , "apace" / "vision", Phrase-O-Matlc code.~adigm", ~ssion"}; / / find out !low many word. aN In ...d11btiot one.Lenqth " wordListOne . length;int twoLength " wordListTwo .length;int threeLength=wordListThree.lenqthj/ / generate .... random numbersint randl :lII (int) (Math.random() " ooeLenqth) jint rand2 ::: (int) (Math .randomO twoLength);int rand3 " (int) (Math.randa:n() " threeLength);O //now build a pllrueString phrase" wordListOne [randl] + " " +wordListTwo[rand2] + " " + wordListTbree[rand3] ; / / print oat the phra..Sys.tem.out.println("What we need is a " + phrase);}16ch apter 1 41. www.it-ebooks.info dive In A Quick DipPhrase.. O. Matlc.low Itworks,In a nutshell, the program makes three lists of words, then randomly picks one wordfrom each of the three lists; and prints out the result, Dont worry if you dont under-m.nd exactly whats happening in each line. For gosh sakes, youve got the whole book~d of you, so relax. This isjust a quick look from a 30,000 foot outside-the-boxa.rgeted leveraged paradigm.i. The first step is to create three String arrays - the containers that will hold all the-..ords . Declaring and creating an array is easy; heres a small one:bch word is in quotes (as all good Strings must be) and separated by commas. For each of the three lists (arrays), the goal is to pick a random word, so we have know how many words are in each list, If there are 14 words in a list, then we needrandom number between 0 and 13 (Java arrays are zero-based, so the first word is atition 0, the second word position I, and the last word is position 13 in a 14-elementwhat we need here Is a ~) . Quite handily, ajava array is more than happy to tell you its length. You just to ask. In the pets array, wed say.sat z =: pets . length ; pervasive targeted z would now hold the value 3. process, . We need three rand~m numbers. Java ships out-of-the-box, off-the-shelf, shrink-dynamic outside- the-box tipplng- pped, and core competent with a set of math methods (for now, think of them as point ctions). The random () method returns a random number between 0 and not-te-l , so we have to multiply it by the number of elements (the array length) in the were using. We have to force the result to be an integer (no decimals allowed!) so smart distributed put in a cast (youll get the details in chapter 4). Its the same as ifwe had any float- core competencypoint number that we wanted to convert to an integer.~t z (int) 24.6; 24/1 empowered mindshareow we get to build the phrase, by picking a word from each of the three lists,smooshing them together (also inserting spaces between words). We use the ,,+n 30,000 fool win-win rator, which concatenaus (we prefer the more technical S1TU>OShes) the String objects visionether. To get an element from an array, you give the array the index number (posi-- n) of the thing you want using:SUinq s " pet. [0 l : / / s is now the String "FiOO"stx-slqrna net-.... + " " + "is a dog"; / / is now "Fido ill a dog" worked portal5. Finally, we print the phrase to the command-line and... voila I Wen in marketing. you are here ~ 17 42. www.it-ebooks.infothe complier and the JVMFireside ChatsTon1gb.ts Talk: The compller and ~~e JVM battle over the question."Whos more lmportaJlU" !he Java Vlrtual Machine The Complier What, are you kidding? HELLO. I amJava. Im the guy who actually makes a program run. The compiler just gives you a file. Thats it. Just a file. You can print it out and use it for wall paper, kindling, lining the bird cage whateuer, but the file doesnt do anything un- less Im there La run it.I dont appreciate that tone. And thats another thing. the compiler has no sense of humor. Then again. if ycm had to spend all day checking nit-picky little syntax violations...Excuse me, but without me, what exactlywould you run? Theres a TMSonJava wasdesigned to use a bytecode compiler, for yourinformation. IfJava were a purely interpretedlanguage, where-s-at runtime-s-the virtualmachine had to translate straight-from-a-text-editor source code, a java program wouldrun at a ludicrously glacial pace. javas had achallenging enough time convincing peoplethat its finally fast and powerful enough for Im not saying youre, like, complmly useless. mostjobs. But really, what is it that you do? Seriously. I have no idea. A programmer could just write bytecode by hand, and Id take it. You might be out ofajob soon, buddy.Excuse me, but thats quite an ignorant (notto mention arrogant) perspective. While itis true that-tJuoretically--you can run anyproperly formatted bytecode even if it didntcome out of a Java compiler, in practice thatsabsurd. A programmer writing bytecode byhand is like doing your word processing bywriting raw postscript. And I would appreciateit if you would not refer to me as "buddy." (I rest my case on the humor thing.) But you still didnt answer my question, what do you actually do?18 chapter 1 43. www.it-ebooks.info dive In A Quick DipThe Java Virtual Machine The Compiler Remember thatJava is a strongly-typed lan- guage, and that means I cant allow variables to hold data of the wrong type. This is a crucial safety feature, and Im able to stop theBut some still get through! I can throw Class- vast majority of violations before they ever getCastExceptions and sometimes I get peopleto you. And I also-trying to put the wrong type of thing in anarray that was declared to hold somethingelse, and- Excuse me, but I wasnt done. And yes, there are some datatype exceptions that can emerge at runtime, but some of those have to be allowed to support one ofJavas other impor- tant features--dynamic binding. At runtime, aJava program can include new objects that werent even known to the original program- mer, so I have to allow a certain amount of flexibility. But my job is to stop anything that would never-could never-succeed at run- time. Usually I can tell when something won t work, for example, if a programmer acciden- tally tried to use a Button object as a Socket connection, I would detect that and thusOK. Sure. But what about security? Look at all protect him from causing harm at runtime.the security stuff I do , and youre like, what,checking for semicolons? Oooohhh big securityrisk ! Thank goodness for youl Excuse me, but I am the first line of defense, as they say. The datatype violations I previous- ly described could wreak havoc in a program if they were allowed to manifest. I am also the one who prevents access violations, such as code trying to invoke a private method, or change a method that - for security reasons - must never be changed. I stop people from touching code theyre not meant to see, including code trying to access another class critical data. It would take hours, perhaps days even, to describe the significance of my work.Whatever. I have to do that same stuff too,though, just to make sure nobody snuck inafter you and changed the byte code beforerunning it. Of course, but as I indicated previously, if I didnt prevent what amounts to perhaps 99% of the potential problems, you would grind to a halt. And it looks like were out of time, so well have to revisit this in a later chat.Oh, you can count on it. Buddy.you a re here ~ 19 44. www.it-ebooks.infoexercise: Code MagnetsCode MagnetsA working Java program is all scrambled upon the fridge. Can you rearrange the codesnippets to make a working Java programthat produces the output listed below?Some of the curly braces fell on the floor if (JC r .. x-I; System. Out . . pr.l n t(,,_,,);while (x > 0) { ~ I., java Shufflela-b c-d 45. www.it-ebooks.info dive In A Quick Dip Bpublic static void main(String [] args)int x = 5; while ( x > 1 ) x = x-I; "BE the oomriler if ( x < 3) { System.out.println(~small X~)i Each of the JIlVll files on this pagerepresents 11 complete source file.Your job is to pIa} cotJ1Piler and determine whether each of thesefiles will cottlPile. If-theywont cottlPile. howwoald you l"lX them? A cclass Exerciselb {~_ass Exerciselb {int x 5; public static void main(String [) args) while ( x > 1 )int x " Ii x =x - Ii while ( x < 10if ( x < 3) (if ( x > 3) ( System.out.println(~small x~);systam.out.println(~big X")iyou are here ~21 46. www.it-ebooks.infopuzzle: crossword12J 4S f-I Ja~Cr~ss t. O II ~ --- 8- 910 ~l..- lets give your right brain somethIng to do. 2I-- Itsyour standard crossword, but almost allf- ~I--13 of the solution words are from chapter 1.Just4 5 6 to keep you awake we alsothrew in a few , (non-Java) words from the high-tech world.- --- ~ 189AcrossI-20-4. Command-line invoker6. Back again?L---bL218. Cant go both ways 1 9. Acronym for your laptopS power12. number variabletype13. Acronym for a chipDown14. SaysomethIng1. Not an integer (or _ _ your boat)18. Quite a crew of characters2. Come back empty-handed19. Announce a new class or method3. Open house21. Whatsa prompt good for?5. ThIngs holders7. Until attitudes improve10. Sourcecode consumer11 . Can pin it downt13. Dept. of LANJockeys1S. Shocking modifier16. Justgona haveone17. How to get things done20. Bytecode consumer22chapter 1 47. www.it-ebooks.info dive In A Quick Dip A short Java program is listed below. One block of the program is missing. Your challenge is to match the candidate block of code (on the left),with the output that youd see if the block were inserted. Not all the lines of output will be used, and some of the lines of output might be used more than once. Draw lines connecting the candidate blocks of code with their matching command-line output. (The answers are at the end of the chapter).class Test {public static void main (String [) args)int x0;int y = 0;while x < 5 ) System.out.print(x + "" + y +" "); x = x + 1;candidates:Possible output:00 11 21 32 42lJ. 21 32 42 5300 11 23 36 41002 14 25 36 41 you are here ~23 48. www.it-ebooks.infopuzzle: Pool Puzzle class PoolPu2zleOne { public static void main(String (I arga) { int x = OJ P~lpuzzle while ( ) { Your job is to take code snippets from thepool and place them into the blank lines in the code. You may not use theif ( x < 1 ) { same snippet more than once,and you wont need to use all the snip-}pets. Your goal is to make a cia 5S thatwill compile and run and produce the output listed. Dont be fooled-this ones harder than it looks.if () { Output }if ( x1 ) {%java PoolPuzzleOnea noise }if ){annoysan oyster}System.out.println("");} }Note: Each snippetfrom the pool can beused only oncel24chapter 1 49. www.it-ebooks.info dive In A Quick Dip class Exercise1b { public static void main(String I] arqs) { int x = 1; while ( x < 10 ) x=x+l; if ( x > 3) { A System.out.println("big x")j e Magnets:__~ss Shuftlel {~~lic static void main(String (J args) { This will compile and run (no output), but } without Q line added to the program, itint x = 3; would run forever inan infinite while loop! ....nile (x > 0) {i f (x > 2) {Systern.out.print(Ua")i class Foo {} public static void main(String I] args) { x = x - Ijint x = s; System.out.print("-");while ( x > 1 ) x =x - Ii i f (x == 2) {B if ( x < 3) {systern.out.print(Nb e")j system.out.println("small x");} i f (x == 1), { This file wont compile without 0Systern.out.print("d")j} class d~c1Qratlon, and dont forgetx = x - Ij ) the matching curly brace!} } class Exerciss1b { public static void main(String Uargs) { int x = Sj j a v a Shuffle! while ( x > 1a- b c - dx .. x - 1; Cif ( x < 3) System.out.println(~smallX]i The while loop code must be in- } side a method. It cant just be hanging out inside the class.you are here ~ 25 50. www.it-ebooks.infopuzzle answersfFIV-PJ sL 0 0 p A V A R,,- -UW .E-I-B D ItVIS B R A IN C HA "-l A1: N T0 AI --- It YL M R ts y s ir 8 E M au T P Rr N T L. Iclass PoolPuzzleOne {public static void main(String (] args) {- T AA-I- L -AB ~M ~ int x == 0; 18 S T R I N G9 D E C L A Re while ( X 4 ) { I R E Tf-- f-- ~JSystem.out. prlntfQ); C------Hif ( x < 1 ) { V0 System.out.prirrt( "): 11 C 0 M M A N D}System.out .prlrrt(n");class Tesc I public scat:ic void main (Scr ing [ 1 args) (if(X>l){ i n c l< ~ 0;i n c y - 0;wh i Ie( x < 5 l (System.out. prfnt( oyster");x=x + 2;}i f ( x == 1 ) { Syscern .ou c.print( x -" y .- "I;x = x + 1;System. out. prfnt(noysj;}if ( X 1 ) { """slble output:Systln. out. prlnt(olsej;}System.out.println(UU);X =X + 1;y j ava PoolPuzzl c One} Ct noise } anno~s}ano ~s t e r32 U 53 .I.f I Y < 5 )II - X + 1,UIy 0 ) { I have behaviors. object, class e2.count = e2.count + e1.count; I am located in objects.method, instance variable}x = x + 1; I live on the heap. object}I am used to create objectSystem.out.println(e2.count);instances.class}}My state can change.object, instance variable I declare methods.classclass Echo {int count = 0; I can change at runtime.object, instance variablevoid hello( ) {System.out.println(helloooo... );Note: both classes and objects are said to have state and behavior.}Theyre dened in the class, but the object is also said to have}them. Right now, we dont care where they technically live.File Edit Window Help Assimilate%java EchoTestDrivehelloooo...helloooo...helloooo...helloooo...10you are here447 72. www.it-ebooks.info3 primitives and references Know Your VariablesVariables come in two flavors: primitive and reference.So far youveused variables In two places-as object state (instance variables), and as local variables(variables declared within a method) . Later, well use variables as arguments (values sent to amethod by the calling code), and as return types (values sent back to the caller of the method).Youve seen variables declared as simpie prj m IUve integer vaIues (type in c). Youve seenvariables declared as something more complex like a String or an array. But theres gotta bemore to life than integers, Strings, and arrays.What If you have a PetOwner object with a Doginstance variable? Or a Car with an Engine? In this chapter well unwrap the mysteries of Javatypes and look at what you can declare as a variable, what you can pur In a variable, and what youcan do with a variable. And well finally see what life Is truly like on the garbage-collectible heap.this Is a new chapter 49 73. www.it-ebooks.infodeclaring a variable Peclarittg avariable Java cares about type. It wont let you do something bizarre and dangerous like stuff a Giraffe reference into a Rabbit variable-what happens when someone tries to ask the so-called Rabbit to hop ()? And it wont let you put a floating point number into an integer variable, unless you lKknowledge to thecompiler that you know you might lose precision (like, everything after the decimal point). The compiler can spot most problems: Rabbit hopper = newGiraffe(); Dont expect that to compile. Thankfully . For all this type-safety to work, you must declare the type of your variable. Is it an integer? a Dog? A single character? Variables come in two flavors: primitive and object reference. Primitives hold fundamental values (think: simple bit patterns) including integers, booleans, and floating point numbers. Object references hold. well, references to objects (gee, didnt that clear it up.) WeUlook at primitives first and then move on to what an object reference really means. But regardless of the type, you must foUow two declaration rules:variables must have a type Besides a type, a variable needs a name, so that you can use that name in code.variables must have a name int count;;?1 14) { System ,out.println("RUff! Ruff!");else (System.out.println("Yip! Yip!-);~: = s sDogTestDrive {pub li c static void main (String! J args) { Dog one = new Dog(); one.size= 70; Dog two = new Dog(); two ,size = 8; Dog three = new Dog(); three.size=35;~ ~ j ava DogTestDrive one. ba rk () ; Wooof! Wooof I two.bark () ; lip! Yip! three.bark/); Ruff! Ruff! you are here. 73 96. www.it-ebooks.infomethod parametersYou can send things to a tttethodJust as you expect from any programming language, you aU1 pass values intoyour methods. You might, for example, want to tell a Dog object how many times to bark by calling:d.bark(3) ;Depending on your programming background and personal preferences,you might use the term arguments or perhaps paramet.ers for the values passedin to a method. Although there emformal computer science distinctions thatpeople who wear lab coats and who will almost certainly not read this book.make. we have bigger fish to fry in this book. So yuu can call them whateveryou like (arguments, donuts, hairballs, etc.) but were doing it like this:A method ~ parameters. A caller passes arguments.Arguments are the things you pass into the methods. An argument (a valuelike 2, "Faa", or a reference to a Dog) lands face-down into a... wait for it..parameter. And a parameter is nothing more than a local variable. A variablewith a type and a name, that can be used inside the body of the methodBut heres the"important part: If a method takes a parameter, you mustpassit something. And that something must be a value of the appropriate type. Dog d= newDog() ; Call the bark method on the Dog refer- O ence, and pass in the value 3 (as the d.bark(3) ; argument to the method). ~ aY~~",e~t.A The bits representing the intW value 3 are delivered into thebark method.P~,"d_~,"l:>. A V The bits land in the numOfBarks parameter (an int-stzec variable).~ invoid bark (int numO arks) {Use the numOfBarkswhile (numOfBarks > 0) {O parameter as a variable inthe method code.System.out.println("ruff");numOfBarks = numOfBarks - 1; } }74 chapter 4 97. www.it-ebooks.info methods use instance variablesYou ca., get thi.,gs backfrottt a lMethod. ods can return values. Every method is declared with a return . but until now weve made all of our methods with a void type, which means they dont give anything back.re can declare a method to give a specific type of valueto the caller, such as: ~giveSecret () return 42; declare a method to return a value, you musta value of the declared rypel (Or a value . (()mpatiblewith the declared type. Well get at more when we talk about polymorphism pter 7 and chapter 8.)atever you sayII give back, you tter give back! t - life. giveSecret () ;giveSec et () {return 42-t,nis "~ ~it.}. tJill aWl WI...you are here ~ 75 98. www.it-ebooks.info.multiple argumentsYou can send ",ore than one thingto a tMethodMethods can have multiple parameters. Separate themwith commas when you declare them, and separate thearguments with commas when you pass them. Mostimportantly, if a method has parameters, you must passarguments of the right type and order.Call1"Q a two-paralMeter IMethod, altd seltdh,gIt two arQuIMe"ts.void qo () { TestStuff t = newT8Ststuff()i t.takeTwo(12, 34); lnt z = xvoid takeTwo(int x, int y) + y;( Systam.out.prinUn ("Total. is "+ z); . )You ca" pass variables hto a IMethod, as lo"c.1 asthe variable type IMatches the paraIMefer type.void qoO ( int faa = 7; int bar = 3; t. takeTwo (foo, bar);~void takeTwo(int x, int y) int z ... x + Yi System. out . println ("Total isrr + z);76 chapter 4 99. www.it-ebooks.info methods use instance variablesJava is pass...by...value. =That tMea"s pass"by"copy.----- int x = 7;int O the valuean7.in~nd assign7it DeclareThe bit pattern for goes into the variable named x.void go(int z){ }~intAiii Declare a method with an int parameter named z.f t Call the goO method, passingWthe variable x as the argument. The bits in x are copied, and the copy lands in z. intintfoo.go(x) ;void qo(int z){ } liteVb dots,,f.,~ ~ d~. f thci113 4:1 ., ~. . . . a.,.d~~t~g L. jJ.. dft":-: tf AVChange the value of z insidethe method. The value of xdoesnt change! The argument > 60) System .out.println("wooof! Wooof!");else i f (size> 14) ( Syscem.out.princln("Ruff!Ruff!");else ( System .out.println( "Yip! Yip!");I.Any place where aparticular value can class GoodDogTestDrive Ibe used, a method call that returns that public static void main (String!) args) ( type can be used.GoodDog one= new GoodDog();one .setSize(70);GoodDog two= new GoodDog(); Instead of:two.setSize(8); int x =3 + 24;System .out.printlnI WDog one: + one.getSize(; you can say: System.out.printlnl"Dog two: " + tWQ.getSize(; int x =3 + one.gdSize(); one. bark ();two. bark () ;82 chapter 4 105. www.it-ebooks.infomethods use instance variablesHow do objects I" a" arrayhave? like any other object. The only difference is. you get to them. In other words, how you getremote control. Lets try calling methods onobjects in an array.Declare and create a Dog array,to hold 7 Dog references.Doq[] pets;pets = new Doq[7]; Dog array object (Dog[]) Dog[]Create two new Dog objects.and assign them to the firsttwo array elements.pets [0] = new Dog () ;pets[l] = new Dog();Call methods on the two Dogobjects.pet8[O].setSize(30) ;int x= pets[O] .qetsize();peta[l) .setSize(8); Dog array object (Dog[])Dog[]you are here ~ 83 106. www.it-ebooks.infoInitializing instance variablesPeclarfttg and initializingittstatlce variables Instance variablesYou already know that a variable declaration needs at least a nameand a type : always get a int size; default value. If String name; you dont explicitlyAnd you know that you can initialize (assign a value) to the assign a valuevariable at the same time: to an instance int size =420; String name="Donny"; variable, or you dont call a setterBut when you dont initialize an instance variable, what happenswhen you call a getter method? In other words, what is the value of method, thean instance variable bejoreyou initialize it?instance variabet,alll.t IIayia,es, still has a value! class PoorDog ( dttaCt t..,o i~ ~ IIalw... / } :l",t. d()t t. a~I~1integers 0 private 1nt size; k~ private String name;floating points0.0 What will -tnue: Cd!.,",??booleans false P)ubliC int getsize ()(~return size; Ifreferences null public String getName ()(return name;, Y.-? y.l public class PoorDogTestDrive { ~:, ~o ~O" t.~j , public static void main (String [] args) (/ . "1 t,O"~ PoorDog one= new PoorDog () ; .!. ~~ e ) System.out.println("Dog size is " + one.getSize(); System.out.println("Dog name is " + one.getName(); % java PoorDogTestDrive Dog size is 0 Dog name is null84 chapter 4 107. www.it-ebooks.infomethods use instance variablesfhe differet1ce betwee" it1sfat1ceat1d local variables o Instancevariables are declared inside a class but not within a method. Local variables doclass Horse (NOT get a default private double height 15.2; value! The compiler private String breed; II more code . . .complains if you try to use a local variable before e Local variables are declared within a method. the variable is initialized.class AddThing { iot a; int b = 12; public iot add() {int total = a + b;return total;Q: What about method parameters?How do the rules about local variablesapply to them?A: e Local variables ~UST be initialized before uselMethod parameters are virtually thesame as local variables-theyre declaredInside the method (well, technically theyredeclared in the argumenr ltst of the method class Foo { "Ie" Yov. u~rather than within the body of the method,public void go () W()l t to"t~ ~ a Ja~, (Ln tx; deda ye Yo WI 0b-1 nl.&t. as $CO as f~ .but theyre still local variables as opposed toInstance variables). But method parametersLrrt z = x + 3;to ~ it, ~e l.oftn the heap. Easy as well, jusl usetwo primitives,the == operator. But sometimes you want to know if two objects are equal.or to see if twoAnd for that, you need the .equals 0 method. The idea of equality forreferences refer toobjects depends on the type of object. For example, if two different Stringthe same object.objects have the same characters (say. "expeditious"), they are meaningfullyequivalent, regardless of whether they are two distinct objects on the heap. Use the equalsOBut what about a Dog? Do you want to treat two Dogs as being equal if they method to seehappen to have the same size and weight? Probably not. So whether twodifferent objects should be treated as equal depends on what makes sense for if two diHerenfthat particular object type . Well explore the notion of object equality againobjects are equal.in later chapters (and appendix B), but for now, we need to understand that(Such as two differentthe == operator is used emly to compare the bits in two variables. What thoseString objects that bothbits represent doesnt matter. The bits are either the same, or theyre not. represent the characters In "Freel")To compare two primitives, use the == operatorThe = operator can be used to compare two variables of any kind, and itsimply compares the bits.if (a = b) {...j looks at the bits in a and b and returns true if the bit patternis the same (although it doesnt care about the size of the variable, 50 all theextra zeroes on the left end dont matter). ~~ 0" )(~ oVe u( t in t Ii = 3; byte b i f (a = 3;== b) { II tl:Ue } (t.t.t( aye." J t"e iYl ,rt ~de.lc.he tJ( ,~t. Ole o.~ t.hat n((e) , L~t t. (.4(e 61l . a-- int-- byteTo see If two references are the same (which means theyrefer to the same object on the heap) use theoperator==Remember, the == operator cares only about the pattern of bits in thevariable. The rules are the same whether the variable is a reference orprimitive . So the == operator returns true if two reference variables refer tothe same objectl In that case, we dont know what the bit pattern is (becauseit s dependent on theJVM, and hidden from us) but we M know that whateverit looks like, it wiU be the samefor two refmrues to a singleobject. Foo a = new Foo(); Foo b = new Foo(); Foo c = a; if (a == b) { II false }Foo a=t.ish"oI.e if (a -- c) ( II true ) a = b is .falst i f (b --c) ( II false ) FooFoa86 chapter 4 109. www.it-ebooks.info methods use Instance variables Make ,t st,tkRoses are red,this poem ischopPY,passing byvalue .;s passing by copy, 1 it.Replace ourcan do better? rJ 8e~ryet.Oh,like yoU d llne with your ow" wn wOld~dumb seconI thing with YOUl 0 theY/ho ereplace forget it. a"d youll neverint a " calcArea(7, 12); Whats legal?Given the method below, whichKEEPshort c " 7;of the method calls listed on theright ore legaltPut a checkmcrk next to the+-RIGHTcalcArea (c,15) ;int d " calcArea(S7);calcArea (2,3) ;ones that are legal. (Somestatements are there to assignlong t " 42;values used in the method colis).int f = calcArea(t,17);int 9 " calcArea();int calcArea(int height, int width) calcArea () ; return height width; byte h = calcArea(4,20);int j = calcArea(2,3,5);you are here ~ 87 110. www.it-ebooks.infoexercise: Be the Compiler BE the oomriler Each ofthe Java files on this page represents a complete source file.Your joh is to play colllliler anddetermine whether each ofthese fileswill compile. If they wont compile. how would you rIX them, and if they do c011lpile. what would hetheir outputi ABclass XCopy { class Clock {String time;public static void main(Strinq [) arqs) {void setTime(String t)int orig = 42;time = t jXcopy x = new xCopy();int y : x.go(orig)j void getTime()return time;System.out.println(orig + U U + y); }int go(int arg)class ClockTestDrive {arg = arg * 2;public static void main(String (] args) {return arg; Clock c = new Clock();}}c.setTime(U124S n ) jString tad = c.getTime()iSystem.out.println(Utime: u + tod)j88 chapter 4 111. www.it-ebooks.infomethods use instance variables A bunch of Java components, in full costume, are playing a party game, Wha am W They gille you a clue, and you try to guess who they are, based on what they say.Assume they always tell the truth about themselves. If they happen to say something that could be true for more tha n on e guy, then write down all fa r whom that sentence applies. Fill In the blanks next to the sentence with the names of one or more attendees. Tonights attendees: Insta nee variable, argument, return, getter, setter, encapsulation, public, private, pass by value, methodA class can have any number of these.A method can have only one of these.This can be Implicitly promoted.I prefer my Instance variables private.It really means make a copy.Only setters should update these.A method can have many of these.I return something by definition.I shouldnt be used with instance variables.I can have many arguments.By definition, I take one argument.These help create encapsulation.I always fly solo. you are here.89 112. www.it-ebooks.infopuzzle: Mi)(ed MessagesMixed Messages A short Java program Is listed to your right.public class Mix4 ( Two blocks of the program are missing. Your challenge Is to match the candIdate int counter = OJ blocks of code (below) , with the output public static void main (String [) args) ( that youd see if the blocks were Inserted.int count = 0; Not all the lines of output will be used, andMix4 [) m4a =new Mix4[20lj some of the lines of output might be usedint x = 0; more than once. Draw lines connecting the candidate blocks of code with their matching command-line output.while(II) m4a [x] = new Mix4 (); m4a(x] . counter = m4a(xl .counter + 1; count count + 1; count count + m4a[x) .maybeNew(x); x = x + 1;System. out.println(count + ~ " + m4a[1) .counter);CandIdates:Possible output: x < 9public iot maybeNew(int index) index < 5 ,!if(I I) ( Mix4 m4 = new Mix4(); x < 20m4.counter = m4.counter + 1; return 1; index < 5.~return 0; x 0) { result = result + __Output } system.out.println("result " + result); } } class { int ivar;_____ doStuff(int) { if (ivar > 100) { return_ } else {- return }--------------------- } }Note: Eachsnippet"om the pool can beused only oncel you are here) 91 114. www.it-ebooks.infopuzzle: Five Minute MysteryFast TImes in Stim-Clty When Buchanan jammed his twitch-gun into Jais side , Jai froze. Jai knew that Buchananwas as stupid lis he was ugly and he didnt want to spook the big guy. Buchanan ordered Jaiinto his bosss office, but Jaid done nothing wrong, (lately), so he figured a little chat withBuchanans boss Leveler couldnt be too bad. Hed been moving lots of neural-stimmers inthe west side lately and he figured Leveler would be pleased. Black market stimmers werentthe best money pump around, but they were pretty harmless. Most of the slim-junkies hedseen tapped out after a while and got back to life, maybe just a little less focused than before.Levelersofficewas a skungy looking skimmer, but once Buchanan shoved him in, Jaicould see that itd been modified to provide aIL the extra speed and armor that a local boss likeLeveler could hope for. "Jai my boy", hissed Leveler, "pleasure to see you again". "LikewiseIm sure...", said Jai, sensing the malice behind Levelers greeting, "We should be squareLeveler, have r missed something?" "Ha! Youre making it look pretty good Jai, your volumeis up, but Ive been experiencing, shall we say, a little breachlately..." said Leveler. Jai winced involuntarily, hed been a top drawer jack-hacker in his day. Anytime someone .figured out how to break: a street-jacks security, unwanted attention turned toward Jai, "Noway its me man", said Jai, "not worth the downside. Im retired from hacking, [just move my stuffand mind my own business", "Yeah, yeah", laughed Leveler, "Im sure youre clean on this one, but Ill be losing big margins until this new jack-hacker is shut out!" "Well, best of luck Leveler, maybe you could just drop me here and Ill go move a few more units for you before I wrap up today", said Jai. "Im afraid its not that easy Jai, Buchanan here tells me that word is youre current on 137NE", insinuated Leveler. "Neural Edition? sure I play around a bit, sowhat?". Jai responded feeling a little queasy. "Neural editions bow I let the stim-junkiesknow where the next drop will be", explained Leveler. "Trouble is, some srim-junkies stayedstraight long enough to figure out how to hack into my WareHousing database." "I need aquick thinker like yourself Jai, to take a look at my StimDrop 137NE class; methods, instancevariables, the whole enchilada, and figure out how theyre getting in. It should..", "HEY!",exclaimed Buchanan, "I dont want no scum backer like Jai DOSin around my code!" "Easybig guy", Jai saw his chance, "Im sure you did a top rate job with your access modi .. "Donttell me - bit twiddler!", shouted Buchanan, "1 left all of those junkie level methods public,so they could access the drop site data, but 1 marked all the critical WareHousing methodsprivate. Nobody on the outside can access those methods buddy, nobody!" "I think I can spot your leak Leveler, what say we drop Buchanan here off at the comerand take a cruise around the block", suggested Jai. Buchanan reached for his twitch-gun butLevelers stunner was already on Buchanans neck, "Let it go Buchanan", sneered Leveler,"Drop the twitcher and step outside, I think Jai and I have some plans to make", What did Jai suspect?Will be get out of Levelers skimmer with all his bones intact?92 chapter 4 115. www.it-ebooks.infomethods use Instance variables class Clock String time; void setTime(~tring t) { time:: t; B } String getTime ( ) return time; } class ClockTestDrive { public static void main(String rl args) { Clock c = new Clock(); c.setTime(R124S R ) j String tod = c.getTime(); System.out.println(Utime: + tod); } Note: Getter methods have a returnXCopy compiles and runs as it stands I Thetype by definition. 84. Remember Java is pass by value, (which copy), the variable orig is nol changed by thedass can have any number of these.Instance varl~bles, getter, utter,method method can have only one of these. returnIcan be implicitly promoted. return. argumentprefer my instance variables private. encapsulationreally means make a copy. pass by valuesetters should update these.Instance variablesmethod can have many of these.o.rgt.llnentreturn something by definition. gettershouldnt be used with instance variables publiccan have many arguments.methoddefinition, , take one argument.setter se help create encapsulation.getter. stter, public. privatealways fly solo . return you are here.93 116. www.it-ebooks.infopuzzle answersPuzzle SolutionsAnswer to the 5-minute mystery...pUblic class Puzzle4 (Jai knew that Buchanan wasnt the sharpestpublic static void main(String [] args) { pencil in the box. When J ai heard BuchananPuzzle4b [ ] ebs =new Puzzle4b[6J;talk about his code, Buchanan never mentionedint y - 1;his instance variables. Jai suspected thatint K .. 0, while Buchanan did in fact handle his methodsint result = 0:correctly, he failed to mark his instance variableswhile (x < 6) (private. That slip up could have easily costobs[x) =new PU2zle4b( ):Leveler thousands.obs[x) . ivar =y;y - y .. 10;x=> 0) {x =x-I;result = result + obs[x].doStuff(x):Candidates:Possible output:System.out.println("result u + result); x < 9}index < 5class Punle4b {1nt ivar,public int doStuff (int factor) x < 20if (ivar > 100) { return ivar * factor;index < 5else {return ivor" (5 - factor); Outputx < 7 q java Puzzle4index < 7 result 543345x < 19index < 194chapter 4 117. www.it-ebooks.info5 writing a programExtra-Strength Methods Lets put some muscle In our methods.We dabbled with variables, played with a few objects, and wrote a little code. But we were weak.We need more tools. Like operators. We need more operators so we can do something a little more interesting than, say, bark. And loops. We need loops, but whats with the wimpy while loops? We need 10, loops jfwere really serious. Might be useful to generate random numbers. And turn a String Into an Int, yeah, that would be cool. Better learn that too. And why dont we learn It all by building something real, to see what its like to write (and test) a program from scratch. Maybe a game, like Battleships. Thats a heavy-lifting task,so Itll take two chapters to finish .Well build a simple version in this chapter, and then build a more powerful deluxe version in chapter 6. this is a new chapter 95 118. www.it-ebooks.infobuilding a real gameLetls build a Jattleship.. stylegattte: "Sitdc a Pot COtttNIts you against the computer, but unlike the realBattleship game, in this one you dont place any ships Youre going to build theof your own. Instead, your job is to sink the computers Sink a Dot Com game, withships 0 the fewest number of guesses. a 7 x 7 grid and threeOh, and we arent sinking ships. Were killing Dot Dot Coms. Each Dot ComCorns. (Thus establishing business relevancy so you can takes up three cells.expense the cost of this book).Goal: Sink all of the computers Dot Corns in the fewestnumber of guesses. Youre given a rating or level, basedon how well you perform.part of a galMe it1feraetlottSetup: When the game program is launched, thecomputer places three Dot Corns on a virtual 7 x 7 ..grid. When thats complete, the game asks for your first %j ava OotComBustguess. Ent e r a guess A3How you play: We havent learned to build a CUI yet, somi s sthis version works at the command-line. The computerwill prompt you to enter a guess (a cell), that you U typeEnt e r a guess 82at the command-line as ~A.3", "C5", etc.). In response mi s sto your guess, youll see a result at the command- Ent e r a guess C4line, either "Hit", "Miss", or "You sunk Pets.corn" (orwhatever the lucky Dot Com of the day is). Whenmi s syouve sent all three Dot Cams to that big 404 in theEnt e r a guess 02sky,the game ends by printing out your rating. h it tat.-. oo~~"7 )< "7 ~r-id,s a "t.t Ent e r a guess 03 hit A k Enter a guess 04 B Ouch! You sunk Pets. com E C 5kill ~ e Enter a guess B4 D P4 ts.cc m miss E Enter a guess G3 F hit Enter a guess G4 GI Asi Me.c pmhit o12 3 4 56Enter a guess GS Ouch! lou sunk AskMe.com- shr-h at. ut"o, like Java dnays96 chapte r 5 119. www.it-ebooks.info writing a programFirst a high.. level desigtt e know well need classes and methods. but whatuld they be? To answer that, we need moreform ation about what the game should do.First, we need to figure out the general flow of thezame. Heres the basic idea: oUser starts the gameo Game set-upGame creates three Dot Comso Game places the three DotColTlS onto a virtual gridGame play beginshitRepeat the following until there areno more Dot Coms:A Prompt user for a guess1W ("2, CO, etc.). ) remove(0Check he user guess oga;nstall Dot Coms to look for a hit,Dot Commiss, or kill. Take appropri-ate action : if a hit, delete cellAdiallOfd(A2, D4, etc.). If a kill, delete yt:f""~lb aDot Com.dt:t.isiOl ~OltGame finishesGive the user a rating based ondisplay userthe number of guesses. score/rating~ ow wehave an idea of the kinds of things therogram needs to do. The next step is figuringut what kind of objects well need to do thelooork. Remember, think like Brad rather thanLarry; focus first on the things in the programra the r than the jrroredures. Whoa. A real flow chait.you are here.97 120. www.it-ebooks.infoa simpler version of the gameNfhe "SitMple Pot CO" .alltea get1tler it1troductiot1It looks like were gonna need at least two classes, aGame class and a DotCom class. But before we buildo6arM starts, and creates ONE DotCom and gives it a location on three. cells in the single row of seven cells. Instead of A2", C4", and 50 on, thethe fuJI monty Sinh a Dot Com game, well start with locations are just integers (for example :a stripped-down. simplified version, Simple Dot Com1,2,3 are the cell locations in thisGame. Well build the simple version in this chapter,picture:followed by the deluxe version that we build in thenext chapter.Everything is simpler in this game , Instead ofa 2-Dgrid, we hide the Dot Com injust a single TOW. And o 1 23 4 5 6instead of three Dot Corns, we use one. 6a1U play begins. Prompt user forThe goal is the same, though, so the game still needsa guess, then check to see jf it hitto make a DotCom instance, assign it a locationany of the DotComs three cells .somewhere in the row, get user input, and when all If a hit , increment the numOfHitsof the DotComs cells have been hit, the game is over, variable.This simplified version of thegame gives us a big head start SlmpleDotCom Game6ame finishes when all three cells haveon building the full game.been hit (the numOfHits variable vel- ~ue is 3), and tells the user how manyIf we can get this small oneSlmpleDofComguesses it took to sink the DotCom.working, we can scale it up tothe more complex one later.Inl 0localionCellsvoId mail Intnum01Hl1sIn this simple version, thegame class has no instancevariables, and all the gameString checkYou~If(Strilg guess)code is in the main () method, void SetlocallonCellsQntO loe)In other words, when theprogram is launched andmain () begins to run, it willmake the one and only DotCominstance, pick a location for it ( threeconsecutive cells on the single virtualseven-cell row), ask the user for a guess, check theguess, and repeat until all three cells have been hit.Keep in mind that the virtual row is... virtual: In otherwords, it doesnt exist anywhere in the program . Aslong as both the game and the user know that theDotCom is hidden in three consecutive cells out ofapossibe seven (starting at zero) , the tOW i.tself doesnthave to be represented in code. You might be temptedto build an array of seven ints and then assign theDotCom to three of the seven elements in the array,but you dont need to. All we need is an array thatholds just the three cells the DotCom occupies.98chapter 5 121. www.it-ebooks.infowriting a programPevelopit1Q aClassfhe three thlt19S we~1I wrIte for_ a programmer, you probably have a methodology/each class: ess/approach to writing code. Well. so do we. Oursequence is designed to help you see (and learn) what re thinking as we work through coding a class. Itt necessarily the way we (or you) write code in the World. In the Real World, of course, youll followThis bar Is displayed on the next set of pages to tellapproach your personal preferences, project, oryou which part youre working on. For example, if youployer dictate. We, however, can do pretty muchsee this picture at the top of a page. it means youre working on prepcode for the SimpleDotCom class.tever we want And when we create aJava class as a rning experience", we usually do it like this:SlmpleDolCom class ~D Figure out what the class is supposed to do.D List the Instance variables and methods.prep codeD Write prepcode for the methods. (Youll see A form of pseudocode. to help you focus onthis in Just a moment.) the logic without stressing about syntax.D Write test code for the methods.test codeD Implement the class.A class or methods that will test the real codeand validate that its doing the right thing.o Test the methods.o Debug and relmplement as needed.rea I code The actual implementation of the class . This iso Express gratitude that we dont have to test _ _- - - -.....al Java code.our so-called learning experience app onTo DO.:actuallJve users.smpeDotCOm claSSo write prep codeo write test codeo write final Java code s,mpeDotCOmoameFlex those dendrftes.ciaHow would you decide whIch class or classeso write prep codeto build first, when youre writIng a program? write test code {nolAssuming that all but the tiniest programsneed more than one class (If youre followingowrite final Java codegood 00 principles and not having one classdo many different Jobs), where do you start? you are here.99 122. www.it-ebooks.infoSimpleDotCom class You11 get the idea of how prepcode (our version of pseudocode) works as you read through this example. Its sort of half-way between real Java code and a plain SlmpleOolCom English description of the class. Most prepcode includes three parts: instanceilll 0IocaIiooCelIsinlnumOft-lils variable declarations, method declarations, method logic. The most important part of prepcode is the method logic, because it defines what has to happen,String checkYourself(string guess) which we later translate into hotu; when we actually write the method code.void selLoca~onCells{inlj) lot) DECLARE an int array to hold the location cells. Call it loeatJonCells. DECLARE an int to hold the number of hits.Call it numOfHits and SET it to O. DECLARE a checkYourset(() method that takes a String for the users guess (" I", "3", etc), checks it. and retums a result representing a "hit", "miss",or "kill", DECLARE a setLocationCeJ/sO setter method that takes an int array (which has the three cell locations as ints (1.3/1, etc.). METHOD: String checkYourself(String userGuess)GET the user guess as a String parameterCONVERT the user guess to an intREPEAT with each of the location cells in the int array II COMPARf the user guess to the location cellIF the user guess matches INCREMENT the number of hits II FIND OUT if it was the last location cell: I F number of hits is 3, RETt,JRN "kill" as the result ELSE it was not a kill. so RETURN"hit"[ END IFELSE the user guess did not match, so RETURN "miss"END IFEND REPEAT END METHOD METHOD: void setLocotJonCe//$(lnt[] eel/Locations)GET the cell locations as an in! array parameterASSIGN the cell locations parameter to the cell locations instance variable END METHOD100chapter 5 123. www.it-ebooks.info writing a programWriting the tttethodhMpletM8ntations lets write the real ...ethod code ttOW, ittd get this puppy worklttg.Before we start coding themethods, though, lets backup and write some code totest the methods. Thats right,were writing the test code1M/ore theres anything to testl The concept of writingthe test code first is one ofthe practices of Extreme Programming (XP), and it can make it easier (and faster) for you to write your code. Were not necessarily saying you should use XP, but we do like the part about ....Tiling tests first. And XP just sounds cool. Extreme Programming (XP)Extreme Programming(XP) Is a newcomer to the software Dont put in anything thats not in the spec (no matter evelopment methodology world.Consld ered by many how tempted you are to put In functionality "for thet be "the way programmers really want to work ~ XPfuture) .e erged In the late 90s and has been adopted byWrite the test cod e first .ompanies ranging from the two-person garage shopthe Ford Motor Company. The thrust of XP is that theNo killer schedules;work regular hours.sterner gets what he wants, when he wants It, evenRefactor (improve the code) whenever and wherever you en the spec changes late In the game.notice the opportunity. is based on a set of proven practices that are all Dont release anything until it passes all the tests. esigned to work together, although many folks do pickand choose, and adopt only a portion of XPs rules. These Set realistic schedules, based around small releases. ctices include things like:Keep it simple. ke small, but frequent, releases.Program in pairs, and move people around so thatvelop in Iteration cycles.everybody knows pretty much everything about the code . you are here ~ 101 124. www.it-ebooks.infoSlmpleDotCom classprepcode Writh1Q test code for the Shttp[eUoiColM class We need to write test code that can make a SimpleDotCom object and run its methods. For the SimpleDotCom class. we really care about only the cMckYourselj() method, although we will have to implement the sdLocatiun~l1s()method in order to get the cMckYourself() method to run correctly. Take a good look at the prepcode below for the checkYourselj() method (the setLocaticmCells() method is a no-brainer setter method, so were not worried about it. but in a real application we might wan I a more robust setter method. which we wouldwant to test). Then ask yourself, "If the checkYourselfO method were implemented. what test code could I write that would prove to me the method is working correctly?"ased Ott this prepcode:Here1s what we should test:METHOD String checkYourselffString userCuess)1. Instantiate a SlmpleDotCom object. GET the user guess as a String parameter2, Assign It a location (an array of 3 ints, like CONVERT the user guess to an Int {2,3.4}). 3. Create a SlJing to represent a user guess REPEAT with each of the location cells in the Int array(2", 0, etc.)./I COMPARf the user guess to the location cell 4.Invoke the checkYourselfO method pass-IF the user guess matches ing il the fake user guess. INCREMENT the number of hits5. Print out the result to see If Its correct/ / FIND OUT if it was the last location cell:("passed" or "failed"). IF number of hits is 3. RETURN "Kill" as the result ELSE it was not a kill, so RETURN"Hif END IFELSE the user guess did not match, so RETURN "Miss"END IF END REPEATEND METHOD102 chapter 5 125. www.it-ebooks.info writing a program ~relare,..{l? "fest code for the SIIMpiePotCoIM classDiiJjjo ~uestl9nsQ..:Maybe Im missing some- public class SimpleDotComTestDrive (....sta"ba-tl. ahere, but how exactly do~....yeDa:.e,o...run a test on something public static void main (S trinq [ ] arqs) ( do~et,t.. . doesnt yet existI1SimpleDotcom dot = new SimpleDotCom ();t::": You dont. We never said start by running the test; .".at.-e 0" "~t.il:l01 ~oY-:.be Got.&e ot.WOl vb~e ,,,b O>t. C, ~1ot 1) start by writing the test. At------ t.o"" . e you write the test code, int [] locations = {2 I 3 I 4}; VJ a YsJ. wont have anything to run,against. so you probably wont dot.setLocationCells(locations); .Ie to compile It until you~e st ub code that can com- .--..,.,tih tJ.. e ~tn-...oIc e .....L bu t that will always cause od 0,. the dot. to .... est to fail (like, return null.)"",Itt 0 ~ akeString userGuess = "2 H; ~~tv"~~:Then I stili dont see the..,rt. Why not walt until the String result = dot.checkYourself(userGuess);Is written, and then whip the test code? Strinq testResult = "failed" j ~i""oke 1:~e thetJcYoursel.fO _...1., m.evodon ille dot to... objttt, a"d Pdss if. illif (result. equals ("hi t") ) ( .fp, no "eed! I e nd i fs the other tells } II end f or/ / FIND OUT ifit. was t he last ee l! if (numOfHits == locationcells.length) (IF number of hitsis 3.result = "kill";RETURN "kili"as the result / ! end i fELSE it wasnot a kill. soRETURN "hit "System.out .println(result); ~ display the reslAlt.for the lASer ELSEreturn result;("Miss", lAllless it was tha"ged to "I-hi;" or "Kill")RETURN t"-. retlAr" the reslAlt bade to} IIend me thod the talli"9 ....ethod104chapter 5 127. www.it-ebooks.info writing a programe things we havent seen before on this page. Stop worryingl The of the details are at the end of chapter. This isjust enough to let keep going.Converting aString to an Intn ~ ++ ... taY1 add I toThe post-incrementoperator(WhaWtrS th&e (ill ~ Wc*d.s, int __ e",ent by ,).numOfHits++ roIArllOtlhh++ i.s the sa...t (ill this ~) as sayi,,~ "...... O.fits ::. """,o.f~hh +" e~rt sli9hUt ...~~ tHitient break statementbreak;~et.s y~ out o-f alOOf l......ediduly. Ri~ht htl"t. No ihl"atioll, no boolulI ust, iwt o.d out "ow!you are here ~ 105 128. www.it-ebooks.infoSlmpleDotCom classprep code:therelare~~"DUmb~uesti9115 public classS~leDotComTestDrive{Q..: What happens InInteger.pa rselnt(l If the thing youpubliC s t a t i c void main(S~ringl] args) {pau Isnt a number? And does ItSimpleDotCom dot~ new SimpleDotCom{};recognize spelled-out numbers, intI] locations ~ (2,3,4);/Ike Jl t hree"? dot , setLocationCells (locations) ;A:Intege r.parselntO wo rks onlyon Strings that represent the ascii String userGuess String result ~ ~ "2-; dot .checkYourself(userGuess);values for digits (0,1,2,3,4,5,6,7,8,9).If you try to parse something like"two" or "blurp; the code wi II blowup at runtime. (By blow up, weactually mean throw an exception,but we dont talk about exceptionsuntil the Exceptions chapter. So for public class SimpleDotComnow, blow up is close enough .)intI) locationCells ;int numOfHits ~ 0 ;Q..:ln the beginning ofthepUblic void setLocationCells(intl] locs) (book, there was an exam pie of alocationCells = locs;for loop that was really differentfrom this one-are there twodifferent styles of for loops?pUblic String checkYourself(String stringGuess)int guess ~ Integer.parselnt{stringGuess);String result - "miss ";A:YeSl From the first version offor (int cell : IocationCells)Java there has been a sIngle kindi f (guess ~ ~ cell) (of (or loop (explained later In this result = " h i t - ;chapter) that looks like this :numOfHits++; break;for (Int i = 0:/ < 10;1++) { )What should we see// do someth ing 10 timesI I out o f t h e l o op when we run this code?The test code makes a if (numOfHits == SimpleDotCom objectYou can use this format for any locationCells.length) and gives it a locat ion atkind of loop you need. But... result ~ "kill-;2,3,4 . Then it sends a fakebeginnIng with Java 5.0 (Tiger), )user guess of "2" Into theyou can also use the enhancedforSystem.out.println{result}; checkYouselfO method.loop (thats the official description) return result; If the code is workingwhen your loop needs to iterate) II clo se meth ocorrectly, we should see theover the elements In an array (or I I c l o e c Ia s result print out:another kind of collection, as youllsee In the next chapter). You canJava SlmpleDotComTestD r l vealways use the plain old for loop Theres a little bug lurking here. It complies end latto iterate over an array, but theruns. but sometimes ... dont WOffY aboulll for now,enhanced for loop makes it easier. but we will have to face it II little later,106 chapter 5 129. www.it-ebooks.infowriting a programWe built the test class, and the SimpleDotCom class.But we still haventmade the actua I game. Given the code on the oppos Ite page, and the spec forthe actual game, write In your Ideas for prepcode for the game class. Weve given The SlmpleDotComGameyou a few lines here and there to get you started. The actual game code is on the needs to do this:next page, so dont tum the page until you do this exerdsel 1. Make the singleYou should have somewhere between 12 and 18 lines (including the ones we wrote, SimpleDotCom Object.but not including lines that have only a curly brace). 2. Make a location for it (threeMETHOD publicstatic void main (String 0 OIJ:S)consecutive cells on a single DECLARE an int variable to hold the number of user guesses. named numOfGuessesrow of seven virtual cells). 3. Ask the user for a guess. 4. Check the guess. 5. Repeat until the dot com is dead . 6. Tell the user how many guesses it took.. COMPUTE a random numberbetween0 and "I that will be the starting location cell position WHILE the dot com IS ~i ll ahve : GET user input (rom the command lineyo u are here.107 130. www.it-ebooks.infoSlmpleOotCom classPrepcode for the ShMpleUofCottttatMe classEverythfng happetts Itt Ittal..nThere are some things youll have to take on faith. For example. we have oneline of prepcode that says, wCET user input from command-line". Let me tellyou, thats a little more than we want to implement from scratch right now, Buthappily, were using 00. And that means you get to ask some otherc1ass/objectto do something for you, without worrying about how it does it. When you writeprepcode, you should assume that somehoto youll be able to do whatever youneed to do, so you can put all your brainpower into working out the logic.public stadc voJd main (String D args) DECLARE an int variable to hold the number of user guesses. named numO(t;uesses. set it to O.MAKE a new SimpleDotCom instanceCOMPUTE a random number between 0 andthat will be the starting location cell position MAKE an int array with 3 ints using the randomly-generated number, that number incremented by I. and that number incre mented by 2 (example: 3.4,5) INVOKE the retLocOlionCeI!sO method on the SimpleDotCom instanceDECLARE a boolean variable representing the state of the game. named isAhve. SET it to trueWHILE the dot com is still alive (isAlive == true) : GET user input {rom the command line // CHECK the user guess INVOKE the checkYourse/fO method on the SlmpleDotCom instanceINCREMENT numO(t;uesses variable II CHECK (or dot com death IF result is "kill" SET isAlwe to false (which means we WOTl! enter the loop again) PRINT the Tlumberof user guesses END IF END WHILEEND METHODnl~ogn.itive ttlDont work one part of the brain for 100 long a stretch at one time.Working Just the left side of the brain formore than 30minules is like working lust your left arm for 30 minutes, Give each sideof your brain a break by swilchlng sides at regular intervals. . When you shift to one side. the other side gels 10 rest and recover. Left-brain actJvlties Include things like step-by-stepsequences, logical probem-solving, and analysis. while theright-brain kicks in formetaphors, creative problem-solving,pattern-matching, and Visualizing.108 chapter 5 131. www.it-ebooks.info writing a program -Your Java program should start with a high Choose forloops over while loops when you level design.know how many times you want torepeat theloop code.Typically youll write three things when you create a new class: Use the pre/post increment operator toadd 1prepcodeto a variable (x++;)testcode Use the pre/post decrement tosubtract 1 froma variable (x-;)real (Java) code Use Integer .parseInt() to get the intPrepcode should describe what to do, not how value ofa String. todoit. Implementation comes later. In teger . parseIn t () works only if theUse the prepcode tohelp design the testString represents a digit ("0":1,"2", etc.) code. Use break 10 leave a loop early (i.e. even ifWrite test code before you implement the the boolean test condition is still true). methods.How manyhits did you getlast month? you are here)109 132. www.it-ebooks.infoSimpleDotComGame classJust as you did with the SimpleDotCom class, be thinking about parts of this codeyou might want (or need) to improve. The numbered things are for stuffwewant to point out. Theyre explained on the opposite pag e. Oh, if you re wonder-ing why we skipp ed the test code phase for this class, we don t need a test class forthe game. It has only one method, so what would you do in your test code? Makea separate class that would call maini] on t~is class? We didnt bother. public static void main(String[] arqs) (DECLARE 3 var i-able to hold userguess count . set itGameBelper helper " new GameBelper (); e-r: this is a 1ft/.Ial t1ass role wv~ thdt hasto 0 t.he ...dhod +OY ~di,,~ ~ illf l< t.. +OYl""WlIG its part. ~ Java lOl objet+Com objec tCOMPUTE ,rando m num be rbe tween 0 and .int randomNum = (int) (Mat:.h.random() ... 5) ;b--lftedot tQtI ih lotdtiOtlS (th, C1Yril1)INVOKE seu.oca -[lonCells on the do tcorn ob jectboolean isAli va " true;DECLARE a boo l-eat" sAliveWHILE the dotco m 1 still aliveGET user inputII CHE.CK ItINVOKE checkro-ursell() on dot co mIN C R EM E N TnurnO fGuessesIF re ult is " kill"SET gameA live tofalsePRINT the numberof user gue sses II c l o s e if II c lose while- II close mainchap ter 5 133. www.it-ebooks.infowriting a programjf...ro things that need a bit more,:xplain ing. are on this page, This is. t a quick look to keep you going;re details on the GameHelperare at the end of this chapter. Make a random number(Math.random() " 5) t Atlau that tOflltstA... rthoci ok the wit.h Java.Mat.h daS$.An l"rl,arU wt "= 4), or youcan even Invoke a method that returns a boolean.Part Three: IteratIon expressionIn this part, put one or more things you want to happen with each trip throughthe loop. Keep In mind that this stoff happens at the end of each loop.114chapter 5 137. www.it-ebooks.infowriting a program output: sthrough a